-/*
- * ============LICENSE_START===========================================================
- * ====================================================================================
- * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
- * ====================================================================================
- * 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.
- * ============LICENSE_END=============================================================
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- */
\ No newline at end of file
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software 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.
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
+++ /dev/null
-.project
-/.settings
-# ECOMP Portal SDK
+# ONAP Portal SDK
-This is the parent Maven project for the following
-ECOMP Portal SDK child Maven projects:
+This is the parent Maven project for the following child Maven modules:
-* SDK Framework library
-* SDK Core library
-* SDK Analytics library
-* SDK Workflow library
-* SDK Common Application library
-* SDK Common Overlay Web Application
+* Portal SDK Framework library
+* Portal SDK Core library
+* Portal SDK Analytics library
+* Portal SDK Workflow library
+* Portal SDK Common Application library
+* Portal SDK Common Overlay Web Application
-This area also includes ECOMP Portal SDK web application projects
-for AT&T internal use and open source distribution, but they are
-not child Maven projects.
+This area also includes ECOMP Portal SDK web application projects.
Release notes are published in each project.
-# ECOMP Portal SDK Analytics
+# ONAP Portal SDK Analytics
## Overview
-This is the Maven project for the ECOMP Portal SDK Analytics library,
+This is the Maven project for the ONAP 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").
### ONAP Distributions
-Version 1.3.0
-- [Portal-19] Renaming the Group Id in the POM file to org.onap.portal.sdk
-- [PORTAL-58] Removing restricted image files under raptor
-- [PORTAL-60] remove CalendarPopup.js that's user for raptor schedule tab
+Version 1.4.0
+- PORTAL-19 Rename Java package base to org.onap
+- PORTAL-72 Address Sonar Scan code issues
+- PORTAL-42 Use OParent as parent POM
+- PORTAL-90 Use approved ONAP license text
+
+Version 1.3.0, 28 August 2017
+- Portal-19 Renaming the Group Id in the POM file to org.onap.portal.sdk
+- PORTAL-58 Removing restricted image files under raptor
+- PORTAL-60 remove CalendarPopup.js that's user for raptor schedule tab
+
Version 1.1.0
-- [Portal-7] Improvements added as part of the rebasing process
-- [PORTAL-17] Remove jfree related items
+- Portal-7 Improvements added as part of the rebasing process
+- PORTAL-17 Remove jfree related items
+
Version 1.0.0
- Initial release
<parent>
<groupId>org.onap.portal.sdk</groupId>
<artifactId>epsdk-project</artifactId>
- <version>1.3.0-SNAPSHOT</version>
+ <version>1.4.0-SNAPSHOT</version>
</parent>
<!-- GroupId is inherited from parent -->
<artifactId>epsdk-analytics</artifactId>
<!-- Version is inherited from parent -->
<packaging>jar</packaging>
- <name>ECOMP Portal SDK Analytics</name>
+ <name>ONAP Portal SDK Analytics</name>
<description>Provides analytics features for SDK applications</description>
<url>https://wiki.onap.org/display/DW/Portal</url>
+ <!-- properties are inherited from parent -->
+
<!-- repositories are inherited from parent -->
- <build>
- <plugins>
- <!--
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>license-maven-plugin</artifactId>
- <version>1.10</version>
- <configuration>
- <encoding>UTF-8</encoding>
- <licenseName>my_license</licenseName>
- <licenseResolver>${project.baseUri}/license</licenseResolver>
- <inceptionYear>2017</inceptionYear>
- <organizationName>AT&T Intellectual Property</organizationName>
- <projectName>eCOMP Portal SDK</projectName>
- <addJavaLicenseAfterPackage>false</addJavaLicenseAfterPackage>
- <processStartTag>================================================================================</processStartTag>
- <sectionDelimiter>================================================================================</sectionDelimiter>
- <processEndTag>================================================================================</processEndTag>
- <roots>
- <root>src/main</root>
- </roots>
- <excludes>
- <exclude>*.png</exclude>
- <exclude>*.drl</exclude>
- <exclude>*.gif</exclude>
- <exclude>*.jpeg</exclude>
- <exclude>*.jpg</exclude>
- <exclude>*.bmp</exclude>
- <exclude>*.ico</exclude>
- <exclude>*.svg</exclude>
- </excludes>
- </configuration>
- <executions>
- <execution>
- <id>first</id>
- <goals>
- <goal>update-file-header</goal>
- </goals>
- <phase>process-sources</phase>
- </execution>
- </executions>
- </plugin>
- -->
- </plugins>
- </build>
-
<dependencies>
<!-- sdk-core -->
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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;
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.config;
+
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+
+import org.onap.portalsdk.analytics.controller.*;
+import org.onap.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 raptorActionMapString =
+ "report.run |org.onap.portalsdk.analytics.controller.ActionHandler|reportRun |report_run.jsp \n"
+ + "mobile.report.run |org.onap.portalsdk.analytics.controller.ActionHandler|reportRun |mobile_report_run.jsp \n"
+ + "report.dashrep1.run |org.onap.portalsdk.analytics.controller.ActionHandler|reportDashRep1 |report_run_dashrep1.jsp \n"
+ + "report.dashrep2.run |org.onap.portalsdk.analytics.controller.ActionHandler|reportDashRep2 |report_run_dashrep2.jsp \n"
+ + "report.dashrep3.run |org.onap.portalsdk.analytics.controller.ActionHandler|reportDashRep3 |report_run_dashrep3.jsp \n"
+ + "report.dashrep4.run |org.onap.portalsdk.analytics.controller.ActionHandler|reportDashRep4 |report_run_dashrep4.jsp \n"
+ + "report.download |org.onap.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_xls.jsp \n"
+ + "report.download.excel2007 |org.onap.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_xlsx.jsp \n"
+ + "report.download.page |org.onap.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_page_xls.jsp \n"
+ + "report.csv.download |org.onap.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_csv.jsp \n"
+ + "report.text.download |org.onap.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_txt.jsp \n"
+ + "report.search |org.onap.portalsdk.analytics.controller.ActionHandler|reportSearch |report_search.jsp \n"
+ + "report.search.execute |org.onap.portalsdk.analytics.controller.ActionHandler|reportSearchExecute |report_search \n"
+ + "report.search.user |org.onap.portalsdk.analytics.controller.ActionHandler|reportSearchUser |report_search.jsp \n"
+ + "report.search.public |org.onap.portalsdk.analytics.controller.ActionHandler|reportSearchPublic |report_search.jsp \n"
+ + "report.search.favorite |org.onap.portalsdk.analytics.controller.ActionHandler|reportSearchFavorites |report_search.jsp \n"
+ + "report.wizard |org.onap.portalsdk.analytics.controller.ActionHandler|reportWizard |report_wizard \n"
+ + "report.create |org.onap.portalsdk.analytics.controller.ActionHandler|reportCreate |report_wizard \n"
+ + "report.import |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_import \n"
+ + "report.import.save |org.onap.portalsdk.analytics.controller.ActionHandler|reportImportSave |report_wizard \n"
+ + "report.copy |org.onap.portalsdk.analytics.controller.ActionHandler|reportCopy |report_wizard \n"
+ + "report.copy.container |org.onap.portalsdk.analytics.controller.ActionHandler|reportCopy |raptor_wizard_container.jsp \n"
+ + "report.edit |org.onap.portalsdk.analytics.controller.ActionHandler|reportEdit |report_wizard \n"
+ + "report.delete |org.onap.portalsdk.analytics.controller.ActionHandler|reportDelete |report_search \n"
+ + "report.popup.field |org.onap.portalsdk.analytics.controller.ActionHandler|reportFormFieldPopup |popup_field.jsp \n"
+ + "report.popup.map |org.onap.portalsdk.analytics.controller.ActionHandler|reportValuesMapDefPopup |popup_map.jsp \n"
+ + "report.popup.drilldown.table |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |popup_drill_down_table.jsp \n"
+ + "report.popup.drilldown.report|org.onap.portalsdk.analytics.controller.ActionHandler|reportDrillDownToReportDefPopup|popup_drill_down_report \n"
+ + "report.popup.import.semaphore|org.onap.portalsdk.analytics.controller.ActionHandler|importSemaphorePopup |popup_import_semaphore \n"
+ + "report.popup.semaphore |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |popup_semaphore \n"
+ + "report.popup.semaphore.save |org.onap.portalsdk.analytics.controller.ActionHandler|saveSemaphorePopup |popup_semaphore \n"
+ + "report.popup.filter.col |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |popup_filter_col.jsp \n"
+ + "report.popup.filter.data |org.onap.portalsdk.analytics.controller.ActionHandler|reportFilterDataPopup |popup_filter_data.jsp \n"
+ + "report.popup.sql |org.onap.portalsdk.analytics.controller.ActionHandler|reportShowSQLPopup |popup_sql \n "
+ + "report.run.popup |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_run_popup.jsp \n"
+ + "report.popup.test.cond |org.onap.portalsdk.analytics.controller.ActionHandler|testSchedCondPopup |popup_sql \n"
+ + "report.popup.testrun.sql |org.onap.portalsdk.analytics.controller.ActionHandler|testRunSQLPopup |popup_testrun_sql \n"
+ + "report.test.jsp |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |test_run_sql \n"
+ + "report.field.testrun.jsp |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |test_field_run_sql \n"
+ + "report.field.default.testrun.jsp |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |default_field_run_sql \n"
+ + "report.field.date.start.testrun.jsp |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |date_start_field_run_sql \n"
+ + "report.field.date.end.testrun.jsp |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |date_end_field_run_sql \n"
+ + "report.popup.table.cols |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |popup_table_cols \n"
+ + "refresh.cache |org.onap.portalsdk.analytics.controller.ActionHandler|refreshCache |message.jsp \n"
+ + "report.message |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |message.jsp \n"
+ + "report.download.pdf |org.onap.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_pdf.jsp \n"
+ + "report.popup.pdfconfig |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |popup_pdf_config.jsp \n"
+ + "download.all |org.onap.portalsdk.analytics.controller.ActionHandler|downloadAll |close.jsp \n"
+ + "download.all.jsp |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |popup_download_flat_file.jsp \n"
+ + "download.data.file |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |download_data_file.jsp \n"
+ + "popup.calendar |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |gtm_calendar.jsp \n"
+ + "report.folderlist |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |folder_report_list.jsp \n"
+ + "report.folderlist_iframe |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |folder_report_list_iframe.jsp \n"
+ + "report.childDropDown |org.onap.portalsdk.analytics.controller.ActionHandler|getChildDropDown |raptor_childdropdown.jsp \n"
+ + "report.create.container |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_create_container.jsp \n"
+ + "report.search.container |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_search_container.jsp \n"
+ + "report.search.execute.container |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_search_execute_container.jsp \n"
+ + "report.search.user.container |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_search_user_container.jsp \n"
+ + "report.search.public.container |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_search_public_container.jsp \n"
+ + "report.search.favorite.container |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_search_favorite_container.jsp \n"
+ + "report.run.container |org.onap.portalsdk.analytics.controller.ActionHandler|reportRun |report_run_container.jsp \n"
+ + "report.formfields.run.container |org.onap.portalsdk.analytics.controller.ActionHandler|formFieldRun |report_run_container.jsp \n"
+ + "report.run.jsp |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_run.jsp \n"
+ + "report.schedule.multiple |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |wizard_schedule_multiple.jsp \n"
+ + "report.schedule.submit |org.onap.portalsdk.analytics.controller.ActionHandler|processSchedule |wizard_schedule_only.jsp \n"
+ + "report.schedule.report.submit |org.onap.portalsdk.analytics.controller.ActionHandler|processScheduleReportList |wizard_schedule_only.jsp \n"
+ + "report.schedule.report.submit_wmenu |org.onap.portalsdk.analytics.controller.ActionHandler|processScheduleReportList |wizard_schedule_only_from_search.jsp \n"
+ + "report.schedule_only |org.onap.portalsdk.analytics.controller.ActionHandler|processSchedule |wizard_schedule_only \n"
+ + "report.schedule_only_from_search |org.onap.portalsdk.analytics.controller.ActionHandler|processSchedule |wizard_schedule_only_from_search.jsp \n"
+ + "report.schedule_delete |org.onap.portalsdk.analytics.controller.ActionHandler|processScheduleDelete |report_run_container.jsp \n"
+ + "report.schedule.submit_from_search |org.onap.portalsdk.analytics.controller.ActionHandler|processSchedule |wizard_schedule_only_from_search.jsp \n"
+ + "report.dashboard.detail |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |dashboard_report_run_detail.jsp \n"
+ + "report.csv.download.direct |org.onap.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_csv.jsp \n"
+ + "report.csv.download.direct |org.onap.portalsdk.analytics.controller.ActionHandler|reportRun |report_download_csv.jsp \n"
+ + "report.download.csv.session |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_download_csv \n"
+ + "report.download.excel2007.session |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_download_xlsx.jsp \n"
+ + "report.download.excel.session |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_download_xls.jsp \n"
+ + "report.download.pdf.session |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_download_pdf.jsp \n"
+ + "report.download.page.session |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_download_page_xls.jsp \n"
+ + "report.data.remove.session |org.onap.portalsdk.analytics.controller.ActionHandler|removeReportDataFromSession |report_run_container.jsp \n"
+ + "report.dashboard.run.container |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_dashboard_run_container.jsp \n"
+ + "chart.force.cluster |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |force_cluster.jsp \n"
+ + "chart.run |org.onap.portalsdk.analytics.controller.ActionHandler|reportChartRun |report_run_container.jsp \n"
+ + "chart.json |org.onap.portalsdk.analytics.controller.ActionHandler|reportChartRun |report_run_container.jsp \n"
+ + "chart.data.json |org.onap.portalsdk.analytics.controller.ActionHandler|reportChartDataRun |report_run_container.jsp \n"
+ + "quicklinks.json |org.onap.portalsdk.analytics.controller.ActionHandler|getQuickLinksJSON |report_run_container.jsp \n"
+ + "embed.run |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_embed_run_container.zul \n"
+ + "schedule.edit |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |wizard_adhoc_schedule.zul \n"
+ + "chart.annotations.run |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |plugin_chart_annotation.jsp \n"
+ + "chart.annotations.exec |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |chart_annotations.jsp \n"
+ + "chart.mini |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |chart_minified.jsp \n"
+ + "report.olap.run.container |org.onap.portalsdk.analytics.controller.ActionHandler|gotoJsp |report_olap_run_container.jsp \n"
+ + "report.hive.run.container |org.onap.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
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.controller;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.system.*;
+
+public class Action extends org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+/* ===========================================================================================
+ * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
+ * 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);<UL><LI> reportFormFieldPopup iterates form field collections. </LI></UL>
+ * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
+ * 13-Aug-2009 : Version 8.5 (Sundar);<UL><LI> reportFormFieldPopup is changed to have effect on textfield with popup. </LI></UL>
+ * 06-Aug-2009 : Version 9.0 (Sundar);<UL><LI> reportFormFieldPopupB is changed. </LI></UL>
+ * 29-Jul-2009 : Version 8.4 (Sundar);<UL><LI> Previously report data for dashboard stored only page level data. This has been changed to show all the data up to the maximum specified. </LI></UL>
+ * 27-Jul-2009 : Version 8.4 (Sundar);<UL><LI>Bug due to not showing back button after child report in drilldown is navigated more than
+ * one page is resolved. </LI></UL>
+ * 14-Jul-2009 : Version 8.4 (Sundar); <UL><LI>Dashboard reports can now be generated excel as separate sheets or group together in PDF.
+ * They can also be scheduled.</LI></UL>
+ *
+ */
+package org.onap.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.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
+import org.onap.portalsdk.analytics.error.RaptorSchedularException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.error.UserDefinedException;
+import org.onap.portalsdk.analytics.error.ValidationException;
+import org.onap.portalsdk.analytics.model.DataCache;
+import org.onap.portalsdk.analytics.model.ReportHandler;
+import org.onap.portalsdk.analytics.model.ReportLoader;
+import org.onap.portalsdk.analytics.model.SearchHandler;
+import org.onap.portalsdk.analytics.model.base.IdNameColLookup;
+import org.onap.portalsdk.analytics.model.base.IdNameList;
+import org.onap.portalsdk.analytics.model.base.IdNameSql;
+import org.onap.portalsdk.analytics.model.base.ReportSecurity;
+import org.onap.portalsdk.analytics.model.definition.ReportDefinition;
+import org.onap.portalsdk.analytics.model.definition.ReportSchedule;
+import org.onap.portalsdk.analytics.model.runtime.ChartWebRuntime;
+import org.onap.portalsdk.analytics.model.runtime.ErrorJSONRuntime;
+import org.onap.portalsdk.analytics.model.runtime.FormField;
+import org.onap.portalsdk.analytics.model.runtime.FormatProcessor;
+import org.onap.portalsdk.analytics.model.runtime.ReportFormFields;
+import org.onap.portalsdk.analytics.model.runtime.ReportJSONRuntime;
+import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
+import org.onap.portalsdk.analytics.model.runtime.VisualManager;
+import org.onap.portalsdk.analytics.model.search.ReportSearchResultJSON;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.ConnectionUtils;
+import org.onap.portalsdk.analytics.system.DbUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.system.fusion.domain.QuickLink;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.analytics.view.DataRow;
+import org.onap.portalsdk.analytics.view.DataValue;
+import org.onap.portalsdk.analytics.view.ReportData;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
+import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
+import org.onap.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.onap.portalsdk.analytics.RaptorObject {
+
+ private static final 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<String> 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; i<aL.size(); i++) {
+ rr = (ReportRuntime) aL.get(i);
+ if( rr!=null && rr.getReportType().equals(AppConstants.RT_DASHBOARD))
+ return true;
+ }
+ }
+ return false;
+ }
+ private ReportRuntime getReportRuntimeFromBackup(HttpServletRequest request) {
+ ArrayList aL = (ArrayList) request.getSession().getAttribute(
+ AppConstants.DRILLDOWN_REPORTS_LIST);
+ ReportRuntime rr = null;
+ HttpSession session = request.getSession();
+ /*if(aL==null || (aL.size() <=0) ) {
+ rr = (ReportRuntime) request.getSession().getAttribute(
+ AppConstants.SI_REPORT_RUN_BACKUP);
+ request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr);
+ } else {*/
+ //clearReportRuntimeBackup(request);
+
+ int index = Integer.parseInt(nvl(AppUtils.getRequestValue(request, AppConstants.DRILLDOWN_INDEX), "0"));
+ int form_index = Integer.parseInt(nvl(AppUtils.getRequestValue(request, AppConstants.FORM_DRILLDOWN_INDEX), "0"));
+ index = index>0 ? --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 <a href=''>login</a> 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<QuickLink> 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; i<sessionParams.length; i++) {
+ for (int j = 0; j < formFieldsArr.length; j++) {
+ if(formFieldsArr[j].startsWith(sessionParams[i])) {
+ request.setAttribute(sessionParams[i], formFieldsArr[j].substring(formFieldsArr[j].indexOf("=")+1));
+ }
+
+ }
+ }
+
+ boolean reportUpdated = false;
+ WizardProcessor wp = null;
+ Connection connection = null;
+ try {
+ connection = DbUtils.startTransaction();
+ wp = new WizardProcessor();
+ String toListUpdated = nvl(request.getParameter("toListUpdated"),"false" );
+ reportUpdated = wp.processAdhocSchedule(request, action);
+ if(reportUpdated && toListUpdated.equals("false")) {
+ request.setAttribute("message", "Report has been scheduled successfully");
+ reportSchedule = (ReportSchedule) request.getSession().getAttribute(AppConstants.SI_REPORT_SCHEDULE);
+ //if(AppUtils.getRequestNvlValue(request, AppConstants.RI_SCHEDULE_ID).length()<=0) {
+ reportSchedule.persistScheduleData(connection, request);
+ DbUtils.commitTransaction(connection);
+ //}
+ }
+ } catch (ValidationException ve) {
+ (new ErrorHandler()).processError(request, ve);
+ } catch (RaptorException e) {
+ nextPage = (new ErrorHandler()).processFatalError(request, e);
+ e.printStackTrace();
+ try {
+ DbUtils.rollbackTransaction(connection);
+ } catch (Exception e1) {e1.printStackTrace();}
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ finally {
+ try {
+ DbUtils.clearConnection(connection);
+ } catch (Exception e1) {e1.printStackTrace();}
+ }
+ request.setAttribute("schedule_only", "Y");
+ //request.getSession().removeAttribute(AppConstants.SI_REPORT_SCHEDULE);
+
+ return nextPage;
+ } else {
+ try {
+ String scheduleID = "";
+ scheduleID = AppUtils.getRequestValue(request, AppConstants.RI_SCHEDULE_ID);
+ String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
+ request.setAttribute("schedule_only", "Y");
+ ReportHandler rh = new ReportHandler();
+ ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
+ ReportSchedule reportSchedule = null;
+ if(rdef!=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; i<sessionParams.length; i++) {
+ for (int j = 0; j < formFieldsArr.length; j++) {
+ if(formFieldsArr[j].startsWith(sessionParams[i])) {
+ request.setAttribute(sessionParams[i], formFieldsArr[j].substring(formFieldsArr[j].indexOf("=")+1));
+ }
+
+ }
+ }
+ request.getSession().setAttribute(AppConstants.SI_REPORT_SCHEDULE, reportSchedule);
+ request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
+ } catch (RaptorException e) {
+ nextPage = (new ErrorHandler()).processFatalError(request, e);
+ }
+
+ return nextPage;
+ }
+ } // processSchedule
+
+ /****Remove Report Data from Session when Javascript throw error on onSubmit***/
+ public String removeReportDataFromSession (HttpServletRequest request, String nextPage) {
+ HttpSession session = request.getSession(false);
+/* if (session.getAttribute(AppConstants.RI_REPORT_DATA)!=null)
+ request.getSession().removeAttribute(AppConstants.RI_REPORT_DATA);
+ if (request.getAttribute(AppConstants.RI_REPORT_DATA)!=null)
+ request.removeAttribute(AppConstants.RI_REPORT_DATA);
+ if (session.getAttribute(AppConstants.RI_CHART_DATA)!=null)
+ request.getSession().removeAttribute(AppConstants.RI_CHART_DATA);
+ if (request.getAttribute(AppConstants.RI_CHART_DATA)!=null)
+ request.removeAttribute(AppConstants.RI_CHART_DATA);
+*/ /*if (session.getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null)
+ request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);*/
+ //request.setAttribute(AppConstants.RI_RESET_ACTION, "Y");
+ return nextPage;
+
+ } // processScheduleDelete
+
+ /****Added to delete a schedule***/
+ public String processScheduleDelete(HttpServletRequest request, String nextPage) {
+
+ // Added for form field chaining in schedule tab so that setParamValues() is called
+ request.setAttribute(AppConstants.SCHEDULE_ACTION, "Y");
+ try {
+ String scheduleID = "";
+ scheduleID = AppUtils.getRequestValue(request, AppConstants.RI_SCHEDULE_ID);
+ String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
+ ReportHandler rh = new ReportHandler();
+ ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
+ String myScheduleRepID = AppUtils.getRequestNvlValue(request, "myScheduleRepId");
+ if (myScheduleRepID.equals(""))
+ myScheduleRepID = "2670";
+ ReportSchedule reportSchedule = null;
+ if(rdef!=null) {
+ reportSchedule = new ReportSchedule(reportID, scheduleID, AppUtils.getUserID(request), request);
+ Connection connection = null;
+
+ try {
+ connection = DbUtils.startTransaction();
+ reportSchedule.deleteScheduleData(connection);
+ DbUtils.commitTransaction(connection);
+ } catch (ValidationException ve) {
+ (new ErrorHandler()).processError(request, ve);
+ } catch (RaptorException e) {
+ nextPage = (new ErrorHandler()).processFatalError(request, e);
+ e.printStackTrace();
+ try {
+ DbUtils.rollbackTransaction(connection);
+ } catch (Exception e1) {e1.printStackTrace();}
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ finally {
+ try {
+ DbUtils.clearConnection(connection);
+ } catch (Exception e1) {e1.printStackTrace();}
+ }
+ }
+ request.setAttribute(AppConstants.RI_REPORT_ID, myScheduleRepID);
+ request.setAttribute(AppConstants.RI_REFRESH, "y");
+ nextPage = this.reportRun(request, nextPage);
+ } catch (RaptorException e) {
+ nextPage = (new ErrorHandler()).processFatalError(request, e);
+ }
+ return nextPage;
+
+ } // processScheduleDelete
+
+ public String reportWizard(HttpServletRequest request, String nextPage) {
+ String action = nvl(request.getParameter(AppConstants.RI_WIZARD_ACTION),
+ AppConstants.WA_BACK);
+ String goToStep = nvl(request.getParameter(AppConstants.RI_GO_TO_STEP));
+ try {
+ (new WizardProcessor()).processWizardStep(request);
+
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
+ AppConstants.SI_REPORT_DEFINITION);
+ WizardSequence ws = rdef.getWizardSequence();
+ //debugLogger.debug("Step Count " + ws.getStepCount());
+ //debugLogger.debug("Dashboard " + ((ws instanceof WizardSequenceDashboard) ? ws.getStepCount(): "Not a Dashboard"));
+ //debugLogger.debug("GO TO STEP LENGTH " + goToStep.length());
+ //debugLogger.debug("NumDash Cols in Action Handler " + AppUtils.getRequestNvlValue(request, "numDashCols"));
+ if (goToStep.length() > 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("<b>");
+ if (idxNext > 0)
+ sb.append(" ");
+ sb.append(sqlClause[idxNext]);
+ sb.append("</b><br>\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("<br>\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,
+ "<br><b>Condition NOT satisfied</b> - email notification will NOT be send.<br><br>");
+ else
+ request
+ .setAttribute(AppConstants.RI_FORMATTED_SQL,
+ "<br><b>Condition satisfied</b> - email notification will be send.<br><br>");
+ } catch (Exception e) {
+ // nextPage = (new ErrorHandler()).processFatalError(request, e);
+ request.setAttribute(AppConstants.RI_FORMATTED_SQL, "<br><b>SQL ERROR</b> "
+ + e.getMessage() + "<br>Email notification will NOT be send.<br><br>");
+ }
+
+ 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 <a href=''>login</a> 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<BR>");
+ messageBuffer.append("<a href=\"" + request.getContextPath() + "/raptor/dwnld/data/" +
+ strFileName + "\">click here</a>.</p>");
+ 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<String> 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 = "<table border=1><tr><td>[Report#123]</td><td>[Report#124]</td></tr><tr><td>[Report#125]</td><td>[Report#126]</td></tr></table>";
+ 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<size; i++) {
+ hashReports.put(sortedArray[i], mapValues.get(mapKeys.indexOf(sortedArray[i])));
+ }*/
+ return new TreeMap(hashReports);
+ }
+
+ public ReportData getReportData(ReportRuntime reportRuntime, HttpServletRequest request, String sql, int maxRows) throws RaptorException {
+
+
+ // replace the request parameter specified in the drill down
+ List reportCols = reportRuntime.getAllColumns();
+ 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());
+ 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.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+ package org.onap.portalsdk.analytics.controller;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class Controller extends org.onap.portalsdk.analytics.RaptorObject {
+
+ private static final 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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.controller;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.*;
+import javax.servlet.http.*;
+
+import org.onap.portalsdk.analytics.error.*;
+import org.onap.portalsdk.analytics.model.definition.ReportDefinition;
+import org.onap.portalsdk.analytics.model.runtime.ErrorJSONRuntime;
+import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.onap.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.onap.portalsdk.analytics.RaptorObject {
+
+ private static final 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
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.ValidationException;
+import org.onap.portalsdk.analytics.model.ReportHandler;
+import org.onap.portalsdk.analytics.model.ReportLoader;
+import org.onap.portalsdk.analytics.model.base.IdNameValue;
+import org.onap.portalsdk.analytics.model.base.OrderBySeqComparator;
+import org.onap.portalsdk.analytics.model.base.OrderSeqComparator;
+import org.onap.portalsdk.analytics.model.definition.ReportDefinition;
+import org.onap.portalsdk.analytics.model.definition.ReportSchedule;
+import org.onap.portalsdk.analytics.model.runtime.FormField;
+import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.DbUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.XSSFilter;
+import org.onap.portalsdk.analytics.xmlobj.ChartDrillFormfield;
+import org.onap.portalsdk.analytics.xmlobj.ColFilterType;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
+import org.onap.portalsdk.analytics.xmlobj.DataSourceType;
+import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
+import org.onap.portalsdk.analytics.xmlobj.FormatType;
+import org.onap.portalsdk.analytics.xmlobj.JavascriptItemType;
+import org.onap.portalsdk.analytics.xmlobj.Marker;
+import org.onap.portalsdk.analytics.xmlobj.ObjectFactory;
+import org.onap.portalsdk.analytics.xmlobj.SemaphoreType;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+/**<HR/>
+ * This class is part of <B><I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I></B><BR/>
+ * <HR/>
+ *
+ * --------------------------------------------------------------------------------------------------<BR/>
+ * <B>WizardProcessor.java</B> - This class is used to process the user input provided in the wizard.<BR/>
+ * It is called in creation as well as updation process. It builds report xml via JAXB using user<BR/>
+ * input. This is vital one, to store meta information of each report<BR/>
+ * ---------------------------------------------------------------------------------------------------<BR/>
+ *
+ *
+ * <U>Change Log</U><BR/><BR/>
+ *
+ * 31-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> For Time Series multi series property is exposed. </LI></UL>
+ * 28-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> If user login id is null, it would display user name when user is added for schedule. </LI></UL>
+ * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
+ * 12-Aug-2009 : Version 8.5 (Sundar); <UL><LI> For Line Charts too options are captured and rendering is customized. </LI></UL>
+ * 29-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Maximum Excel Download size would be persisted if changed. </LI></UL>
+ * 14-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Schedule feature is added to Dashboard Reports. </LI></UL>
+ * 29-Jun-2009 : Version 8.4 (Sundar); <UL><LI> Options for <I>Compare to Previous year Chart</I> are processed.</LI>
+ * <LI> In the Bar chart Last Occuring Series/Category can be plotted as Bar or Line Renderer. </LI>
+ * </UL>
+ * 22-Jun-2009 : Version 8.4 (Sundar); <UL><LI> processChart method is modified to accommodate creating
+ * Bar Charts, Time Difference Charts and adding generic chart options.</LI></UL>
+ *
+ */
+
+public class WizardProcessor extends org.onap.portalsdk.analytics.RaptorObject {
+
+ private static final 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 != null && 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<br>Expected date format " + nvl(
+ currColumn.getColFormat(),
+ AppConstants.DEFAULT_DATE_FORMAT))
+ : "Invalid value<br>Possible reason: use of single quotes"))
+ + "<!--" + e.getMessage() + "--><br>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.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+ package org.onap.portalsdk.analytics.controller;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.model.base.*;
+import org.onap.portalsdk.analytics.model.definition.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.controller;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.controller;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.controller;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.controller;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.controller;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.controller;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.controller;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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);
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+/**
+ *
+ */
+package org.onap.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);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.gmap.line;
+
+import java.awt.geom.Point2D;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.onap.portalsdk.analytics.gmap.map.NovaMap;
+
+public class Line {
+ private NovaMap map;
+ private LineCollection lineCollection;
+ private ArrayList<String> selectionList;
+ private Set<String> lineIDSet;
+
+ public Line(NovaMap map) {
+ this.map = map;
+ lineCollection = new LineCollection();
+ lineIDSet = new HashSet<String>();
+ selectionList = new ArrayList<String>();
+ }
+
+ public ArrayList<LineInfo> lineExist(Point2D screenPoint) {
+ ArrayList<LineInfo> 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<LineInfo> 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<LineInfo>();
+ }
+
+ existLineInfo.add(lineInfo);
+ }
+ }
+
+ return existLineInfo;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.gmap.line;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Set;
+
+public class LineCollection {
+ private Set<String> selectedLine; // all selected node
+ private String lineID; // last clicked node
+ private ArrayList<LineInfo> lineCollection;
+
+ public LineCollection() {
+ lineCollection = new ArrayList<LineInfo>(20000);
+ selectedLine = new HashSet<String>();
+ }
+
+ public void addSelectedLine(String lineID) {
+ selectedLine.add(lineID);
+ }
+
+ public void removeSelectedLine(String lineID) {
+ selectedLine.remove(lineID);
+ }
+
+ public Set<String> 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<LineInfo> 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<String> list = new ArrayList<String>();
+
+ 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;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.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<String, String> lineAttributes;
+
+ public LineInfo(String nodeID1, String nodeID2) {
+ this.nodeID1 = nodeID1;
+ this.nodeID2 = nodeID2;
+ lineAttributes = new HashMap<String, String>();
+ }
+
+ 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<String, String> lineAttributes) {
+ this.lineAttributes.clear();
+ Set<String> keySet = lineAttributes.keySet();
+ Iterator<String> 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<String> getAttributeKeys() {
+ Set<String> keySet = lineAttributes.keySet();
+ List<String> keys = new ArrayList<String>(keySet.size());
+ Iterator<String> iter = keySet.iterator();
+
+ while (iter.hasNext()) {
+ String key = iter.next();
+
+ if (key.indexOf("x_") != 0) {
+ keys.add(key);
+ }
+ }
+
+ return keys;
+ }
+
+ public List<String> getAttributeInternalKeys() {
+ Set<String> keySet = lineAttributes.keySet();
+ List<String> internalKeys = new ArrayList<String>();
+ Iterator<String> 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;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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<String, Object> colorProperties;
+ private ArrayList<String> nodeLegends;
+ private ArrayList<String> lineLegends;
+
+ public ColorProperties(NovaMap map) {
+ this.map = map;
+ colorProperties = new HashMap<String, Object>();
+ }
+
+ 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());
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.gmap.map;
+
+import java.io.InputStream;
+import java.util.Properties;
+
+import org.onap.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();
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.gmap.map;
+
+public class GeoCoordinate {
+ public double longitude;
+ public double latitude;
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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;
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.gmap.line.Line;
+import org.onap.portalsdk.analytics.gmap.line.LineInfo;
+import org.onap.portalsdk.analytics.gmap.map.layer.SwingLayer;
+import org.onap.portalsdk.analytics.gmap.node.Node;
+import org.onap.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<String> showList;
+ private ArrayList<SwingLayer> 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<meter2pixel.length; ++i)
+ meter2pixel[i] = meter2pixel[i-1]/2;
+ }
+
+ private static void initShapeWidth() {
+ // ZOOM_MAX+1 is added to below line because of ArrayIndexOutOfException. This is Suggested by Hendra Tuty. - Sundar
+ shapeWidth = new int[MapConstant.ZOOM_MAX];
+ int width = 0;
+ for (int i = 0; i < shapeWidth.length; i++) {
+ if (i < 5) {
+
+ }
+ else if (i == 5) {
+ width = 4;
+ }
+ else if (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<String>();
+ swingLayers = new ArrayList<SwingLayer>();
+ }
+
+
+
+ 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<SwingLayer> 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<<zoomLevel),
+ ( 0.5 - Math.log((1.0+sinLatitude)/(1.0-sinLatitude))
+ /(4.0*Math.PI) )*256.0*(1<<zoomLevel)
+ );
+ }
+
+ private boolean checkTransform(Rectangle2D geoArea) {
+ System.out.println("%%%%%%map.checkTransform start");
+ if (!this.geoArea.equals(geoArea)) {
+ Point2D point1 = getPixelPos(geoArea.getMinY(), geoArea.getMinX());
+ Point2D point2 = getPixelPos(geoArea.getMaxY(), geoArea.getMaxX());
+ mapArea.setRect(point1.getX(), point2.getY(),
+ boundingBox.getWidth(), boundingBox.getHeight());
+ this.geoArea.setRect(geoArea);
+ resetTransform(boundingBox, mapArea);
+ System.out.println("%%%%%%map.checkTransform end 1");
+ return true;
+ }
+
+ System.out.println("%%%%%%map.checkTransform end 2");
+ return false;
+ }
+
+ private void resetTransform(Rectangle boundingBox, Rectangle2D mapArea) {
+ System.out.println("%%%%%%map.resetTransform start");
+ if (mapArea == null || boundingBox.getWidth() == 0 || boundingBox.getHeight() == 0 ) {
+ System.out.println("%%%%%%map.resetTransform end 1");
+ return;
+ }
+
+ transform = new AffineTransform(mapArea.getWidth() / boundingBox.getWidth(),
+ 0.0, 0.0, mapArea.getHeight() / boundingBox.getHeight(),
+ mapArea.getMinX(), mapArea.getMinY());
+ System.out.println("%%%%%%map.resetTransform end 2");
+ }
+
+ protected AffineTransform getTransform() {
+ if (transform != null) {
+ return new AffineTransform(transform);
+ }
+
+ return null;
+ }
+
+ public Point2D getScreenPointFromPixel(double xPixel, double yPixel) {
+ try {
+ return getTransform().inverseTransform(new Point2D.Double(xPixel, yPixel), null);
+ } catch (NoninvertibleTransformException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ return null;
+ }
+
+ public Point2D getScreenPointFromLonLat(double longitude, double latitude) {
+ Point2D point = getPixelPos(latitude, longitude);
+ return getScreenPointFromPixel(point.getX(), point.getY());
+ }
+
+ public Point2D getLonLatFromPixel(int x1, int y1) {
+ double x = (double) x1 / 256;
+ double y = (double) y1 / 256;
+ double lon = -180; // x
+ double lonWidth = 360; // width 360
+
+ //double lat = -90; // y
+ //double latHeight = 180; // height 180
+ double lat = -1;
+ double latHeight = 2;
+
+ int tilesAtThisZoom = 1 << getZoomLevel();
+ lonWidth = 360.0 / tilesAtThisZoom;
+ lon = -180 + (x * lonWidth);
+ latHeight = -2.0 / tilesAtThisZoom;
+ lat = 1 + (y * latHeight);
+
+ // convert lat and latHeight to degrees in a transverse mercator projection
+ // note that in fact the coordinates go from about -85 to +85 not -90 to 90!
+ latHeight += lat;
+ latHeight = (2 * Math.atan(Math.exp(Math.PI * latHeight))) - (Math.PI / 2);
+ latHeight *= (180 / Math.PI);
+
+ lat = (2 * Math.atan(Math.exp(Math.PI * lat))) - (Math.PI / 2);
+ lat *= (180 / Math.PI);
+
+ latHeight -= lat;
+
+ if (lonWidth < 0) {
+ lon = lon + lonWidth;
+ lonWidth = -lonWidth;
+ }
+
+ if (latHeight < 0) {
+ lat = lat + latHeight;
+ latHeight = -latHeight;
+ }
+
+ return new Point2D.Double(lon, lat + latHeight);
+ }
+
+ public ArrayList getImage(final HttpServletRequest request, Rectangle2D geoArea) {
+ Object showListArr[] = ((HashSet)getShowList()).toArray();
+ BufferedImage image = new BufferedImage(boundingBox.width, boundingBox.height, BufferedImage.TYPE_INT_ARGB);
+ final Graphics2D g2d = image.createGraphics();
+ // LEGEND INFO
+ BufferedImage legendImage = null;
+ Graphics2D g2Legend = null;
+ if(showLegend) {
+ legendImage = new BufferedImage(boundingBox.width, (int)(20*showListArr.length) + 20, BufferedImage.TYPE_INT_ARGB);
+ g2Legend = legendImage.createGraphics();
+ g2Legend.setBackground(Color.WHITE);
+ }
+
+ checkTransform(geoArea);
+
+ boolean swingLayerPainted = false;
+
+ Object object = request.getAttribute("server_process_interrupted");
+ if (object != null && ((Boolean) object)) {
+ System.out.println("interrupted");
+ g2d.dispose();
+ return null;
+ }
+
+ for (SwingLayer layer : swingLayers) {
+ swingLayerPainted = swingLayerPainted || layer.paintLayer(request, g2d, boundingBox, mapArea, g2Legend);
+ }
+
+ ArrayList imageArr = new ArrayList();
+ //if(showLegend) layer.paintLegend(g2Legend);
+
+ g2d.dispose();
+ if(showLegend && g2Legend != null)
+ g2Legend.dispose();
+ object = request.getAttribute("server_process_interrupted");
+
+ if (object != null && ((Boolean) object)) {
+ System.out.println("interrupted");
+ return imageArr;
+ }
+ else if (!swingLayerPainted) {
+ System.out.println("not painted");
+ return imageArr;
+ }
+
+ imageArr.add(image);
+ if(g2Legend!=null) {
+ imageArr.add(legendImage);
+ }
+ return imageArr;
+ }
+
+ public Object singleLeftClick(double longitude, double latitude, Rectangle2D geoArea) {
+ System.out.println("%%%%%%map.singleLeftClick start");
+ System.out.println("%%%%%%map.singleLeftClick check transform start");
+ checkTransform(geoArea);
+ System.out.println("%%%%%%map.singleLeftClick check transform end");
+ Point2D screenPoint = getScreenPointFromLonLat(longitude, latitude);
+ System.out.println("%%%%%%map.singleLeftClick getting nodeExist array ");
+ ArrayList<NodeInfo> existNodeInfo = node.nodeExist(screenPoint);
+
+ if (existNodeInfo == null) {
+ ArrayList<LineInfo> 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;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.gmap.map.ColorProperties;
+import org.onap.portalsdk.analytics.gmap.map.MapConstant;
+import org.onap.portalsdk.analytics.gmap.map.NovaMap;
+import org.onap.portalsdk.analytics.gmap.node.Node;
+import org.onap.portalsdk.analytics.gmap.node.NodeInfo;
+import org.onap.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<String,NodeInfo> hashMap = node.getNodeCollection().getNodeCollection();
+ Set set = hashMap.entrySet();
+ int width = map.getShapeWidth();
+ ArrayList<String> visibleLabel = new ArrayList<String>(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;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.gmap.map.MapConstant;
+import org.onap.portalsdk.analytics.gmap.map.NovaMap;
+
+public class Node {
+ private Set<String> nodeIDSet;
+ private NodeCollection nodeCollection;
+ private ArrayList<String> selectionList;
+ private NovaMap map;
+
+ public Node(NovaMap map) {
+ this.map = map;
+ nodeCollection = new NodeCollection();
+ nodeIDSet = new HashSet<String>();
+ selectionList = new ArrayList<String>();
+ }
+
+ 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<NodeInfo> nodeCollection = this.nodeCollection.getNodeCollection();
+
+ for (NodeInfo nodeInfo : nodeCollection) {
+ nodeInfo.setAttribute(NodeInfo.NUMBER_OF_T1_KEY, nodeInfo.getAttribute(currentYearMonth));
+ }
+ }
+*/
+/* public Set<Integer> getUniqueNumberT1(String currentYearMonth) {
+ ArrayList<NodeInfo> nodeCollection = this.nodeCollection.getNodeCollection();
+ Set<Integer> numberT1Set = new TreeSet<Integer>();
+
+ for (NodeInfo nodeInfo : nodeCollection) {
+ numberT1Set.add(Integer.parseInt(nodeInfo.getAttribute(currentYearMonth).toString()));
+ }
+
+ return numberT1Set;
+ }
+*/
+ public void updateNumberT1(String currentYearMonth) {
+ HashMap<String,NodeInfo> 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<Integer> getUniqueNumberT1(String currentYearMonth) {
+ HashMap<String,NodeInfo> hashMap = this.nodeCollection.getNodeCollection();
+ Set set = hashMap.entrySet();
+ Set<Integer> numberT1Set = new TreeSet<Integer>();
+
+ 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<NodeInfo> nodeExist(Point2D screenPoint) {
+ ArrayList<NodeInfo> existNodeInfo = null;
+ int nearest = 9999;
+ String selectedNode = null;
+ String selectedType = null;
+ int nodeSize = map.getShapeWidth();
+ HashMap<String,NodeInfo> hashMap = nodeCollection.getNodeCollection();
+ Set set = hashMap.entrySet();
+ //ArrayList<NodeInfo> 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<NodeInfo>();
+ }
+
+ existNodeInfo.add(nodeInfo);
+ }
+ }
+
+ return existNodeInfo;
+ }
+
+ public NodeCollection getNodeCollection() {
+ return nodeCollection;
+ }
+
+ public void clearNodeIDSet() {
+ nodeIDSet.clear();
+ }
+
+ public void clearSelectionList() {
+ selectionList.clear();
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.gmap.node;
+
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class NodeCollection {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(NodeCollection.class);
+
+ private Set<String> selectedNode; // all selected node
+ private String nodeID; // last clicked node
+ private HashMap<String,NodeInfo> nodeCollection;
+
+ public NodeCollection() {
+ selectedNode = new HashSet<String>();
+ nodeCollection = new HashMap<String,NodeInfo>(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<String> getSelectedNode() {
+ return selectedNode;
+ }
+
+ public void addNode(NodeInfo nodeInfo) {
+ if (nodeInfo == null)
+ logger.error("addNode: nodeInfo is null");
+ else
+ nodeCollection.put(nodeInfo.getNodeID()+""+nodeInfo.getNodeType(), nodeInfo);
+ }
+
+ public HashMap<String,NodeInfo> 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<NodeInfo> getWildCardNode(String nodeID, String nodeType) {
+ ArrayList<NodeInfo> list = new ArrayList<NodeInfo>();
+
+ 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<NodeInfo> getCellsiteLocation(String location, boolean exactMatch) {
+ ArrayList<NodeInfo> list = new ArrayList<NodeInfo>();
+
+ 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 = "";
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.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<String> lineIDS;
+ private Map<String, String> nodeAttributes;
+
+ public NodeInfo(String nodeID) {
+ this.nodeID = nodeID;
+ lineIDS = new ArrayList<String>();
+ nodeAttributes = new TreeMap<String, String>();
+ 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<String> getLineIDS() {
+ return lineIDS;
+ }
+
+ public void printLineIDS() {
+ Iterator<String> iter = lineIDS.iterator();
+
+ while (iter.hasNext()) {
+ System.out.println(iter.next());
+ }
+ }
+
+ public List<String> cloneLineIDS() {
+ List<String> lineIDS = new ArrayList<String>();
+
+ for (String lineID : this.lineIDS) {
+ lineIDS.add(lineID);
+ }
+
+ return lineIDS;
+ }
+
+ public void setLineIDS(List<String> 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<String, String> nodeAttributes) {
+ this.nodeAttributes.clear();
+ Set<String> keySet = nodeAttributes.keySet();
+ Iterator<String> 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<String> getAttributeKeys() {
+ Set<String> keySet = nodeAttributes.keySet();
+ List<String> keys = new ArrayList<String>(keySet.size());
+ Iterator<String> iter = keySet.iterator();
+
+ while (iter.hasNext()) {
+ String key = iter.next();
+
+ if (key.indexOf("x_") != 0) {
+ keys.add(key);
+ }
+ }
+
+ return keys;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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);
+ } */
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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 <code>get</code> method.
+ */
+ public abstract Object construct();
+
+ /**
+ * Called on the event dispatching thread (not on the worker thread)
+ * after the <code>construct</code> 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 <code>construct</code> 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 <code>construct</code> 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 <code>construct</code> 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();
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model;
+
+import java.util.*;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.model.base.*;
+import org.onap.portalsdk.analytics.model.definition.*;
+import org.onap.portalsdk.analytics.model.runtime.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+
+public class DataCache extends org.onap.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_<framework>.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
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+/* ===========================================================================================
+ * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
+ * 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);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
+ * 14-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Signature for generating excel method has been changed to add the report name as sheet name. </LI>
+ * <LI> Dashboard reports can be downloaded with each report as a separate sheet. </LI>
+ * </UL>
+ * 08-Jun-2009 : Version 8.3 (Sundar); <UL><LI> Short datatype is replaced with default integer datatype to create
+ * row as short is not expoting more than 32768 rows. </LI></UL>
+ *
+ */
+package org.onap.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.onap.portalsdk.analytics.controller.ErrorHandler;
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.model.base.IdNameValue;
+import org.onap.portalsdk.analytics.model.definition.ReportDefinition;
+import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.ConnectionUtils;
+import org.onap.portalsdk.analytics.system.ExecuteQuery;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.ExcelColorDef;
+import org.onap.portalsdk.analytics.util.HtmlStripper;
+import org.onap.portalsdk.analytics.util.Log;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.analytics.view.ColumnHeader;
+import org.onap.portalsdk.analytics.view.ColumnHeaderRow;
+import org.onap.portalsdk.analytics.view.DataRow;
+import org.onap.portalsdk.analytics.view.DataValue;
+import org.onap.portalsdk.analytics.view.HtmlFormatter;
+import org.onap.portalsdk.analytics.view.ReportData;
+import org.onap.portalsdk.analytics.view.RowHeader;
+import org.onap.portalsdk.analytics.view.RowHeaderCol;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
+import org.onap.portalsdk.analytics.xmlobj.DataSourceType;
+import org.onap.portalsdk.analytics.xmlobj.FormatList;
+import org.onap.portalsdk.analytics.xmlobj.FormatType;
+import org.onap.portalsdk.analytics.xmlobj.Reports;
+import org.onap.portalsdk.analytics.xmlobj.SemaphoreList;
+import org.onap.portalsdk.analytics.xmlobj.SemaphoreType;
+import org.onap.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.onap.portalsdk.analytics.RaptorObject {
+
+ private static final 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, "<BR/>", " ");
+ header = Utils.replaceInString(header, "<br/>", " ");
+ header = Utils.replaceInString(header, "<br>", " ");
+ header = strip.stripHtml(nvl(header).trim());
+ subtitle = Utils.replaceInString(subtitle, "<BR/>", " ");
+ subtitle = Utils.replaceInString(subtitle, "<br/>", " ");
+ subtitle = Utils.replaceInString(subtitle, "<br>", " ");
+ 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());
+// <td align="center"<%= ch.getColumnWidthHtml() %><%= ch.getColSpanHtml() %><%= ch.getRowSpanHtml() %>>
+// <b class=rtableheader><%= ch.getColumnTitleHtml() %></b>
+// </td>
+ } // 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<dataTypeMap.size(); tmp++){
+ String dataTypeStr = (String)(dataTypeMap.get(tmp));
+ if(dataTypeStr.equals("NUMBER")){
+ cell.setCellStyle(styleNumber);
+ }else if (dataTypeStr.equals("VARCHAR2")){
+ cell.setCellStyle(styleDefault);
+
+ }else if (dataTypeStr.equals("DATE")){
+ cell.setCellStyle(styleDate);
+ }else{
+
+ }
+
+ }*/
+ 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
+
+ // 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;
+ }
+ }
+ }
+
+ /*
+ if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols!=null) {
+
+ for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();) {
+ rowCount++;
+
+
+ DataRow dr = rd.reportDataTotalRow.getNext();
+ row = sheet.createRow(rowNum);
+ cellNum = -1;
+ int j = 0;
+ cellNum += 1;
+ cell = row.createCell((short) cellNum);
+ cell.setCellValue("Total");
+ cell.setCellStyle(styleTotal);
+
+ for (dr.resetNext(); dr.hasNext();j++) {
+ DataValue dv = dr.getNext();
+ if(j==0 || !dv.isVisible()) continue;
+ cellNum += 1;
+ styleCell = null;
+ boolean bold = true;
+ String value = nvl(dv.getDisplayValue());
+ //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(styleTotal!=null) {
+ styleTotal.setDataFormat((short) 8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)"));
+ cell.setCellStyle(styleTotal);
+ } else
+ cell.setCellStyle(styleCurrencyDecimalNumberTotal);
+ cell.setCellValue(tempDoubleDollar);
+ } catch (NumberFormatException ne) {
+ if(styleTotal!=null) {
+ styleTotal.setWrapText(true);
+ cell.setCellStyle(styleTotal);
+ } 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(styleTotal!=null) {
+ styleTotal.setDataFormat((short)0x28 );//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)"));
+ cell.setCellStyle(styleTotal);
+ } else
+ cell.setCellStyle(styleDecimalNumberTotal);
+ cell.setCellValue(tempDouble);
+ } catch (NumberFormatException ne) {
+ if(styleTotal!=null) {
+ styleTotal.setWrapText(true);
+ cell.setCellStyle(styleTotal);
+ } 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(styleTotal!=null) {
+ styleTotal.setDataFormat((short) 6);//HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
+ cell.setCellStyle(styleTotal);
+ } else
+ cell.setCellStyle(styleCurrencyNumberTotal);
+ cell.setCellValue(tempIntDollar);
+ } catch (NumberFormatException ne) {
+ if(styleTotal!=null) {
+ styleTotal.setWrapText(true);
+ cell.setCellStyle(styleTotal);
+ } 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(styleTotal!=null) {
+ styleTotal.setDataFormat((short) 0x26);//HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)"));
+ cell.setCellStyle(styleTotal);
+ } else
+ cell.setCellStyle(styleNumber);
+ cell.setCellValue(temp);
+ } catch (NumberFormatException ne) {
+ if(styleTotal!=null) {
+ styleTotal.setWrapText(true);
+ cell.setCellStyle(styleTotal);
+ } 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(styleTotal!=null) {
+ styleTotal.setWrapText(true);
+ cell.setCellStyle(styleTotal);
+ } else
+ cell.setCellStyle(styleDefault);
+ }
+ }
+ }
+
+
+
+
+ }
+ }
+ }
+ */
+
+
+
+ } else if (rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { // Linear
+ int rowCount = 0;
+ List l = rd.getReportDataList();
+ boolean first = true;
+ for (int dataRow = 0; dataRow < l.size(); dataRow++) {
+
+
+ DataRow dr = (DataRow) l.get(dataRow);
+ row = sheet.createRow(rowNum);
+
+ cellNum = -1;
+ first = true;
+ Vector<DataValue> rowNames = dr.getRowValues();
+ for(dr.resetNext(); dr.hasNext(); rowCount++ ) {
+ if(first) {
+ if(rowNames!=null) {
+ for(int i=0; i<rowNames.size(); i++) {
+ DataValue dv = rowNames.get(i);
+ cellNum += 1;
+ row.createCell((short) cellNum).setCellValue(strip.stripHtml(dv.getDisplayValue()));
+ row.getCell((short) cellNum).setCellStyle(styleDefault);
+ }
+ }
+ }
+ first = false;
+
+ DataValue dv = dr.getNext();
+ if(dv.isVisible()) {
+ String value = dv.getDisplayValue();
+ if(value.indexOf("|#")!=-1)
+ value = value.substring(0,value.indexOf("|"));
+
+ if(dr.isRowFormat() || nvl(dv.getFormatId()).length()>0) {
+ 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, "<BR/>", " ");
+ footer = Utils.replaceInString(footer, "<br/>", " ");
+ footer = Utils.replaceInString(footer, "<br>", " ");
+ 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<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>();
+ 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.onap.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.onap.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<ZipEntry> en = (Enumeration<ZipEntry>) 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("<?xml version=\"1.0\" encoding=\""+XML_ENCODING+"\"?>" +
+ "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">" );
+ _out.write("<sheetData>\n");
+ }
+
+ public void endSheet() throws IOException {
+ _out.write("</sheetData>");
+ _out.write("</worksheet>");
+ }
+
+ /**
+ * Insert a new row
+ *
+ * @param rownum 0-based row number
+ */
+ public void insertRow(int rownum) throws IOException {
+ _out.write("<row r=\""+(rownum+1)+"\">\n");
+ this._rownum = rownum;
+ }
+
+ /**
+ * Insert row end marker
+ */
+ public void endRow() throws IOException {
+ _out.write("</row>\n");
+ }
+
+ public void createCell(int columnIndex, String value, int styleIndex) throws IOException {
+ String ref = new CellReference(_rownum, columnIndex).formatAsString();
+ _out.write("<c r=\""+ref+"\" t=\"inlineStr\"");
+ if(styleIndex != -1) _out.write(" s=\""+styleIndex+"\"");
+ _out.write(">");
+ _out.write("<is><t>"+value+"</t></is>");
+ _out.write("</c>");
+ }
+
+ 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("<c r=\""+ref+"\" t=\"n\"");
+ if(styleIndex != -1) _out.write(" s=\""+styleIndex+"\"");
+ _out.write(">");
+ _out.write("<v>"+value+"</v>");
+ _out.write("</c>");
+ }
+
+ 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<String, XSSFCellStyle> loadXSSFStyles(ReportRuntime rr, XSSFWorkbook wb, Map<String, XSSFCellStyle> 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<String, XSSFCellStyle> hashMapStyles = new HashMap<String, XSSFCellStyle>();;
+ Map<String, XSSFFont> hashMapFonts = new HashMap<String, XSSFFont>();
+ 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<String, XSSFCellStyle> 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, "<BR/>", " ");
+ header = Utils.replaceInString(header, "<br/>", " ");
+ header = Utils.replaceInString(header, "<br>", " ");
+ header = strip.stripHtml(nvl(header).trim());
+ subtitle = Utils.replaceInString(subtitle, "<BR/>", " ");
+ subtitle = Utils.replaceInString(subtitle, "<br/>", " ");
+ subtitle = Utils.replaceInString(subtitle, "<br>", " ");
+ 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<String, Short> dateFormatMap = new HashMap<String, Short>();
+
+ 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, "<BR/>", " ");
+ footer = Utils.replaceInString(footer, "<br/>", " ");
+ footer = Utils.replaceInString(footer, "<br>", " ");
+ 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.onap.portalsdk.analytics.system.Globals.getFooterFirstLine().replaceAll("&", "&"), styleDefaultCell.getIndex());
+ sw.endRow();
+ rowNum += 1;
+ sw.insertRow(rowNum);
+ cellNum = 0;
+ sw.createCell(cellNum, org.onap.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; tmp<dataTypeMap.size(); tmp++){
+ String dataTypeStr = (String)(dataTypeMap.get(tmp));
+ if(dataTypeStr.equals("NUMBER")){
+ cell.setCellStyle(styleNumber);
+ }else if (dataTypeStr.equals("VARCHAR2")){
+ cell.setCellStyle(styleDefault);
+
+ }else if (dataTypeStr.equals("DATE")){
+ cell.setCellStyle(styleDate);
+ }else{
+
+ }
+
+ }*/
+ rowNum += 1;
+ sw.endRow();
+ } // for
+
+ if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols!=null) {
+
+ for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();) {
+ rowCount++;
+ sw.insertRow(rowNum);
+ cellNum = -1;
+ 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());
+
+ DataRow drTotal = rd.reportDataTotalRow.getNext();
+ if(drTotal!=null) {
+ drTotal.resetNext(); drTotal.getNext();
+ for (; drTotal.hasNext();) {
+ cellNum += 1;
+ styleCell = null;
+ DataValue dv = drTotal.getNext();
+ String value = dv.getDisplayValue();
+ sw.createCell(cellNum,value,styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex());
+ }
+ }
+
+ rowNum += 1;
+ sw.endRow();
+ }
+
+
+ String footer = (String) session.getAttribute("FOOTER_"+index);
+ if(nvl(footer).length()>0) {
+ footer = Utils.replaceInString(footer, "<BR/>", " ");
+ footer = Utils.replaceInString(footer, "<br/>", " ");
+ footer = Utils.replaceInString(footer, "<br>", " ");
+ 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.onap.portalsdk.analytics.system.Globals.getFooterFirstLine().replaceAll("&", "&"), styleDefaultCell.getIndex());
+ sw.endRow();
+ rowNum += 1;
+ sw.insertRow(rowNum);
+ cellNum = 0;
+ sw.createCell(cellNum, org.onap.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("<HTML>\n" +
+ "<HEAD><TITLE>" + rr.getReportName() + "</TITLE></HEAD>\n" +
+ "<BODY>\n" );
+ System.out.println("HTML-Excel Generation Triggered: " + new java.util.Date());
+ csvOut.print("<TABLE>");
+ 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("<TR><TD COLSPAN=\"2\">" + "Run-time Parameters" + "</TD></TR>");
+ //strBuf.append("Run-time Parameters\n");
+ }
+ csvOut.println("<TR><TD>" + value.getId() +"</TD>");
+ csvOut.println("<TD>" + value.getName().replaceAll("~",",")+ "</TD>");
+ csvOut.println("</TR>");
+
+ //strBuf.append(value.getId()+": "+ value.getName()+"\n");
+ }
+ } //for
+ csvOut.println("<TR><TD COLSPAN=\"2\"> </TD></TR>");
+ csvOut.println("<TR><TD COLSPAN=\"2\"> </TD></TR>");
+ 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<ResultSet> callable = new ExecuteQuery(st, sql_whole, downloadLimit);
+ ExecutorService executor = new ScheduledThreadPoolExecutor(5);
+ System.out.println("Time Started" + new java.util.Date());
+ Future<ResultSet> 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("<TR>");
+ for (chr.resetNext(); chr.hasNext();) {
+ ColumnHeader ch = chr.getNext();
+ if(ch.isVisible()) {
+ csvOut.print("<TD bgColor=\"8F9381\">" + ch.getColumnTitle() + "</TD>");
+ //for (int i = 1; i < ch.getColSpan(); i++)
+ // csvOut.print(",");
+
+ }
+ } // for
+ csvOut.println("</TR>");
+ } // for
+
+
+ while(rs.next()) {
+ csvOut.println("<TR>");
+/* 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("<TD>" + strip.stripCSVHtml(nvl((String)colHash.get(ch.getLinkColId().toUpperCase()))) + "</TD>");
+ }
+
+ }
+ csvOut.println("</TR>");
+ }
+ System.out.println("Downloaded Rows in HTML-Excel " + rowCount + " : "+ new java.util.Date());
+ if(rowCount == 0) {
+ csvOut.print("<TR><TD COLSPAN=\""+ numberOfColumns + "\">No Data Found</TD></TR>");
+ } else {
+ }
+ } else {
+ csvOut.println("<TR><TD COLSPAN=\""+ numberOfColumns + "\">No Data Found</TD></TR>");
+ }
+ csvOut.println("</TABLE></BODY>\n</HTML>");
+
+ } 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("<TR>");
+ for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) {
+ RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
+
+ if (firstPass) {
+ numberOfColumns++;
+ csvOut.print("<TD bgColor=\"8F9381\">" + rhc.getColumnTitle() + "</TD>");
+ }
+ //csvOut.print(",");
+ } // for
+
+
+ for (chr.resetNext(); chr.hasNext();) {
+ ColumnHeader ch = chr.getNext();
+ if(ch.isVisible()) {
+ if(firstPass) numberOfColumns++;
+ csvOut.print("<TD bgColor=\"8F9381\">" + ch.getColumnTitle() + "</TD>");
+ //for (int i = 1; i < ch.getColSpan(); i++)
+ //csvOut.print(",");
+ }
+ } // for
+ firstPass = false;
+ csvOut.println("</TR>");
+ } // for
+
+ firstPass = true;
+ for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) {
+ DataRow dr = rd.reportDataRows.getNext();
+ csvOut.println("<TR>");
+ for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) {
+ RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
+ if (firstPass)
+ rhc.resetNext();
+ RowHeader rh = rhc.getNext();
+
+ csvOut.print("<TD bgColor=\"8F9381\">" + strip.stripCSVHtml(rh.getRowTitle()) + "</TD>");
+ } // for
+ firstPass = false;
+
+ for (dr.resetNext(); dr.hasNext();) {
+ DataValue dv = dr.getNext();
+ if(dv.isVisible())
+ csvOut.print("<TD bgColor=\"8F9381\">" + strip.stripCSVHtml(dv.getDisplayValue()) + "</TD>");
+ } // for
+
+ csvOut.println("</TR>");
+
+ } // for
+ //csvOut.flush();
+ } else {
+ csvOut.println("<TR><TD COLSPAN=\""+ numberOfColumns + "\">No Data Found</TD></TR>");
+ }
+ }
+ csvOut.println("</TABLE></BODY>\n</HTML>");
+ 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();
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+/* ===========================================================================================
+ * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
+ * 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);<UL><LI> isDashboardType is made to return false, as any report can be added to Dashboard. </LI></UL>
+ * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
+ * 27-Jul-2009 : Version 8.4 (Sundar);<UL><LI>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. </LI></UL>
+ *
+ */
+package org.onap.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.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.model.base.IdNameValue;
+import org.onap.portalsdk.analytics.model.base.ReportWrapper;
+import org.onap.portalsdk.analytics.model.definition.ReportLogEntry;
+import org.onap.portalsdk.analytics.model.search.ReportSearchResult;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.DbUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.system.fusion.domain.QuickLink;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class ReportLoader extends org.onap.portalsdk.analytics.RaptorObject {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportLoader.class);
+
+ 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")
+ + "', '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>', "
+ + 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("<a href=\"" + AppUtils.getReportExecuteActionURL() + ds.getString(i, 0));
+ if(b) link.append("&PAGE_ID="+menuId+"&refresh=Y");
+ link.append("\">" +ds.getString(i, 1) + "</a>" + (Globals.getShowDescrAtRuntime() ? " - " + ds.getString(i, 2) : "") );
+ quickLinks.add(link.toString());
+ }
+
+ return quickLinks;
+ } // loadQuickLinks
+
+ public static ArrayList<QuickLink> 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<QuickLink> quickLinksArray = new ArrayList<QuickLink>(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 = "'<a class=\"hyperref1\" href=''#'' onClick=''document."+HTML_FORM+"."+AppConstants.RI_ACTION+".value=\"report.run\";"+
+ "document."+HTML_FORM+".c_master.value=\"'|| cr.rep_id||'\";document."+HTML_FORM+".submit()''>'";
+ String PRIVATE_ICON = "<img border=0 src="
+ + AppUtils.getImgFolderURL()
+ + "accessicon.gif alt=Private width=16 height=12> ";
+
+ 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||'</a>' 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||'</a>' 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("<a href=\"" + AppUtils.getReportExecuteActionURL() + ds.getString(i, 0));
+ if(b) link.append("&PAGE_ID="+menuId+"&refresh=Y");
+ link.append("\">" +ds.getString(i, 2) + "</a>" + (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("<a href=\"" + AppUtils.getRaptorActionURL()+"download.data.file&filename="
+ + ds.getString(i, 0)+"\">" + ds.getString(i, 1)+ "</a>" + " "+ 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("<a href=\"" + AppUtils.getRaptorActionURL()+"report.run.container&display_content=Y&fromReportLog=Y&refresh=Y&c_master="+ds.getString(i, 0)+ds.getString(i, 3)+"\">" + ds.getString(i, 1)+ "</a>");
+ }
+ 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(" '<a href=\"" + AppUtils.getRaptorActionURL() +"report.run.container&c_master='||x.rep_id||'&'||x.form_fields||'&fromReportLog=Y&display_content=Y&noFormFields=Y&refresh=Y\">'||x.action||'</a>'");
+ 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 '<a href=\"" + AppUtils.getRaptorActionURL() +"report.run.container&c_master='||x.rep_id||'&'||x.form_fields||'&fromReportLog=Y&display_content=Y&noFormFields=Y&refresh=Y\"><img src=\""+AppUtils.getImgFolderURL()+ "test_run.gif\" width=\"12\" height=\"12\" border=0 alt=\"Run report\"/></a>' 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
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+/* ===========================================================================================
+ * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
+ * 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);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
+ * 13-Aug-2009 : Version 8.5 (Sundar);<UL><LI>Refresh is added while running report.</LI>
+ * </UL>
+ * 27-Jul-2009 : Version 8.4 (Sundar);<UL><LI> A new sort order PUBLIC is added.</LI>
+ * <LI> 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".</LI>
+ * </UL>
+ *
+ */
+package org.onap.portalsdk.analytics.model;
+
+import java.io.*;
+import java.sql.*;
+import java.util.*;
+import javax.servlet.http.*;
+
+import org.onap.portalsdk.analytics.controller.*;
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.model.search.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+
+public class SearchHandler extends org.onap.portalsdk.analytics.RaptorObject {
+ private static final String HTML_FORM = "forma";
+ private final static String PRIVATE_ICON = "<img border=0 src="
+ + AppUtils.getImgFolderURL()
+ + "accessicon.gif alt=Private width=16 height=12> ";
+
+ 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 = "'<a class=\"hyperref1\" href=''#'' onClick=''document."+HTML_FORM+"."+AppConstants.RI_ACTION+".value=\"report.run\";"+
+ "document."+HTML_FORM+".c_master.value=\"'|| cr.rep_id||'\";document."+HTML_FORM+".refresh.value=\"Y\";document."+HTML_FORM+".submit();return false;''>'";
+ for (Iterator iter = AppUtils.getUserRoles(request).iterator(); iter.hasNext();)
+ roleList.append("," + ((String) iter.next()));
+ //<a href="#" alt="Run report" onClick="document.forma.r_action.value='report.run'; document.forma.c_master.value='1073';">
+ /*String sql = "SELECT cr.rep_id, "
+ + "cr.rep_id report_id, "
+ + rep_title_sql+
+ "||DECODE(cr.public_yn, 'Y', '', '"
+ + PRIVATE_ICON
+ + "')||cr.title||'</a>' 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 '%<allowSchedule>N</allowSchedule>%' "
+ + "then 'N' "
+ + "when report_xml like '%<allowSchedule>Y</allowSchedule>%' "
+ + "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 = "'<a class=\"hyperref1\" href=''#'' onClick=''document."+HTML_FORM+"."+AppConstants.RI_ACTION+".value=\"report.run\";"+
+ "document."+HTML_FORM+".c_master.value=\"'|| cr.rep_id||'\";document."+HTML_FORM+".submit();return false;''>'";
+ for (Iterator iter = AppUtils.getUserRoles(request).iterator(); iter.hasNext();)
+ roleList.append("," + ((String) iter.next()));
+ //<a href="#" alt="Run report" onClick="document.forma.r_action.value='report.run'; document.forma.c_master.value='1073';">
+ /*String sql = "SELECT cr.rep_id, "
+ + "cr.rep_id report_id, "
+ + rep_title_sql+
+ "||DECODE(cr.public_yn, 'Y', '', '"
+ + PRIVATE_ICON
+ + "')||cr.title||'</a>' 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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.base;
+
+import java.util.Comparator;
+
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.base;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.base;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.model.*;
+import org.onap.portalsdk.analytics.model.runtime.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+/* ===========================================================================================
+ * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
+ * 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.onap.portalsdk.analytics.model.base;
+
+import java.util.HashMap;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.system.ConnectionUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class IdNameSql extends IdNameList {
+
+ private static final 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.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.base;
+
+import java.util.Comparator;
+
+import org.onap.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
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.base;
+
+import java.util.Comparator;
+
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.base;
+
+import java.util.Comparator;
+
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.base;
+
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.Vector;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.UserAccessException;
+import org.onap.portalsdk.analytics.model.definition.SecurityEntry;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.DbUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class ReportSecurity extends org.onap.portalsdk.analytics.RaptorObject {
+
+ private static final 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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.base;
+
+import java.io.*;
+import java.sql.*;
+import java.util.*;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalsdk.analytics.controller.ActionHandler;
+import org.onap.portalsdk.analytics.error.*;
+import org.onap.portalsdk.analytics.model.base.*;
+import org.onap.portalsdk.analytics.model.definition.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+@Entity
+public class ReportUserRole extends org.onap.portalsdk.analytics.RaptorObject implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ private Long repId = null;
+
+ @Id
+ @GeneratedValue(strategy=GenerationType.AUTO)
+ private Long orderNo = null;
+
+ private Long roleId = null;
+
+ private Long userId = null;
+
+ private String readOnlyYn = null;
+
+ public ReportUserRole() {
+ super();
+ }
+
+ public ReportUserRole(Long repId, Long orderNo, Long roleId, Long userId, String readOnlyYn) {
+ super();
+ this.repId = repId;
+ this.orderNo = orderNo;
+ this.roleId = roleId;
+ this.userId = userId;
+ this.readOnlyYn = readOnlyYn;
+ }
+
+ public Long getRepId() {
+ return repId;
+ }
+
+ public void setRepId(Long repId) {
+ this.repId = repId;
+ }
+
+ public Long getOrderNo() {
+ return orderNo;
+ }
+
+ public void setOrderNo(Long orderNo) {
+ this.orderNo = orderNo;
+ }
+
+ public Long getRoleId() {
+ return roleId;
+ }
+
+ public void setRoleId(Long roleId) {
+ this.roleId = roleId;
+ }
+
+ public Long getUserId() {
+ return userId;
+ }
+
+ public void setUserId(Long userId) {
+ this.userId = userId;
+ }
+
+ public String getReadOnlyYn() {
+ return readOnlyYn;
+ }
+
+ public void setReadOnlyYn(String readOnlyYn) {
+ this.readOnlyYn = readOnlyYn;
+ }
+
+
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
+import org.onap.portalsdk.analytics.error.UserDefinedException;
+import org.onap.portalsdk.analytics.model.DataCache;
+import org.onap.portalsdk.analytics.model.ReportLoader;
+import org.onap.portalsdk.analytics.model.definition.TableSource;
+import org.onap.portalsdk.analytics.model.runtime.FormField;
+import org.onap.portalsdk.analytics.model.runtime.ReportParamValues;
+import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.ConnectionUtils;
+import org.onap.portalsdk.analytics.system.DbUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.SQLCorrector;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.analytics.xmlobj.ChartAdditionalOptions;
+import org.onap.portalsdk.analytics.xmlobj.ChartDrillFormfield;
+import org.onap.portalsdk.analytics.xmlobj.ChartDrillOptions;
+import org.onap.portalsdk.analytics.xmlobj.ColFilterList;
+import org.onap.portalsdk.analytics.xmlobj.ColFilterType;
+import org.onap.portalsdk.analytics.xmlobj.CustomReportType;
+import org.onap.portalsdk.analytics.xmlobj.DashboardEditorList;
+import org.onap.portalsdk.analytics.xmlobj.DashboardReports;
+import org.onap.portalsdk.analytics.xmlobj.DashboardReportsNew;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnList;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
+import org.onap.portalsdk.analytics.xmlobj.DataSourceList;
+import org.onap.portalsdk.analytics.xmlobj.DataSourceType;
+import org.onap.portalsdk.analytics.xmlobj.DataminingOptions;
+import org.onap.portalsdk.analytics.xmlobj.FormFieldList;
+import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
+import org.onap.portalsdk.analytics.xmlobj.FormatList;
+import org.onap.portalsdk.analytics.xmlobj.FormatType;
+import org.onap.portalsdk.analytics.xmlobj.JavascriptItemType;
+import org.onap.portalsdk.analytics.xmlobj.JavascriptList;
+import org.onap.portalsdk.analytics.xmlobj.Marker;
+import org.onap.portalsdk.analytics.xmlobj.ObjectFactory;
+import org.onap.portalsdk.analytics.xmlobj.PDFAdditionalOptions;
+import org.onap.portalsdk.analytics.xmlobj.PredefinedValueList;
+import org.onap.portalsdk.analytics.xmlobj.ReportMap;
+import org.onap.portalsdk.analytics.xmlobj.Reports;
+import org.onap.portalsdk.analytics.xmlobj.SemaphoreList;
+import org.onap.portalsdk.analytics.xmlobj.SemaphoreType;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+/**<HR/>
+ * This class is part of <B><I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I></B><BR/>
+ * <HR/>
+ *
+ * --------------------------------------------------------------------------------------------------<BR/>
+ * <B>ReportWrapper.java</B> - This is the base class for the RAPTOR. This involves in creating,<BR/>
+ * modifying, running RAPTOR reports.<BR/>
+ * --------------------------------------------------------------------------------------------------<BR/>
+ *
+ *
+ * <U>Change Log</U><BR/><BR/>
+ *
+ * 31-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> All the elements in the meta xml is copied to the target reports. </LI></UL>
+ * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
+ * 27-Jul-2009 : Version 8.4 (Sundar); <UL><LI> verifySQLBasedReportAccess method checks for Admin user instead of super user. </LI></UL>
+ * 09-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Bug due to parsing and removing formfields from "and" is bulletproofed to the right "and" to which the formfield is associated. </LI></UL>
+ * 08-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Bug due to parsing and removing formfields when there is no parameter for Daytona specific database is resolved. </LI></UL>
+ * 29-Jun-2009 : Version 8.4 (Sundar); <UL><LI> isLastSeriesALineChart() and setLastSeriesALineChart(String value) method have been added for the Bar Chart enhancements. </LI></UL>
+ * 23-Jun-2009 : Version 8.4 (Sundar); <UL><LI> check for cr.getChartAdditionalOptions() for null value is added.</LI></UL>
+ * 22-Jun-2009 : Version 8.4 (Sundar); <UL><LI> 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.</LI></UL>
+ *
+ */
+
+public class ReportWrapper extends org.onap.portalsdk.analytics.RaptorObject {
+
+ private static final 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.onap.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.onap.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<Item> getChartValueColumnsListModelList( int filter, HashMap formValues) { / *filter; all=0;create without new chart =1; createNewChart=2 * /
+ List reportCols = getAllColumns();
+
+ ArrayList chartValueCols = new ArrayList();
+ ListModelList<Item> chartValueListModelList = new ListModelList<Item>();
+ 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<DataColumnType> 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.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.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.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.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<ds.getColumnCount(); k++) {
+ if(dct.getColId().toUpperCase().trim().equals(ds.getColumnName(k).trim())) {
+ reportCols.add(dct);
+ continue outer;
+ }
+ }
+ }
+
+ if (getFormFieldList() != null) {
+ String paramValue = "";
+ for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
+ FormFieldType fft = (FormFieldType) iter.next();
+ if(fft.isGroupFormField()!=null && fft.isGroupFormField().booleanValue()) {
+ paramValue = Utils.oracleSafe(nvl(paramValues
+ .getParamValue(fft.getFieldId())));
+ outer:
+ for (Iterator iter1 = reportCols1.iterator(); iter1.hasNext();) {
+ DataColumnType dct = (DataColumnType) iter1.next();
+ if(("["+fft.getFieldName()+ "]").equals(dct.getColName().trim())) {
+ dct.setDisplayName(paramValue);
+ continue outer;
+ }
+ }
+
+
+ }
+ }
+ }
+
+ }
+
+ for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
+ DataColumnType dc = (DataColumnType) iter.next();
+ //TODO: commented if (dc.isVisible()) {
+ if (colNames.length() > 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.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.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.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.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.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.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.onap.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.onap.portalsdk.analytics.xmlobj");
+ Unmarshaller u = jc.createUnmarshaller();
+ javax.xml.bind.JAXBElement<CustomReportType> doc = (javax.xml.bind.JAXBElement<CustomReportType>) 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.onap.portalsdk.analytics.xmlobj.ChartDrillFormfield cdf = (org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition;
+
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition;
+
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition;
+
+import org.onap.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;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.controller.WizardSequence;
+import org.onap.portalsdk.analytics.controller.WizardSequenceCrossTab;
+import org.onap.portalsdk.analytics.controller.WizardSequenceDashboard;
+import org.onap.portalsdk.analytics.controller.WizardSequenceLinear;
+import org.onap.portalsdk.analytics.controller.WizardSequenceSQLBasedCrossTab;
+import org.onap.portalsdk.analytics.controller.WizardSequenceSQLBasedHive;
+import org.onap.portalsdk.analytics.controller.WizardSequenceSQLBasedLinear;
+import org.onap.portalsdk.analytics.controller.WizardSequenceSQLBasedLinearDatamining;
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.model.DataCache;
+import org.onap.portalsdk.analytics.model.ReportLoader;
+import org.onap.portalsdk.analytics.model.base.OrderBySeqComparator;
+import org.onap.portalsdk.analytics.model.base.OrderSeqComparator;
+import org.onap.portalsdk.analytics.model.base.ReportWrapper;
+import org.onap.portalsdk.analytics.model.runtime.FormField;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.DbUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.analytics.xmlobj.ChartAdditionalOptions;
+import org.onap.portalsdk.analytics.xmlobj.ChartDrillOptions;
+import org.onap.portalsdk.analytics.xmlobj.ColFilterType;
+import org.onap.portalsdk.analytics.xmlobj.CustomReportType;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnList;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
+import org.onap.portalsdk.analytics.xmlobj.DataSourceType;
+import org.onap.portalsdk.analytics.xmlobj.DataminingOptions;
+import org.onap.portalsdk.analytics.xmlobj.FormFieldList;
+import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
+import org.onap.portalsdk.analytics.xmlobj.FormatList;
+import org.onap.portalsdk.analytics.xmlobj.FormatType;
+import org.onap.portalsdk.analytics.xmlobj.JavascriptItemType;
+import org.onap.portalsdk.analytics.xmlobj.ObjectFactory;
+import org.onap.portalsdk.analytics.xmlobj.PredefinedValueList;
+import org.onap.portalsdk.analytics.xmlobj.SemaphoreType;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+/**<HR/>
+ * This class is part of <B><I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I></B><BR/>
+ * <HR/>
+ *
+ * --------------------------------------------------------------------------------------------------<BR/>
+ * <B>ReportDefinition.java</B> - This involves in creating and modifying RAPTOR reports.
+ * --------------------------------------------------------------------------------------------------<BR/>
+ *
+ *
+ * <U>Change Log</U><BR/><BR/>
+ *
+ * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
+ * 27-Jul-2009 : Version 8.4 (Sundar); <UL><LI>userIsAuthorizedToSeeLog is checked for Admin User instead of Super User.</LI></UL>
+ * 22-Jun-2009 : Version 8.4 (Sundar); <UL><LI>A new type ChartAdditionalOptions is introduced in RAPTOR XSD.
+ * For this type a create procedure is added to this class.</LI></UL>
+ *
+ */
+
+public class ReportDefinition extends ReportWrapper implements Serializable {
+
+ private static final 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.onap.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.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.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.onap.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.onap.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.onap.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.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition;
+
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import org.onap.portalsdk.analytics.RaptorObject;
+import org.onap.portalsdk.analytics.view.DataRow;
+import org.onap.portalsdk.analytics.view.DataValue;
+import org.onap.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;
+ }
+
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.RaptorObject;
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.error.UserDefinedException;
+import org.onap.portalsdk.analytics.model.base.IdNameValue;
+import org.onap.portalsdk.analytics.model.base.NameComparator;
+import org.onap.portalsdk.analytics.model.runtime.FormField;
+import org.onap.portalsdk.analytics.model.runtime.ReportParamValues;
+import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.ConnectionUtils;
+import org.onap.portalsdk.analytics.system.DbUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class ReportSchedule extends RaptorObject {
+
+ private static final 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<IdNameValue> 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<IdNameValue> 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.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition;
+
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition;
+
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition;
+
+import org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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;
+ private String errorMessage;
+ private String errorStackTrace;
+
+ public String getTabId() {
+ return tabId;
+ }
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+ public String getErrorStackTrace() {
+ return errorStackTrace;
+ }
+ public void setErrorStackTrace(String errorStackTrace) {
+ this.errorStackTrace = errorStackTrace;
+ }
+ 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;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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<IdNameBooleanJSON> 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<NameBooleanJSON> 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<IdNameBooleanJSON> getDisplayArea() {
+ return displayArea;
+ }
+
+ public void setDisplayArea(List<IdNameBooleanJSON> 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<NameBooleanJSON> getDisplayOptions() {
+ return displayOptions;
+ }
+
+ public void setDisplayOptions(List<NameBooleanJSON> 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;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition.wizard;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+import org.onap.portalsdk.analytics.view.ColumnHeader;
+
+public interface ElementJSON {
+
+ // To be defined by child class
+ public String getId();
+ public String getName();
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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<IdNameBooleanJSON> predefinedValueList;
+ private String message;
+ private String errorMessage;
+ private String errorStackTrace;
+
+
+ public String getMessage() {
+ return message;
+ }
+ public void setMessage(String message) {
+ this.message = message;
+ }
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+ public String getErrorStackTrace() {
+ return errorStackTrace;
+ }
+ public void setErrorStackTrace(String errorStackTrace) {
+ this.errorStackTrace = errorStackTrace;
+ }
+ 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<IdNameBooleanJSON> getPredefinedValueList() {
+ return predefinedValueList;
+ }
+ public void setPredefinedValueList(List<IdNameBooleanJSON> predefinedValueList) {
+ this.predefinedValueList = predefinedValueList;
+ }
+ public String getFieldSQL() {
+ return fieldSQL;
+ }
+ public void setFieldSQL(String fieldSQL) {
+ this.fieldSQL = fieldSQL;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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;
+ }
+
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition.wizard;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+import org.onap.portalsdk.analytics.view.ColumnHeader;
+
+public class ListJSON {
+
+ private ArrayList<ElementJSON> elements;
+
+ public ArrayList<ElementJSON> getElements() {
+ return elements;
+ }
+
+ public void setElements(ArrayList<ElementJSON> elements) {
+ this.elements = elements;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.model.base.IdNameValue;
+import org.onap.portalsdk.analytics.view.ColumnHeader;
+import org.onap.portalsdk.analytics.view.DataValue;
+import org.onap.portalsdk.analytics.xmlobj.ColFilterList;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnList;
+import org.onap.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;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition.wizard;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+import org.onap.portalsdk.analytics.model.definition.wizard.WizardJSON;
+import org.onap.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;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition.wizard;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+import org.onap.portalsdk.analytics.view.ColumnHeader;
+
+public class QueryResultJSON {
+
+ private String query;
+
+ private int totalRows;
+ private ArrayList<String> reportDataColumns;
+ private ArrayList<Map<String,String>> 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<String> getReportDataColumns() {
+ return reportDataColumns;
+ }
+
+ public void setReportDataColumns(ArrayList<String> reportDataColumns) {
+ this.reportDataColumns = reportDataColumns;
+ }
+
+ public ArrayList<Map<String, String>> getReportDataRows() {
+ return reportDataRows;
+ }
+
+ public void setReportDataRows(ArrayList<Map<String, String>> reportDataRows) {
+ this.reportDataRows = reportDataRows;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition.wizard;
+
+public class RaptorError extends RaptorResponse{
+ public RaptorError(String theMessage) {
+ error().put("message", theMessage);
+ }
+
+ public RaptorError(String theMessage, Throwable theError) {
+ error().put("message", theMessage)
+ .put("exception", theError.toString());
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition.wizard;
+
+import org.json.JSONObject;
+
+import com.fasterxml.jackson.annotation.JsonRawValue;
+
+public class RaptorResponse {
+ private JSONObject data = new JSONObject(),
+ error = new JSONObject();
+
+ public RaptorResponse() {
+ }
+
+ public JSONObject data() {
+ return this.data;
+ }
+
+ @JsonRawValue
+ public String getData() {
+ return this.data.toString();
+ }
+
+ public JSONObject error() {
+ return this.error;
+ }
+
+ @JsonRawValue
+ public String getError() {
+ return this.error.toString();
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.definition.wizard;
+
+public interface WizardJSON {
+
+ public String getTabName();
+ public void setTabName(String tabName);
+ public String getTabId();
+ public void setTabId(String tabId);
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.pdf;
+
+import java.awt.Color;
+import java.io.File;
+import java.io.IOException;
+import java.net.MalformedURLException;
+
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.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("<no logo>"))
+ howManyLogos ++;
+
+ if(AppUtils.isNotEmpty(pb.getLogo2Url()) && !pb.getLogo2Url().equalsIgnoreCase("<no logo>"))
+ 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("<no logo>"))
+ 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("<no logo>"))
+ 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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+/* ===========================================================================================
+ * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
+ * 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); <UL>
+ * <LI> Dashboard reports can be downloaded with each report occupying separate page including its charts. </LI>
+ * </UL>
+ *
+ */
+package org.onap.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.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.model.ReportHandler;
+import org.onap.portalsdk.analytics.model.ReportLoader;
+import org.onap.portalsdk.analytics.model.base.IdNameValue;
+import org.onap.portalsdk.analytics.model.definition.ReportDefinition;
+import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.ConnectionUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.HtmlStripper;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.analytics.view.ColumnHeader;
+import org.onap.portalsdk.analytics.view.ColumnHeaderRow;
+import org.onap.portalsdk.analytics.view.DataRow;
+import org.onap.portalsdk.analytics.view.DataValue;
+import org.onap.portalsdk.analytics.view.HtmlFormatter;
+import org.onap.portalsdk.analytics.view.ReportData;
+import org.onap.portalsdk.analytics.view.RowHeader;
+import org.onap.portalsdk.analytics.view.RowHeaderCol;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
+import org.onap.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.onap.portalsdk.analytics.RaptorObject{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PdfReportHandler.class);
+
+ private PdfBean pb;
+ private HtmlStripper strip = new HtmlStripper();
+ private static final int RetryCreateNewImage = 3;
+ private int retryCreateNewImageCount=0;
+
+ 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 ; i<paraList.size(); i++) {
+ reportDescrBuf.append(paraList.get(i));
+ }
+
+ }
+ add2Cells(table,"Description : ",reportDescrBuf.toString());
+ 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 : ",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; i<rows; i++)
+ for(int j=0;j<table.getAbsoluteWidths().length;j++)
+ table.addCell(new Paragraph(" "));
+
+ }
+
+ private void add2Cells(PdfPTable table, String key, String value) {
+
+ PdfPCell cell;
+ cell = new PdfPCell(new Paragraph(key));
+ cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
+ cell.setBorderWidth(0f);
+ table.addCell(cell);
+
+ cell = new PdfPCell(new Paragraph(value));
+ cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
+ cell.setBorderWidth(0f);
+ table.addCell(cell);
+ }
+
+ private void paintPdfImage(HttpServletRequest request, Document document, String fileName, ReportRuntime rr)
+ throws DocumentException
+ {
+
+ ArrayList images = getImage(request, fileName,pb.isAttachmentOfEmail()?true:false, rr);
+ //Image image = getImage(request, fileName,pb.isAttachmentOfEmail()?true:false);
+ PdfPTable table = null;
+ PdfPCell cellValue = null;
+ if(images!=null) {
+
+ for (int i = 0; i < images.size(); i++) {
+ table = new PdfPTable(1);
+ cellValue = new PdfPCell();
+ cellValue.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
+ Image image = (Image) images.get(i);
+ image.setAlignment(Image.ALIGN_CENTER);
+ //System.out.println("Document 3 " + document + " i-" + i);
+ if(i%2 ==0)
+ document.newPage();
+ //System.out.println("Document 31 " + document);
+ cellValue.setImage(image);
+ //table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
+ table.addCell(cellValue);
+ //System.out.println("Document 32 " + document + "table " + table);
+ document.add(table);
+ //System.out.println("Document 33 " + document);
+ }
+ }
+ }
+
+ private ArrayList getImage(HttpServletRequest request, String fileName, boolean isGenerateNewImage, ReportRuntime rr) {
+ ArrayList images = new ArrayList();
+ if(!isGenerateNewImage) {
+ try {
+ Image image = Image.getInstance(fileName);
+ images.add(image);
+ return images;
+ }
+ catch (MalformedURLException e) {
+ isGenerateNewImage = true;
+ //e.printStackTrace();
+ }
+ catch (BadElementException e) {
+ isGenerateNewImage = true;
+ //e.printStackTrace();
+
+ } catch (FileNotFoundException e) {
+ isGenerateNewImage = true;
+ //e.printStackTrace();
+ } catch (IOException e) {
+ isGenerateNewImage = true;
+ //e.printStackTrace();
+ }
+ }
+
+ if(isGenerateNewImage && retryCreateNewImageCount<RetryCreateNewImage){
+ retryCreateNewImageCount++;
+ return generateNewImage(request, rr);
+ //return getImage(request,fileName, false);
+ }
+
+ return null;
+
+ }
+
+ private ArrayList generateNewImage(HttpServletRequest request, ReportRuntime rr) {
+ ArrayList images = new ArrayList();
+ try {
+ //ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
+ DataSet ds = null;
+ if(request.getSession().getAttribute(AppConstants.RI_CHART_DATA)!=null) {
+ ds = (DataSet) request.getSession().getAttribute(AppConstants.RI_CHART_DATA);
+ } else {
+ ds = rr.loadChartData(pb.getUserId(),request);
+ }
+ String downloadFileName = "";
+ HashMap additionalChartOptionsMap = new HashMap();
+ String chartType = nvl(rr.getChartType());
+ if(chartType.equals(AppConstants.GT_PIE_MULTIPLE)) {
+ additionalChartOptionsMap.put("multiplePieOrderRow", new Boolean((AppUtils.getRequestNvlValue(request, "multiplePieOrder").length()>0?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; i<rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues).size();i++) {
+ String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
+ chartTitle = rr.getFormFieldFilled(chartTitle);
+ downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
+ filename = null;/*(String) ChartGen.generateChart( chartType,
+ request.getSession(),
+ ds,
+ legendColumnName,
+ chartLeftAxisLabel,
+ chartRightAxisLabel,
+ rr.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i, i+1),
+ rr.getChartColumnColorsList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i, i+1),
+ rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i, i+1),
+ "",
+ chartTitle,
+ null,
+ rr.getChartWidthAsInt(),
+ rr.getChartHeightAsInt(),
+ rr.getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i,i+1),
+ 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();
+ }
+ }
+
+ } else { /** first check the columns to be opened in new charts and loop around in ChartGen generate chart function - sundar**/
+ String tempChartGroupPrev = "";
+ String tempChartGroupCurrent = "";
+ for (int i=0; i<lGroups.size();i++) {
+ String chartGroupOrg = (String) lGroups.get(i);
+ String chartYAxis = (String) mapYAxis.get(chartGroupOrg);
+ //System.out.println("chartGroupOrg " + chartGroupOrg);
+ if(nvl(chartGroupOrg).length()>0)
+ 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<rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).size();i++) {
+ //System.out.println(" rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1) " + rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1));
+ //System.out.println(" rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1) " + rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1));
+ //System.out.println(" rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i,i+1) " + rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i,i+1));
+
+ downloadFileName = AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
+ String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
+ chartTitle = rr.getFormFieldFilled(chartTitle);
+
+ filename = null; /*(String) ChartGen.generateChart( chartType,
+ request.getSession(),
+ ds,
+ legendColumnName,
+ chartLeftAxisLabel,
+ chartRightAxisLabel,
+ (chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1),
+ (chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartColumnColorsList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartColumnColorsList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1),
+ (chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1),
+ "",
+ chartTitle,
+ null,
+ rr.getChartWidthAsInt(),
+ rr.getChartHeightAsInt(),
+ rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i,i+1),
+ 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();
+ }
+ }
+ }
+ /** second rest of the columns are merged to one single chart - sundar**/
+ // System.out.println(" rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
+ // System.out.println(" rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
+ // System.out.println(" rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
+
+ if((!(lGroups!=null && lGroups.size() > 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<DataValue> 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; i<rowNames.size(); i++) {
+ DataValue dv = rowNames.get(i);
+ rfmt = dr.getRowFormatter();
+
+ cellFont = FontFactory.getFont(FONT_FAMILY,
+ FONT_SIZE,
+ Font.NORMAL, Color.BLACK);
+ if(rfmt != null) {
+ cellFormatterFont(rfmt,cellFont);
+ }
+ cellValue = dv.getDisplayValue();
+ if(cellValue.indexOf("|#")!=-1)
+ cellValue = cellValue.substring(0,cellValue.indexOf("|"));
+
+ 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);
+ }
+ }
+ }
+ first = false;
+
+ if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*Globals.getMemoryThreshold()/100) ) {
+ returnValue = 1;
+ }
+
+ //addRowHeader(table,dr,idx,rd);
+
+ addRowColumns(table,dr,idx);
+
+ if (idx % fragmentsize == fragmentsize - 1) {
+ document.add(table);
+ table.deleteBodyRows();
+ table.setSkipFirstHeader(true);
+ }
+ }
+
+ }
+ }
+
+ //document.add(table);
+
+ }
+
+ document.add(table);
+ paintPdfReportFooter(request, document, rr, f);
+
+ return returnValue;
+ }
+
+ private void addRowHeader(PdfPTable table, DataRow dr, int idx, ReportData rd) {
+
+ table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
+
+ for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
+ RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
+ if(idx==0)
+ rhc.resetNext();
+ RowHeader rh = rhc.getNext();
+ //System.out.println(" =============== RowHeader\n "+rh);
+
+ Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY,
+ FONT_SIZE,
+ Font.NORMAL, Color.BLACK);
+ if(rh.isBold()) {
+ rowHeaderFont.setStyle(Font.BOLD);
+ rowHeaderFont.setSize(FONT_SIZE+1f);
+ }
+
+ if(rh.getColSpan()>0) {
+ 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; i<relativeWidths.length; i++)
+ relativeWidths[i] = 10f;
+
+ int index=0;
+ boolean firstPass = true;
+
+ for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();)
+ {
+ if(firstPass) {
+ /*if(rd.reportTotalRowHeaderCols!=null) {
+ String columnWidth = "5";
+
+ if(columnWidth != null && columnWidth.trim().endsWith("%"))
+ relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
+
+ index++;
+ }*/
+
+ for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
+ String columnWidth = rd.reportRowHeaderCols.getNext().getColumnWidth();
+
+ if(columnWidth != null && columnWidth.trim().endsWith("%"))
+ relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
+
+ index++;
+ }
+ firstPass = false;
+ }
+
+ ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
+ for (chr.resetNext(); chr.hasNext();) {
+
+ ColumnHeader ch = chr.getNext();
+
+ if(ch.isVisible()) {
+
+ String columnWidth = ch.getColumnWidth();
+
+ if(ch.getColSpan() <= 1){
+ if(columnWidth != null && columnWidth.trim().endsWith("%"))
+ relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
+ }
+ else {
+ for(int i=0; i<ch.getColSpan(); i++) {
+ index += i;
+ if(columnWidth != null && columnWidth.trim().endsWith("%"))
+ relativeWidths[index] =
+ (Float.parseFloat(removeLastCharacter(columnWidth)))/ch.getColSpan();
+ }
+ }
+
+ index++;
+ }
+ }
+ }
+
+ return relativeWidths;
+ }
+
+ public static String removeLastCharacter(String str) {
+ return str.substring(0, str.length()-1);
+ }
+
+ private PdfPTable paintPdfReportHeader(HttpServletRequest request, Document document, PdfPTable table, 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("TITLE_"+index);
+ String subtitle = (String) session.getAttribute("SUBTITLE_"+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-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, "<BR/>", " ");
+ title = Utils.replaceInString(title, "<br/>", " ");
+ title = Utils.replaceInString(title, "<br>", " ");
+ title = strip.stripHtml(nvl(title).trim());
+ //subtitle = Utils.replaceInString(subtitle, "<BR/>", " ");
+ //subtitle = Utils.replaceInString(subtitle, "<br/>", " ");
+ //subtitle = Utils.replaceInString(subtitle, "<br>", " ");
+ //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, "<BR/>", " ");
+ title = Utils.replaceInString(title, "<br/>", " ");
+ title = Utils.replaceInString(title, "<br>", " ");
+ 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"));
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+public class CategoryAxisJSON extends IndexValueJSON {
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.model.ReportHandler;
+import org.onap.portalsdk.analytics.model.base.ChartSeqComparator;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.ConnectionUtils;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.HtmlStripper;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.analytics.view.ReportData;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
+import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.web.support.UserUtils;
+
+public class ChartD3Helper {
+
+ private static final 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<String, String> chartOptionsMap = new HashMap<String, String>();
+ 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<String,String> chartOptionsMap = new HashMap<String, String>();
+ 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<String,String> 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<String> ts1 = new HashSet();
+ ArrayList<String> ts1 = new ArrayList();
+ HashMap<String, String> 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("<!DOCTYPE html>\n");
+ wholeScript.append("<html>\n");
+ wholeScript.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF8\">\n");
+ wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n");
+ wholeScript.append("<link href=\""+ chartScriptsPath +"d3/css/nv.d3.css\" rel=\"stylesheet\" type=\"text/css\">\n");
+ //wholeScript.append("")
+ wholeScript.append("<style>\n " +
+ " body { \n" +
+ " overflow-y:scroll; \n" +
+ " } \n" +
+ " text { \n" +
+ " font: 12px sans-serif; \n" +
+ " } \n" +
+ " svg { \n" +
+ " display: block;\n" +
+ " } \n" +
+ " #chart"+reportRuntime.getReportID()+" svg { \n" +
+ " height: "+ (nvl(height).length()>0?(height.endsWith("px")?height:height+"px"):"420px") + "; \n" +
+ " width: "+ (nvl(width).length()>0?(width.endsWith("px")?width:width+"px"):"700px") + "; \n" +
+ " min-width: 100px; \n" +
+ " min-height: 100px; \n" +
+ " } \n" +
+ " tr.z-row-over > td.z-row-inner, tr.z-row-over > .z-cell {" +
+ " background-color: rgb(255, 255, 255); "+
+ "} \n");
+
+ wholeScript.append(".nodatadiv {\n");
+ wholeScript.append(" display: table-cell;\n");
+ wholeScript.append(" width: 700px;\n");
+ wholeScript.append(" height:370px;\n");
+ wholeScript.append(" text-align:center;\n");
+ wholeScript.append(" vertical-align: middle;\n");
+ wholeScript.append("}\n");
+ wholeScript.append(".nodatainner {\n");
+ wholeScript.append(" padding: 10px;\n");
+ wholeScript.append("}\n");
+
+ wholeScript.append(" </style> \n" );
+ wholeScript.append("<body> \n");
+ if(showTitle)
+ wholeScript.append("<div align=\"center\"><H3>" + title +"</H3></div>");
+
+ wholeScript.append("<div id=\"chart"+reportRuntime.getReportID()+"\"> <svg></svg> </div> \n");
+ //js files
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/d3.v3.min.js\"></script>");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/nv.d3.min.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/tooltip.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/utils.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/axis.min.js\"></script> \n");
+ //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/discreteBar.js\"></script> \n");
+ //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/discreteBarChart.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/multiChart.js\"></script> \n");
+ //json
+ wholeScript.append("<script> \n");
+ wholeScript.append("historicalBarChart = [ \n");
+ //wholeScript.append("{ \n");
+ // data
+ ArrayList dataSeries = new ArrayList();
+
+ String uniqueElement = "";
+ for (int i = 0; i < uniqueElements.length; i++) {
+ uniqueElement = (String)uniqueElements[i];
+ if(multipleSeries && (nvl(chartRightAxisLabel).length() > 0))
+ dataSeries.add(new StringBuffer(" { \"type\":\"bar\", \"key\": \""+ (hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement) +"\", \"yAxis\": \""+(i+1)+"\", "+ (hasCustomizedChartColor?("\"color\": \""+uniqueElement.substring(uniqueElement.indexOf("|")+1) + "\","):"")+"\"values\": ["));
+ else
+ dataSeries.add(new StringBuffer(" { \"type\":\"bar\", \"key\": \""+ (hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement) +"\", \"yAxis\": \""+(1)+"\", "+ (hasCustomizedChartColor?("\"color\": \""+uniqueElement.substring(uniqueElement.indexOf("|")+1) + "\","):"")+"\"values\": ["));
+ }
+
+ // added to load all date elements
+ HashMap<String, HashMap<String, String>> dataSeriesMap = new HashMap<String, HashMap<String, String>>();
+
+ for (int i = 0; i < uniqueElements.length; i++) {
+ if(multipleSeries && (nvl(chartRightAxisLabel).length() > 0))
+ dataSeriesMap.put((String) uniqueElements[i], new HashMap<String, String>());
+ //dataSeries.add(new StringBuffer(" { \"type\":\"bar\", \"key\": \""+ uniqueElements[i] +"\", \"yAxis\": \""+(i+1)+"\", \"values\": ["));
+ else
+ dataSeriesMap.put((String) uniqueElements[i], new HashMap<String, String>());
+
+ //dataSeries.add(new StringBuffer(" { \"type\":\"bar\", \"key\": \""+ uniqueElements[i] +"\", \"yAxis\": \""+(1)+"\", \"values\": ["));
+ }
+
+ 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<String> dateStrList = new TreeSet<String>();
+ // added to store all date elements
+ SortedSet<String> sortSet = new TreeSet<String>();
+ int count = 0;
+ if(flag!= 1) {
+ HashMap dataSeriesStrMap = new HashMap();
+ HashMap dataSeriesOverAllMap = new HashMap();
+ String valueDataSeries = "";
+
+ for (int j = 0; j < uniqueElements.length; j++) {
+ dataSeriesStrMap = new HashMap();
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ flagNoDate = 0;
+ YAXISNUM = 0;
+ YAXISDOUBLENUM = 0.0;
+ flagNull= 0;
+ dateStr = ds.getString(i, 1);
+ if(timeAxis) {
+ date = getDateFromDateStr(dateStr);
+ formatFlag = getFlagFromDateStr(dateStr);
+ }
+ uniqueElement = (String)uniqueElements[j];
+ if(date==null) {
+ //continue;
+ flagNoDate = 1;
+ int pos = 0;
+ //if(!((String)uniqueElementsList.get(i)).equals(dateStr)) {
+ for (int f=0 ; f< uniqueXAxisElements.length; f++) {
+ if(uniqueXAxisElements[f].equals(dateStr)){
+ pos = f ;
+ break;
+ }
+ }
+ /*for(int f=0; f<uniqueElementsList.size() && f < pos; f++)
+ {
+ StringBuffer strBuf = ((StringBuffer)dataSeries.get(j));
+ if(strBuf.indexOf((String)uniqueElementsList.get(f)) < 0 ) {
+ dataSeriesStrMap.put((String)uniqueElementsList.get(f), value);
+ //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + (String)uniqueElementsList.get(f) + "\" , \"y\": null },");
+ }
+ }*/
+ //}
+
+ dateStrList.add("'"+dateStr+"'");
+ //uniqueElement = (String)uniqueElements[j];
+ try {
+ YAXISNUM = Integer.parseInt(ds.getString(i, columnMap.get((hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement))));
+ //if(MAXNUM < YAXISNUM) MAXNUM = YAXISNUM;
+ if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
+ } catch (NumberFormatException ex) {
+ try {
+ YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, columnMap.get((hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement))));
+ MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
+ if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
+ } catch (NumberFormatException ex1) {
+ flagNull = 1;
+ }
+ //flagNull = 1;
+ }
+ /* For Non-date type value enclose with double quotes */
+ // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
+ if(logScale) {
+ // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():(YAXISNUM>0?new Double(Math.log10(new Integer(YAXISNUM).doubleValue())).toString():null)):null) +"}, ");
+ valueDataSeries = "{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ";
+ dataSeriesStrMap.put(dateStr, valueDataSeries);
+ } else {
+ //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
+ valueDataSeries = "{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ";
+ dataSeriesStrMap.put(dateStr, valueDataSeries);
+
+ }
+
+ dataSeriesOverAllMap.put(uniqueElements[j], dataSeriesStrMap);
+
+ //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":\"" + ds.getString(i, columnMap.get((String)uniqueElements[j])) +"\"}, ");
+ } else {
+
+ if(!barRealTimeAxis) { // true - non-time
+ if(!dateStrList.contains(new Long(date.getTime()).toString())) {
+ dateStrList.add(new Long(date.getTime()).toString());
+ for (int k = 0; k < uniqueElements.length; k++) {
+ //((StringBuffer) dataSeries.get(k)).append ("{ \"x\":" + date.getTime() + " , \"y\":null}, ");
+ HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[k]);
+ dataMap.put(date.getTime()+"", "null");
+
+ }
+ }
+ }
+ //if(ds.getString(i, 2).equals(uniqueElements[j])) {
+ /*if(!dateStrList.contains(new Long(date.getTime()).toString())) {
+ for (int k = 0; k < uniqueElements.length; k++) {
+ ((StringBuffer) dataSeries.get(k)).append ("{ \"x\":" + date.getTime() + " , \"y\":null}, ");
+ }
+ }*/
+ //dateStrList.add(new Long(date.getTime()).toString());
+ try {
+ YAXISNUM = Integer.parseInt(ds.getString(i, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
+ dateStrList.add(new Long(date.getTime()).toString());
+ //if(MAXNUM < YAXISNUM) MAXNUM = YAXISNUM;
+ if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
+ } catch (NumberFormatException ex) {
+ try {
+ YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
+ MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
+ if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
+ } catch (NumberFormatException ex1) {
+ flagNull = 1;
+ }
+
+ //flagNull = 1;
+ }
+ HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[j]);
+ if(logScale) {
+ dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():(YAXISNUM>0?new Double(Math.log10(new Integer(YAXISNUM).doubleValue())).toString():null)): "null"));
+ } else {
+ dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(YAXISDOUBLENUM).toString():new Integer(YAXISNUM).toString()): "null"));
+ }
+
+
+ // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
+
+ //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + ds.getString(i, columnMap.get((String)uniqueElements[j])) +"}, ");
+ }
+ //}
+ }
+ }
+ for(int kI = 0; kI < uniqueElements.length; kI++) {
+ HashMap dataSeriesStrMap1 = (HashMap) dataSeriesOverAllMap.get(uniqueElements[kI]);
+ for (int kL = 0; kL < uniqueXAxisElements.length; kL++) {
+ if(dataSeriesStrMap1.containsKey(uniqueXAxisElements[kL])) {
+ ((StringBuffer) dataSeries.get(kI)).append ((String)dataSeriesStrMap1.get(uniqueXAxisElements[kL]));
+ } else {
+ ((StringBuffer) dataSeries.get(kI)).append ("{ \"x\":\"" + uniqueXAxisElements[kL] + "\" , \"y\": null }, ");
+ }
+ }
+ }
+
+ } else {
+ HashMap dataSeriesStrMap = new HashMap();
+ HashMap dataSeriesOverAllMap = new HashMap();
+ String valueDataSeries = "";
+ for (int j = 0; j < uniqueElements.length; j++) {
+ dataSeriesStrMap = new HashMap();
+
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ flagNoDate = 0;
+ YAXISNUM = 0;
+ YAXISDOUBLENUM = 0.0;
+ flagNull= 0;
+ //flagSecondNull = 0;
+ dateStr = ds.getString(i, 1);
+ if(timeAxis) {
+ date = getDateFromDateStr(dateStr);
+ formatFlag = getFlagFromDateStr(dateStr);
+ }
+ uniqueElement = (String)uniqueElements[j];
+ if(date==null) {
+ //continue;
+ flagNoDate = 1;
+ int pos = 0;
+ //if(!((String)uniqueElementsList.get(i)).equals(dateStr)) {
+ for (int f=0 ; f< uniqueXAxisElements.length; f++) {
+ if(uniqueXAxisElements[f].equals(dateStr)){
+ pos = f ;
+ break;
+ }
+ }
+ /*for(int f=0; f<uniqueElementsList.size() && f < pos; f++)
+ {
+ StringBuffer strBuf = ((StringBuffer)dataSeries.get(j));
+ if(strBuf.indexOf((String)uniqueElementsList.get(f)) < 0 ) {
+ dataSeriesStrMap.put((String)uniqueElementsList.get(f), value);
+ //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + (String)uniqueElementsList.get(f) + "\" , \"y\": null },");
+ }
+ }*/
+ //}
+
+ if(ds.getString(i, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
+ dateStrList.add("'"+dateStr+"'");
+ try {
+ YAXISNUM = Integer.parseInt(ds.getString(i, 3));
+ if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
+ } catch (NumberFormatException ex) {
+ try {
+ YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, 3));
+ MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
+ if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
+ } catch (NumberFormatException ex1) {
+ flagNull = 1;
+ }
+
+ //flagNull = 1;
+ }
+
+ if(logScale) {
+ if(timeAxis) {
+ //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + dateStr + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ");
+ valueDataSeries = "{ \"x\":" + dateStr + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ";
+ dataSeriesStrMap.put(dateStr, valueDataSeries);
+ } else {
+ // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ");
+ valueDataSeries = "{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ";
+ dataSeriesStrMap.put(dateStr, valueDataSeries);
+ }
+ } else {
+ if(timeAxis) {
+ //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + dateStr + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ");
+ valueDataSeries = "{ \"x\":" + dateStr + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ";
+ dataSeriesStrMap.put(dateStr, valueDataSeries);
+
+ } else {
+ //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ");
+ valueDataSeries = "{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ";
+ dataSeriesStrMap.put(dateStr, valueDataSeries);
+
+ }
+ }
+
+ /*if(ds.getString(i, 2).equals(uniqueElements[j])) {
+ dateStrList.add("'"+dateStr+"'");
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":\"" + ds.getString(i, 3) +"\"}, ");
+ */
+ }
+ dataSeriesOverAllMap.put(uniqueElements[j], dataSeriesStrMap);
+ } else {
+ //date = MMDDYYYYFormat.parse(ds.getString(i, 1), new ParsePosition(0));
+ if(!barRealTimeAxis) { // true - non-time
+ if(!dateStrList.contains(new Long(date.getTime()).toString())) {
+ dateStrList.add(new Long(date.getTime()).toString());
+ for (int k = 0; k < uniqueElements.length; k++) {
+ //((StringBuffer) dataSeries.get(k)).append ("{ \"x\":" + date.getTime() + " , \"y\":null}, ");
+ HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[k]);
+ dataMap.put(date.getTime()+"", "null");
+
+ }
+ }
+ }
+ if(ds.getString(i, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
+ dateStrList.add(new Long(date.getTime()).toString());
+ try {
+ YAXISNUM = Integer.parseInt(ds.getString(i, 3));
+ if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
+ } catch (NumberFormatException ex) {
+ try {
+ YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, 3));
+ MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
+ if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
+ } catch (NumberFormatException ex1) {
+ flagNull = 1;
+ }
+
+ //flagNull = 1;
+ }
+
+ //if(ds.getString(i, 2).equals(uniqueElements[j])) {
+ // dateStrList.add("'"+dateStr+"'");
+ HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[j]);
+ if(logScale) {
+ dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): "null"));
+ } else {
+ if(dataMap.containsKey(new String(""+date.getTime())) && dataMap.get(new String(""+date.getTime())).equals("null")) {
+ dataMap.remove(date.getTime());
+ }
+ dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(YAXISDOUBLENUM).toString():new Integer(YAXISNUM).toString()): "null"));
+ //System.out
+ // .println(dataMap + " " + dataSeriesMap);
+ //}
+ }
+ // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ");
+
+
+ //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + ds.getString(i, 3) +"}, ");
+ } else if (AppUtils.nvl(ds.getString(i, 2)).length()<=0) {
+ dateStrList.add(new Long(date.getTime()).toString());
+ HashMap<String, String> dataMap1 = null;
+ String uniqueElement1 = "";
+ for (int j1 = 0; j1 < uniqueElements.length; j1++) {
+ uniqueElement1 = (String)uniqueElements[j];
+ if(ds.getString(i, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement1.lastIndexOf("|") != -1) ?uniqueElement1.substring(0, uniqueElement1.lastIndexOf("|")):uniqueElement1))) {
+ dataMap1 = dataSeriesMap.get((String) uniqueElements[j1]);
+ if(!dataMap1.containsKey(new String(""+date.getTime())))
+ dataMap1.put(date.getTime()+"", "null");
+ }
+ }
+ }
+ }
+ // dataSeriesOverAllMap.put(uniqueElements[j], dataSeriesMap);
+ }
+
+ }
+ for(int kI = 0; kI < uniqueElements.length; kI++) {
+ HashMap dataSeriesStrMap1 = (HashMap) dataSeriesOverAllMap.get(uniqueElements[kI]);
+ for (int kL = 0; kL < uniqueXAxisElements.length; kL++) {
+ if(dataSeriesStrMap1.containsKey(uniqueXAxisElements[kL])) {
+ ((StringBuffer) dataSeries.get(kI)).append ((String)dataSeriesStrMap1.get(uniqueXAxisElements[kL]));
+ } else {
+ ((StringBuffer) dataSeries.get(kI)).append ("{ \"x\":\"" + uniqueXAxisElements[kL] + "\" , \"y\": null }, ");
+ }
+ }
+ }
+ }
+
+ StringBuffer dateStrBuf = new StringBuffer("");
+ /*if(count == 1) {
+ Long initialDate = Long.parseLong((String)ds.getString(0, 0));
+ Long endDate = Long.parseLong((String) ds.getString(ds.getRowCount(), 0));
+ java.util.Date date1 = null;
+
+ while ( initialDate <= endDate) {
+ //System.out.println("********** " + df.format(initialDate));
+ date1 = new java.util.Date(initialDate.longValue() * 1000);
+ initialDate = initialDate + HOUR;
+
+ dateStrBuf.append(initialDate+",");
+ sortSet.add(""+initialDate);
+ //DateUtils.addHours(date1, 1);
+ }
+ }*/
+
+ if(dateStrList.size()>0) {
+ SortedSet<String> s = Collections.synchronizedSortedSet(dateStrList);
+ Object[] dateElements = (Object[]) s.toArray();
+
+ String element = "";
+ /* if not date value */
+ if(!timeAxis) {
+ for (int i = 0; i < dateElements.length; i++) {
+ dateStrBuf.append(dateElements[i]+",");
+ }
+ } else {
+ if(!barRealTimeAxis || (flagNoDate == 1)) { // non-time
+ for (int i = 0; i < dateElements.length; i++) {
+ dateStrBuf.append(dateElements[i]+",");
+ }
+ } else {
+ Long initialDate = Long.parseLong((String)dateElements[0]);
+ Long endDate = Long.parseLong((String) dateElements[dateElements.length-1]);
+ java.util.Date date1 = null;
+ //first value
+ date1 = new java.util.Date(initialDate.longValue());
+ /* DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss Z");
+ System.out.println(formatter.format(new java.util.Date(initialDate.longValue())));
+ */ //initialDate = initialDate + HOUR;
+
+ dateStrBuf.append(initialDate+",");
+ sortSet.add(""+initialDate);
+
+ // DateUtils.
+
+ while ( initialDate <= endDate) {
+ //System.out.println("********** " + df.format(initialDate));
+ //date1 = new java.util.Date(initialDate.longValue() * 1000);
+ date1 = new java.util.Date(initialDate.longValue());
+ if(formatFlag==HOURFLAG)
+ date1 = DateUtils.addHours(date1, 1);
+ else if(formatFlag==MINFLAG)
+ date1 = DateUtils.addMinutes(date1, 30);
+ else if (formatFlag == DAYFLAG)
+ date1 = DateUtils.addDays(date1, 1);
+ else if (formatFlag == MONTHFLAG)
+ date1 = DateUtils.addMonths(date1, 1);
+ else if (formatFlag == YEARFLAG)
+ date1 = DateUtils.addMonths(date1, 1);
+ initialDate = date1.getTime();
+
+ if(initialDate <= endDate) {
+ dateStrBuf.append(initialDate+",");
+ sortSet.add(""+initialDate);
+ }
+ //DateUtils.addHours(date1, 1);
+ }
+ //DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
+ //df.setTimeZone(TimeZone.getTimeZone("UTC"));
+ //java.util.Date date1 = new java.util.Date(initialDate.longValue() * 1000);
+ //java.util.Date d = df.
+ //for ()
+ }
+ }
+ dateStrBuf.deleteCharAt(dateStrBuf.length()-1);
+ }
+
+ if(timeAxis) {
+ //if(!barRealTimeAxis) { // false - non-time
+ Object[] dateAllElements = (Object[]) sortSet.toArray();
+
+ for (int i = 0; i < uniqueElements.length; i++) {
+ HashMap<String, String> dataMap = dataSeriesMap.get((String)uniqueElements[i]);
+ for (int j=0; j<dateAllElements.length;j++) {
+ //if(strBuf.toString().indexOf((String) dateAllElements[j]) == -1) {
+ if(!dataMap.containsKey((String) dateAllElements[j])) {
+ dataMap.put((String) dateAllElements[j], "null");
+ //((StringBuffer) dataSeries.get(i)).append ("{ \"x\":" + dateAllElements[j] + " , \"y\":null}, ");
+ }
+ }
+ }
+ //}
+ }
+ String valueStr = "";
+ for (int i = 0; i < uniqueElements.length; i++) {
+ HashMap<String, String> dataMap = dataSeriesMap.get((String)uniqueElements[i]);
+ Set<String> keySet = dataMap.keySet();
+ ArrayList<String> keySortedList = new ArrayList<String>(new TreeSet<String>(keySet));
+
+ for (int k=0; k < keySortedList.size(); k++) {
+ valueStr = dataSeriesMap.get((String)uniqueElements[i]).get(keySortedList.get(k));
+ if(valueStr.equals("null"))
+ valueStr = null;
+ else {
+ //if(logScale)
+ //valueStr = new Double(Math.log10(new Double(valueStr).doubleValue())).toString();
+ }
+ ((StringBuffer) dataSeries.get(i)).append ("{ \"x\":" + keySortedList.get(k) + " , \"y\":" + valueStr +"}, ");
+ // ((StringBuffer) dataSeries.get(i)).append ("{ \"x\":" + keySortedList.get(k) + " , \"y\":" + valueStr +"}, ");
+ }
+
+ // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ");
+ }
+
+ for (int i = 0; i < uniqueElements.length; i++) {
+ StringBuffer strBuf = ((StringBuffer) dataSeries.get(i));
+ ((StringBuffer) dataSeries.get(i)).deleteCharAt(((StringBuffer) dataSeries.get(i)).lastIndexOf(","));
+ if(i < (uniqueElements.length -1) ) {
+ ((StringBuffer) dataSeries.get(i)).append("] } , \n");
+ }
+ else {
+ ((StringBuffer) dataSeries.get(i)).append("] } \n");
+ }
+ }
+ if(ds.getRowCount() > 0) {
+ for (int i = 0; i < uniqueElements.length; i++) {
+ wholeScript.append((StringBuffer)dataSeries.get(i));
+ }
+ }
+
+
+ wholeScript.append("]; \n");
+
+ //add global variable
+ wholeScript.append("var chart; \n");
+ //javascript to create Bar Chart
+ wholeScript.append("nv.addGraph(function() { \n");
+ if(horizontalBar /*&& flagNoDate == 1*/)
+ wholeScript.append(" chart = nv.models.multiBarHorizontalChart() \n");
+ else /*if (flagNoDate == 1)*/
+ wholeScript.append(" chart = nv.models.multiBarChart() \n");
+ /*else
+ wholeScript.append(" var chart = nv.models.multiBarTimeSeriesChart() \n");*/
+
+ wholeScript.append(" .margin({top: "+ topMargin +", right: "+ rightMargin +", bottom: "+ bottomMargin +", left: " + leftMargin +"}) \n");
+ if(showLegend) {
+ wholeScript.append(" .showLegend(true) \n ");
+ } else {
+ wholeScript.append(" .showLegend(false) \n ");
+ }
+ if(!horizontalBar && barReduceXAxisLabels)
+ wholeScript.append(" .reduceXTicks(true) \n ");
+ else if (!horizontalBar) {
+ wholeScript.append(" .reduceXTicks(false) \n ");
+ //wholeScript.append(" chart.lines1.forceY(["+(nvl(reportRuntime.getRangeAxisLowerLimit()).length()<=0?"0":reportRuntime.getRangeAxisLowerLimit()) +", "+ (nvl(reportRuntime.getRangeAxisUpperLimit()).length()<=0?UPPER_RANGE:reportRuntime.getRangeAxisUpperLimit()) + "]); \n" +
+ double UPPER_RANGE = 0;
+ if(Math.ceil((MAXDOUBLENUM+(MAXDOUBLENUM*25/100))/100) * 100 >= 1) {
+ UPPER_RANGE = Math.ceil(MAXDOUBLENUM+(MAXDOUBLENUM*25/100));
+ } else UPPER_RANGE = 1;
+ wholeScript.append(" .forceY(["+(nvl(reportRuntime.getRangeAxisLowerLimit()).length()<=0?"0":reportRuntime.getRangeAxisLowerLimit()) +", "+ (nvl(reportRuntime.getRangeAxisUpperLimit()).length()<=0?UPPER_RANGE:reportRuntime.getRangeAxisUpperLimit()) + "])\n");
+ }
+ if(!animation) {
+ wholeScript.append(" .delay(0) \n ");
+ }
+ if(showControls) {
+ wholeScript.append(" .showControls(true) \n ");
+ } else if (!showControls){
+ wholeScript.append(" .showControls(false) \n ");
+ }
+ if(stacked && !logScale)
+ wholeScript.append(" .stacked(true)\n ");
+ else if(!stacked || logScale)
+ wholeScript.append(" .stacked(false)\n ");
+ if(logScale) {
+ wholeScript.append(" .logScale(true)\n ");
+ } else {
+ wholeScript.append(" .logScale(false)\n ");
+ }
+
+ if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
+ wholeScript.append(" .legendPos('right')\n" );
+ } else {
+ wholeScript.append(" .legendPos('top')\n" );
+ }
+ if(uniqueElements.length <= 10) {
+ wholeScript.append(" .color(d3.scale.category10().range()); \n" +
+ " chart.xAxis\n");
+ } else if (uniqueElements.length <= 20) {
+ wholeScript.append(" .color(d3.scale.category50().range()); \n" +
+ " chart.xAxis\n");
+ } else {
+ wholeScript.append(" .color(d3.scale.category50().range()); \n" +
+ " chart.xAxis\n");
+
+ }
+
+ if(flagNoDate == 0)
+ wholeScript.append(" .tickValues(["+ dateStrBuf.toString() + "])\n ");
+ else {
+ wholeScript.append(" .tickValues(["+ dateStrBuf.toString() + "])\n ");
+ }
+ if(staggerLabels) {
+ wholeScript.append(" .staggerLabels(true) \n");
+ } else {
+ wholeScript.append(" .staggerLabels(false) \n");
+ }
+ if(!horizontalBar) {
+ if(showMaxMin) {
+ wholeScript.append(" .showMaxMin(true) \n ");
+ } else {
+ wholeScript.append(" .showMaxMin(false) \n ");
+ }
+ }
+ if(nvl(rotateLabels).length()>0) {
+ wholeScript.append(" .rotateLabels("+ rotateLabels+ ") \n ");
+ } else {
+ wholeScript.append(" .rotateLabels(\"0\") \n ");
+ }
+ wholeScript.append(" .axisLabel('" + legendColumnName + "')");
+ if(flagNoDate == 1 || !timeAxis) {
+ wholeScript.append(";\n");
+ } else {
+ wholeScript.append("\n .tickFormat(function(d) { \n");
+ if(timeAxis) {
+ if(formatFlag==HOURFLAG)
+ wholeScript.append(" return d3.time.format('%x %H')(new Date(d)) }); \n");
+ else if(formatFlag==MINFLAG)
+ wholeScript.append(" return d3.time.format('%x %H:%M')(new Date(d)) }); \n");
+ else if(formatFlag==SECFLAG)
+ wholeScript.append(" return d3.time.format('%X')(new Date(d)) }); \n");
+ else if(formatFlag==MONTHFLAG)
+ wholeScript.append(" return d3.time.format('%b %y')(new Date(d)) }); \n");
+ else
+ wholeScript.append(" return d3.time.format('%x')(new Date(d)) }); \n");
+
+ } else {
+ wholeScript.append(" return d; }); \n");
+ }
+ }
+
+ if(nvl(chartRightAxisLabel).length() > 0) {
+ //if(flagNoDate == 1)
+ wholeScript.append(" chart.yAxis\n");
+ //else
+ // wholeScript.append(" chart.yAxis1\n");
+ if(logScale) {
+ wholeScript.append(" .logScale(true)\n ");
+ } else {
+ wholeScript.append(" .logScale(false)\n ");
+ }
+
+ wholeScript.append(" .axisLabel('" + chartLeftAxisLabel + "') \n" +
+ " .tickFormat(d3.format(',.0f')); \n");
+ /*" chart.yAxis2\n " +
+ " .axisLabel('" + chartRightAxisLabel + "') \n" +
+ " .tickFormat(d3.format(',.0f')); \n");*/
+
+
+ } else {
+ //if(flagNoDate == 1)
+ wholeScript.append(" chart.yAxis\n");
+ //else
+ // wholeScript.append(" chart.yAxis1\n");
+ if(logScale) {
+ wholeScript.append(" .logScale(true)\n ");
+ } else {
+ wholeScript.append(" .logScale(false)\n ");
+ }
+ wholeScript.append(" .axisLabel('" + chartLeftAxisLabel + "') \n");
+
+ if(MAXDOUBLENUM <=5 && MAXNUMDECIMALPLACES == 0 ) MAXNUMDECIMALPLACES = 2;
+ if( MAXNUMDECIMALPLACES >=3 ) MAXNUMDECIMALPLACES = 2;
+ if(!logScale)
+ wholeScript.append(" .tickFormat(d3.format(',."+MAXNUMDECIMALPLACES+"f')); \n");
+ else
+ wholeScript.append(" .tickFormat(d3.format(',." + precision + "f')); \n");
+ //" .tickFormat(d3.format(',.0f')); \n");
+ }
+ wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n" +
+ " .datum(historicalBarChart) \n" );
+ if(animation)
+ wholeScript.append(" .transition().duration(1000) \n" );
+ else
+ wholeScript.append(" .transition().duration(0) \n" );
+ wholeScript.append(" .call(chart); \n" +
+ "nv.utils.windowResize(chart.update); \n" +
+ "return chart; \n" +
+ "}); \n");
+ wholeScript.append("function redraw() { \n");
+ //wholeScript.append(" nv.utils.windowResize(chart.update); \n");
+ wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n") ;
+ wholeScript.append(" .datum(historicalBarChart) \n");
+ wholeScript.append(" .transition().duration(500) \n");
+ wholeScript.append(" .call(chart); \n");
+ wholeScript.append("} \n");
+ wholeScript.append("\n");
+ wholeScript.append(" setInterval(function () { \n");
+ wholeScript.append(" redraw(); \n");
+ wholeScript.append(" }, 1500) \n");
+
+ wholeScript.append("if(historicalBarChart.length <= 0 ) {\n");
+ wholeScript.append(" document.getElementById(\"chart"+reportRuntime.getReportID()+"\").innerHTML = \"<div id='noData'><b>No Data Available</b></div>\";\n");
+ wholeScript.append(" document.getElementById(\"chart"+reportRuntime.getReportID()+"\").className=\"nodatadiv\";\n");
+ wholeScript.append(" document.getElementById(\"nodata\").className=\"nodatainner\";\n");
+ wholeScript.append("}\n");
+ wholeScript.append("</script> </body></html> \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<String>();
+ HashMap<String, String> 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<String> 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<String> colorList = new TreeSet<String>();
+ 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<String> 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("<!DOCTYPE html>\n");
+ wholeScript.append("<html>\n");
+ wholeScript.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF8\">\n");
+ wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n");
+ wholeScript.append("<link href=\""+ chartScriptsPath +"d3/css/nv.d3.css\" rel=\"stylesheet\" type=\"text/css\">\n");
+ wholeScript.append("<style>\n " +
+ " body { \n" +
+ " overflow-y:scroll; \n" +
+ " } \n" +
+ " text { \n" +
+ " font: 12px sans-serif; \n" +
+ " } \n" +
+ " svg { \n" +
+ " display: block;\n" +
+ " } \n" +
+ " #chart"+reportRuntime.getReportID()+" svg { \n" +
+ " height: "+ (nvl(height).length()>0?(height.endsWith("px")?height:height+"px"):"420px") + "; \n" +
+ " width: "+ (nvl(width).length()>0?(width.endsWith("px")?width:width+"px"):"700px") + "; \n" +
+ " min-width: 100px; \n" +
+ " min-height: 100px; \n" +
+ " } \n" +
+ " tr.z-row-over > td.z-row-inner, tr.z-row-over > .z-cell {" +
+ " background-color: rgb(255, 255, 255); "+
+ "}\n");
+ wholeScript.append(".nodatadiv {\n");
+ wholeScript.append(" display: table-cell;\n");
+ wholeScript.append(" width: 700px;\n");
+ wholeScript.append(" height:370px;\n");
+ wholeScript.append(" text-align:center;\n");
+ wholeScript.append(" vertical-align: middle;\n");
+ wholeScript.append("}\n");
+ wholeScript.append(".nodatainner {\n");
+ wholeScript.append(" padding: 10px;\n");
+ wholeScript.append("}\n");
+
+ wholeScript.append(" </style> \n" );
+
+ wholeScript.append("<body> \n");
+
+ if(showTitle)
+ wholeScript.append("<div align=\"center\"><H3>" + title +"</H3></div>");
+
+
+ wholeScript.append("<div id=\"chart"+reportRuntime.getReportID()+"\"> <svg></svg> </div> \n");
+ //js files
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/d3.v3.min.js\"></script>\n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/nv.d3.min.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/axis.min.js\"></script> \n");
+ //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/cumulativeLineChart.js\"></script> \n");
+ //if(multipleSeries)
+ //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/multiChart.js\"></script> \n");
+
+ //json
+ wholeScript.append("<script> \n");
+
+ wholeScript.append("historicalBarChart = [ \n");
+ //wholeScript.append("{ \n");
+ ArrayList dataSeries = new ArrayList();
+ String uniqueElement = "";
+
+ String [] uniqueRevElements = null;
+ //Added to make sure order appears same as legend
+ /*if(nvl(subType).length() > 0 && subType.equals("area")) {
+ uniqueRevElements = reverse((String[])uniqueElements);
+ } else {*/
+ uniqueRevElements = (String[])uniqueElements;
+ //}
+
+ int RIGHTAXISSERIES = 0;
+ for (int i = 0; i < uniqueRevElements.length; i++) {
+ //element.substring(element.indexOf("|")+1)
+ uniqueElement = (String)uniqueRevElements[i];
+ if(multipleSeries && (nvl(chartRightAxisLabel).length() > 0)) {
+ if(nvl(subType).length() > 0 && subType.equals("area")) {
+ if(nvl(uniqueElement).indexOf("|R") !=-1)
+ dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(2)+"\", "+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1) ?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+" \"values\": ["));
+ else
+ dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(1)+"\", "+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1) ?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+" \"values\": ["));
+ } else {
+ if(nvl(uniqueElement).indexOf("|R") !=-1)
+ dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(2)+"\","+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1) ?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+" \"values\": ["));
+ else
+ dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(1)+"\","+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1) ?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+" \"values\": ["));
+ }
+ RIGHTAXISSERIES = dataSeries.size()-1;
+ //dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((DataColumnType)columnMap.get(i)).getDisplayName() +"\", \"yAxis\": \""+(i+1)+"\", \"values\": ["));
+ }
+ else {
+ dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|")!= -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(1)+"\","+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1)?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+"\"values\": ["));
+ }
+
+ }
+ /*StringBuffer dataSeries1 = new StringBuffer("");
+ dataSeries1.append(" { key: \"Series1\",values: [");
+ StringBuffer dataSeries2 = new StringBuffer("");
+ dataSeries2.append(" { key: \"Series2\", values: [");
+ StringBuffer dataSeries3 = new StringBuffer("");
+ dataSeries3.append(" { key: \"Series3\", values: [");
+ */
+
+
+ //long minTime = 1000000000000000L;
+ int MAXNUM = 0;
+ double MAXDOUBLENUM = 0.0;
+ int YAXISNUM = 0;
+ double YAXISDOUBLENUM = 0.0;
+ int MAXNUMDECIMALPLACES = 0;
+ int flagNull = 0;
+ int flagSecondNull = 0;
+ TreeSet dateList = new TreeSet();
+ int formatFlag = 0;
+ if(flag!= 1) {
+ for (int j = 0; j < uniqueRevElements.length; j++) {
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ flagNull = 0;
+ flagSecondNull=0;
+ YAXISNUM = 0;
+ YAXISDOUBLENUM = 0.0;
+ dateStr = "";
+ date = null;
+ dateStr = ds.getString(i, 1);
+ if(timeAxis) {
+ date = getDateFromDateStr(dateStr);
+ formatFlag = getFlagFromDateStr(dateStr);
+ }
+ if(date==null && timeAxis) continue;
+
+
+ //if(ds.getString(i, 2).equals(uniqueElements[j])) {
+ //if(minTime > date.getTime())
+ // minTime = date.getTime();
+ uniqueElement = (String)uniqueRevElements[j];
+ try {
+ YAXISNUM = Integer.parseInt(ds.getString(i, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
+ if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
+ } catch (NumberFormatException ex) {
+ try {
+ YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
+ if(RIGHTAXISSERIES!=j) {
+ MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
+ if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
+ }
+ } catch (NumberFormatException ex1) {
+ flagNull = 1;
+ }
+ }
+
+ if(date==null) {
+ dateList.add(dateStr);
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
+ } else {
+ dateList.add(new Long(date.getTime()).toString());
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
+ }
+
+
+
+ if(nvl(subType).length() > 0 && subType.equals("area")) {
+
+ if(flagNull!=1) {
+ if(i<ds.getRowCount()-1) {
+ try {
+ YAXISNUM = Integer.parseInt(ds.getString(i+1, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
+ if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
+ } catch (NumberFormatException ex) {
+ try {
+ YAXISDOUBLENUM = Double.parseDouble(ds.getString(i+1, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
+ if(RIGHTAXISSERIES!=j) {
+ MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
+ if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
+ }
+ } catch (NumberFormatException ex1) {
+ flagSecondNull = 1;
+ }
+ }
+
+ if(flagSecondNull==1 && date == null) {
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + null +"}, ");
+ } else if( flagSecondNull == 1){
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + null +"}, ");
+ }
+ }
+ } else {
+ if(i<ds.getRowCount()-1) {
+ dateStr = ds.getString(i+1, 1);
+
+ if(!timeAxis) {
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + null +"}, ");
+ } else {
+ date = getDateFromDateStr(dateStr);
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + null +"}, ");
+ }
+ //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + null +"}, ");
+ }
+ }
+
+ }
+
+
+ //}
+ }
+ //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + minTime + " , \"y\":" + 0 +"}, ");
+ }
+
+ } else {
+ for (int j = 0; j < uniqueRevElements.length; j++) {
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ YAXISNUM = 0;
+ YAXISDOUBLENUM = 0.0;
+ flagNull= 0;
+ flagSecondNull = 0;
+ dateStr = ds.getString(i, 1);
+ if(timeAxis) {
+ date = getDateFromDateStr(dateStr);
+ formatFlag = getFlagFromDateStr(dateStr);
+ }
+
+ if(date==null && timeAxis) continue;
+
+ uniqueElement = (String)uniqueRevElements[j];
+ //date = MMDDYYYYFormat.parse(ds.getString(i, 1), new ParsePosition(0));
+ if(ds.getString(i, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
+ //if(minTime > date.getTime())
+ // minTime = date.getTime();
+ try {
+ YAXISNUM = Integer.parseInt(ds.getString(i, 3));
+ if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
+ } catch (NumberFormatException ex) {
+ try {
+ YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, 3));
+ if(RIGHTAXISSERIES!=j) {
+ MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
+ if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
+
+ }
+ } catch (NumberFormatException ex1) {
+ flagNull = 1;
+ }
+ }
+
+ if(date==null) {
+ dateList.add(dateStr);
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + dateStr + " , \"y\":" + (flagNull==0?(YAXISDOUBLENUM!=0.0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
+ } else {
+ dateList.add(new Long(date.getTime()).toString());
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + (flagNull==0?(YAXISDOUBLENUM!=0.0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
+ }
+
+
+ if(nvl(subType).length() > 0 && subType.equals("area")) {
+
+ if(flagNull!=1) {
+ if(i<ds.getRowCount()-1) {
+ for (int k = i+1; k < ds.getRowCount(); k++) {
+ if (ds.getString(k, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
+ try {
+ YAXISNUM = Integer.parseInt(ds.getString(k, 3));
+ if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
+ } catch (NumberFormatException ex) {
+ try {
+ YAXISDOUBLENUM = Double.parseDouble(ds.getString(k, 3));
+ if(RIGHTAXISSERIES!=j) {
+ MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
+ if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
+ }
+ } catch (NumberFormatException ex1) {
+ flagSecondNull = 1;
+ }
+ }
+ break;
+ }
+ }
+
+ if(date==null && flagSecondNull==1){
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + dateStr + " , \"y\":" + null +"}, ");
+ } else if(flagSecondNull == 1){
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + null +"}, ");
+ }
+ //}
+ }
+ } else {
+ if(i<ds.getRowCount()-1) {
+ for (int k = i+1; k < ds.getRowCount(); k++) {
+ if (ds.getString(k, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
+ dateStr = ds.getString(k, 1);
+ if(!timeAxis) {
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + null +"}, ");
+ break;
+ } else {
+ date = getDateFromDateStr(dateStr);
+ ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + null +"}, ");
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ }
+ }
+ // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + minTime + " , \"y\":" + 0 +"}, ");
+
+ }
+/* if(ds.getString(i, 2).equals("Series1")) {
+ dataSeries1.append("[ " + date.getTime() + " , " + ds.getString(i, 3) +"], ");
+ } else if (ds.getString(i, 2).equals("Series2")) {
+ dataSeries2.append("[ " + date.getTime() + " , " + ds.getString(i, 3) +"], ");
+ } else if (ds.getString(i, 2).equals("Series3")) {
+ dataSeries3.append("[ " + date.getTime() + " , " + ds.getString(i, 3) +"], ");
+ }
+*/ }
+
+ for (int i = 0; i < uniqueRevElements.length; i++) {
+ StringBuffer strBuf = ((StringBuffer) dataSeries.get(i));
+ ((StringBuffer) dataSeries.get(i)).deleteCharAt(((StringBuffer) dataSeries.get(i)).lastIndexOf(","));
+ if(i < (uniqueRevElements.length -1) ) {
+ ((StringBuffer) dataSeries.get(i)).append("] } , \n");
+ }
+ else {
+ ((StringBuffer) dataSeries.get(i)).append("] } \n");
+ }
+ }
+
+ for (int i = 0; i < uniqueRevElements.length; i++) {
+ wholeScript.append((StringBuffer)dataSeries.get(i));
+ }
+/* wholeScript.append(dataSeries1);
+ wholeScript.append(dataSeries2);
+ wholeScript.append(dataSeries3);
+*/ wholeScript.append("];\n");
+
+ /* Sorting is commented out.*/
+ StringBuffer dateStrBuf = new StringBuffer("");
+ if(dateList.size()>0) {
+ //SortedSet<String> s = Collections.synchronizedSortedSet(dateList);
+ Object[] dateElements = (Object[]) dateList.toArray();
+
+ String element = "";
+
+ for (int i = 0; i < dateElements.length; i++) {
+ dateStrBuf.append(dateElements[i]+",");
+ }
+ dateStrBuf.deleteCharAt(dateStrBuf.length()-1);
+ }
+
+ wholeScript.append(" var chart;\n");
+ wholeScript.append("nv.addGraph(function() { \n");
+ //" var chart = nv.models.cumulativeLineChart() \n" + nv.models.lineWithFocusChart()
+// " chart = nv.models.lineChart() \n" +
+ if(nvl(subType).length() > 0 && subType.equals("area")) {
+ wholeScript.append(" chart = nv.models.stackedAreaChart() \n");
+ if(showControls) {
+ wholeScript.append(" .showControls(true) \n ");
+ } else {
+ wholeScript.append(" .showControls(false) \n ");
+ }
+ } else {
+ wholeScript.append(" chart = nv.models.multiChart() \n");
+ if(nvl(chartRightAxisLabel).length() > 0) {
+ wholeScript.append(" .dualaxis(true) \n ");
+ } else {
+ wholeScript.append(" .dualaxis(false) \n ");
+ }
+
+ if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
+ wholeScript.append(" .legendPos('right')\n" );
+ } else {
+ wholeScript.append(" .legendPos('top')\n" );
+ }
+
+
+ }
+
+ wholeScript.append(" .margin({top: "+ topMargin +", right: "+ rightMargin +", bottom: "+ bottomMargin +", left: " + leftMargin +"}) \n");
+ if(showLegend) {
+ wholeScript.append(" .showLegend(true) \n ");
+ } else {
+ wholeScript.append(" .showLegend(false) \n ");
+ }
+
+ if(nvl(subType).length() > 0 && subType.equals("area")) {
+ if( MAXNUMDECIMALPLACES >=3 ) {
+ wholeScript.append(" .yAxisTooltipFormat(d3.format(',.3f')) \n");
+ } else {
+ wholeScript.append(" .yAxisTooltipFormat(d3.format(',."+MAXNUMDECIMALPLACES+ "f')) \n");
+ }
+
+ wholeScript.append(".x (function(d) {return d.x;}) \n" +
+ ".y (function(d) {return d.y;}) \n");
+ }
+
+ //" .x(function(d) { return d[0] }) \n" +
+ //" .y(function(d) { return d[1] }) \n" +
+ //" .forceY("+(nvl(reportRuntime.getRangeAxisLowerLimit()).length()<=0?"0":reportRuntime.getRangeAxisLowerLimit()) +", "+ Math.ceil((MAXNUM+(MAXNUM*25/100))/100) * 100 + ") \n" + // reportRuntime.getRangeAxisUpperLimit()+") \n" +
+ wholeScript.append(" .color(d3.scale.category10().range()); \n");
+ if(!(nvl(subType).length() > 0 && subType.equals("area"))) {
+ double UPPER_RANGE = 0;
+ if(Math.ceil((MAXDOUBLENUM+(MAXDOUBLENUM*25/100))/100) * 100 >= 1) {
+ UPPER_RANGE = Math.ceil(MAXDOUBLENUM+(MAXDOUBLENUM*25/100));
+ } else UPPER_RANGE = 1;
+
+ wholeScript.append(" chart.lines1.forceY(["+(nvl(reportRuntime.getRangeAxisLowerLimit()).length()<=0?"0":reportRuntime.getRangeAxisLowerLimit()) +", "+ (nvl(reportRuntime.getRangeAxisUpperLimit()).length()<=0?UPPER_RANGE:reportRuntime.getRangeAxisUpperLimit()) + "]); \n" +
+ " chart.lines2.forceY([0,1]); \n");
+ }
+ wholeScript.append(" chart.xAxis\n");
+ if(reportRuntime.isShowXaxisLabel()) {
+ // X axis label is commented for time-being. This should be derived from request parameter.
+ //" .axisLabel('" + legendColumnName + "') \n" +
+ wholeScript.append(" .axisLabel('" + legendColumnName + "') \n");
+ } else {
+ wholeScript.append(" .axisLabel('') \n");
+ }
+ if(reportRuntime.isAddXAxisTickers()) {
+ wholeScript.append(" .tickValues(["+ dateStrBuf.toString()+ "])\n ");
+ } else {
+ //wholeScript.append(" .tickValues([])\n ");
+ }
+ if(staggerLabels) {
+ wholeScript.append(" .staggerLabels(true) \n");
+ } else {
+ wholeScript.append(" .staggerLabels(false) \n");
+ }
+ if(showMaxMin) {
+ wholeScript.append(" .showMaxMin(true) \n ");
+ } else {
+ wholeScript.append(" .showMaxMin(false) \n ");
+ }
+
+ if(nvl(rotateLabels).length()>0) {
+ wholeScript.append(" .rotateLabels("+ rotateLabels+ ") \n ");
+ } else {
+ wholeScript.append(" .rotateLabels(\"0\") \n ");
+ }
+
+ wholeScript.append(" .tickFormat(function(d) { \n");
+ if(formatFlag==DAYFLAG)
+ wholeScript.append(" return d3.time.format('%m/%d/%Y')(new Date(d)) }); \n");
+ else if(formatFlag==HOURFLAG)
+ wholeScript.append(" return d3.time.format('%x %H')(new Date(d)) }); \n");
+ else if(formatFlag==MINFLAG)
+ wholeScript.append(" return d3.time.format('%x %H:%M')(new Date(d)) }); \n");
+ else if(formatFlag==SECFLAG)
+ wholeScript.append(" return d3.time.format('%x %X')(new Date(d)) }); \n");
+ else if(formatFlag==MONTHFLAG)
+ wholeScript.append(" return d3.time.format('%b %y')(new Date(d)) }); \n");
+
+ else if(timeAxis)
+ wholeScript.append(" return d3.time.format('%x')(new Date(d)) }); \n");
+ else
+ wholeScript.append(" return d; }); \n");
+ if(nvl(chartRightAxisLabel).length() > 0) {
+ if(nvl(subType).length() > 0 && subType.equals("area")) {
+ wholeScript.append(" chart.yAxis\n");
+ } else {
+ wholeScript.append(" chart.yAxis1\n");
+ }
+ wholeScript.append(" .axisLabel('" + chartLeftAxisLabel + "') \n");
+ //if(nvl(subType).length() > 0 && subType.equals("area")) {
+ if(MAXDOUBLENUM <=5 && MAXNUMDECIMALPLACES == 0 ) MAXNUMDECIMALPLACES = 2;
+ if( MAXNUMDECIMALPLACES >=3 ) MAXNUMDECIMALPLACES = 2;
+ wholeScript.append(" .tickFormat(d3.format(',."+MAXNUMDECIMALPLACES+"f')); \n");
+ /*} else {
+ wholeScript.append(" .tickFormat(d3.format(',.2f')); \n");
+ }*/
+ // " .tickFormat(function (d) {return d;} ); \n");
+ //" .tickFormat(function(d) {if (d >= 1000) return Math.round(d/1000)+\"K\"; else return d;}); \n");
+ if(!(nvl(subType).length() > 0 && subType.equals("area"))) {
+ wholeScript.append(" chart.yAxis2\n " +
+ " .axisLabel('" + chartRightAxisLabel + "') \n" +
+ " .tickFormat(d3.format(',.02f')); \n");
+ //" .tickFormat(function(d) {if (d >= 1000) return Math.round(d/1000)+\"K\"; else return d;}); \n");
+ //" .tickFormat(function(d) {if( d <= 1) return Math.round(d*100)+\"%\"; else return d;}); \n");
+ // " .tickFormat(function(d) { return d;}); \n");
+ }
+
+
+ } else {
+ if(nvl(subType).length() > 0 && subType.equals("area")) {
+ wholeScript.append(" chart.yAxis\n");
+ } else {
+ wholeScript.append(" chart.yAxis1\n");
+ }
+ wholeScript.append(" .axisLabel('" + chartLeftAxisLabel + "') \n");
+ //if(nvl(subType).length() > 0 && subType.equals("area")) {
+ if(MAXDOUBLENUM <=5 && MAXNUMDECIMALPLACES == 0 ) MAXNUMDECIMALPLACES = 2;
+ if( MAXNUMDECIMALPLACES >=3 ) {
+ MAXNUMDECIMALPLACES = 2;
+ }
+ wholeScript.append(" .tickFormat(d3.format(',."+MAXNUMDECIMALPLACES+"f')); \n");
+ /*} else {
+ wholeScript.append(" .tickFormat(d3.format(',.2f')); \n");
+ }*/
+ //" .tickFormat(function(d) {if (d >= 1000) return Math.round(d/1000)+\"K\"; else return d;}); \n");
+ }
+ wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n" +
+ " .datum(historicalBarChart) \n" );
+ if(animation)
+ wholeScript.append(" .transition().duration(1000) \n" );
+ wholeScript.append(" .call(chart); \n" +
+ "nv.utils.windowResize(chart.update); \n" +
+ "return chart; \n" +
+ "}); \n");
+
+ wholeScript.append("function redraw() { \n");
+ //wholeScript.append(" nv.utils.windowResize(chart.update); \n");
+ wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n") ;
+ wholeScript.append(" .datum(historicalBarChart) \n");
+ wholeScript.append(" .transition().duration(500) \n");
+ wholeScript.append(" .call(chart); \n");
+ wholeScript.append("} \n");
+ wholeScript.append("\n");
+ wholeScript.append(" setInterval(function () { \n");
+ wholeScript.append(" redraw(); \n");
+ wholeScript.append(" }, 1500) \n");
+
+ wholeScript.append("if(historicalBarChart.length <= 0 ) {\n");
+ wholeScript.append(" document.getElementById(\"chart"+reportRuntime.getReportID()+"\").innerHTML = \"<div id='noData'><b>No Data Available</b></div>\";\n");
+ wholeScript.append(" document.getElementById(\"chart"+reportRuntime.getReportID()+"\").className=\"nodatadiv\";\n");
+ wholeScript.append(" document.getElementById(\"nodata\").className=\"nodatainner\";\n");
+ wholeScript.append("}\n");
+
+ wholeScript.append("</script> </body> </html> \n");
+
+ } else if (chartType.equals(AppConstants.GT_PIE) || chartType.equals(AppConstants.GT_PIE_3D)) {
+ wholeScript.append("<!DOCTYPE html>\n");
+ wholeScript.append("<html>\n");
+ wholeScript.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF8\">\n");
+ wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n");
+ wholeScript.append("<link href=\""+ AppUtils.getBaseFolderURL() +"d3/css/nv.d3.css\" rel=\"stylesheet\" type=\"text/css\">\n");
+ wholeScript.append("<style>\n " +
+ " body { \n" +
+ " overflow-y:scroll; \n" +
+ " } \n" +
+ " text { \n" +
+ " font: 12px sans-serif; \n" +
+ " } \n" +
+ " tr.z-row-over > td.z-row-inner, tr.z-row-over > .z-cell {" +
+ " background-color: rgb(255, 255, 255); "+
+ "} "+
+ " svg { display: block; } " +
+ " #chart"+reportRuntime.getReportID()+" svg { \n" +
+ " height: "+ (nvl(height).length()>0?(height.endsWith("px")?height:height+"px"):"420px") + "; \n" +
+ " width: "+ (nvl(width).length()>0?(width.endsWith("px")?width:width+"px"):"700px") + "; \n" +
+ " min-width: 100px; \n" +
+ " min-height: 100px; \n" +
+ " } \n" +
+ " </style> \n" );
+ wholeScript.append("<body> \n");
+
+ if(showTitle)
+ wholeScript.append("<div align=\"center\"><H3>" + title +"</H3></div>");
+
+ wholeScript.append("<div id=\"chart"+reportRuntime.getReportID()+"\"><svg></svg></div>");
+ //"<svg id=\"test2\"></svg>\n");
+ //js files
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/d3.v3.min.js\"></script>\n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/nv.d3.min.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/legend.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/pie.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/pieChart.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/utils.js\"></script> \n");
+ wholeScript.append("<script> \n");
+
+ wholeScript.append("historicalBarChart = [ \n");
+ double TOTAL = 0;
+ double VALUE = 0;
+ int flagNull = 0;
+ String KEY = "";
+ String COLOR = "";
+ TreeSet<String> colorList = new TreeSet<String>();
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ VALUE = 0;
+ try {
+ VALUE = Double.parseDouble(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<String> 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.lastIndexOf("|")+1)+"',");
+ }
+ color.deleteCharAt(color.length()-1);
+ }
+
+ wholeScript.append("];\n");
+
+
+ wholeScript.append("var chart; \n");
+ wholeScript.append("nv.addGraph(function() { \n" +
+ " var width1= 700, height1=720; \n" +
+ " chart = nv.models.pieChart() \n" +
+ " .margin({top: "+ topMargin +", right: "+ rightMargin +", bottom: "+ bottomMargin +", left: " + leftMargin +"}) \n" +
+
+ //" .x(function(d) { return d.key +\" \"+ Math.round(d.y/"+TOTAL+" *100) + \"%\" }) \n" +
+ " .x(function(d) { return d.key }) \n" +
+ " .y(function(d) { return d.y }) \n");
+ if(colorList.size()>0) {
+ wholeScript.append(" .color(["+ color.toString() + "] ) \n");
+ }
+ //wholeScript.append(" .values(function(d) { return d }) \n");
+ //" .color(d3.scale.category10().range()); \n" +
+ if(showLegend) {
+ wholeScript.append(" chart.showLegend(true);\n ");
+ } else {
+ wholeScript.append(" chart.showLegend(false);\n ");
+ }
+
+ //wholeScript.append("chart.showLegend(false);\n" +
+ //" .width(width1) \n" +
+ //" .height(height1); \n" +
+ wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n" +
+ " .datum(historicalBarChart) \n");
+ if(animation)
+ wholeScript.append(" .transition().duration(1200) \n" );
+/* " .attr(\"width\", width1) \n" +
+ " .attr(\"height\", height1) \n" +
+*/ wholeScript.append(" .call(chart); \n" +
+ " nv.utils.windowResize(chart.update);\n"+
+ "return chart; \n" +
+ "}); \n");
+
+ wholeScript.append("function redraw() { \n");
+ //wholeScript.append(" nv.utils.windowResize(chart.update); \n");
+ wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n") ;
+ wholeScript.append(" .datum(historicalBarChart) \n");
+ wholeScript.append(" .transition().duration(500) \n");
+ wholeScript.append(" .call(chart); \n");
+ wholeScript.append("} \n");
+ wholeScript.append("\n");
+ wholeScript.append(" setInterval(function () { \n");
+ wholeScript.append(" redraw(); \n");
+ wholeScript.append(" }, 1500) \n");
+
+
+
+ wholeScript.append("if(historicalBarChart.length <= 0 ) {\n");
+ wholeScript.append(" document.getElementById(\"chart"+reportRuntime.getReportID()+"\").innerHTML = \"<div id='noData'><b>No Data Available</b></div>\";\n");
+ wholeScript.append(" document.getElementById(\"chart"+reportRuntime.getReportID()+"\").className=\"nodatadiv\";\n");
+ wholeScript.append(" document.getElementById(\"nodata\").className=\"nodatainner\";\n");
+ wholeScript.append("}\n");
+
+ wholeScript.append("</script> </body> </html> \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<String> dateStrList = new TreeSet<String>();
+ // added to store all date elements
+ SortedSet<String> sortSet = new TreeSet<String>();
+ 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<ds.getColumnCount();columnIndex++) {
+ columnName = ds.getColumnName(columnIndex);
+ if(!timeCharts && !columnName.toLowerCase().equals("anomaly_text")) {
+ columnNames.add(columnName);
+ columnValues.add(AppUtils.nvls(ds.getString(i, columnIndex), "null"));
+ } else if (timeCharts) {
+ columnNames.add(columnName);
+ columnValues.add(AppUtils.nvls(ds.getString(i, columnIndex), "null"));
+ }
+ }
+/* actual = ds.getString(i, "actual");
+ //forecast = ds.getString(i, "forecast");
+ upperBound = ds.getString(i, "upperBound");
+ lowerBound = ds.getString(i, "lowerBound");
+
+*/ if(!timeCharts)
+ anomalyText = ds.getString(i, "anomaly_text");
+ //dataStrBuf.append(" [new Date(moment(\""+dateStr+"\")),"+ actual /*+","+ forecast*/+","+ lowerBound +","+ upperBound +"],\n");
+ dataStrBuf.append(" [new Date(moment(\""+dateStr+"\"))");
+ for(int c=0; c< columnNames.size(); c++ ) {
+ columnName = (String) columnNames.get(c);
+ columnValue = (String) columnValues.get(c);
+ for (Iterator iter1 = l.iterator(); iter1.hasNext();) {
+ dct = (DataColumnType) iter1.next();
+ if((dct.getChartSeq()!=null && dct.getChartSeq() >=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("<!DOCTYPE html>\n");
+ wholeScript.append("<html>\n");
+ wholeScript.append(" <head>\n");
+ //wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7; IE=EmulateIE9\">\n");
+ wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n");
+ wholeScript.append("<script type=\"text/javascript\" src=\""+ chartScriptsPath +"dy3/js/dygraph-combined.js\"></script>\n");
+ wholeScript.append("<script type=\"text/javascript\" src=\""+ chartScriptsPath +"dy3/js/moment.min.js\"></script>\n");
+ wholeScript.append("<script type=\"text/javascript\" src=\""+ chartScriptsPath +"dy3/js/interaction.min.js\"></script>\n");
+
+ wholeScript.append("<script type=\"text/javascript\">\n");
+ if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
+ wholeScript.append("var click=2;\n");
+ } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
+ wholeScript.append("var click=3;\n");
+ } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
+ wholeScript.append("var click=3;\n");
+ } else
+ wholeScript.append("var click=3;\n");
+ //wholeScript.append(" var click=0;\n");
+ wholeScript.append(" function downV3(event, g, context) { \n");
+ wholeScript.append(" context.initializeMouseDown(event, g, context); \n");
+ wholeScript.append(" if (event.altKey || event.shiftKey) { \n");
+ wholeScript.append(" var minDate = g.xAxisRange()[0]; \n");
+ wholeScript.append(" var maxDate = g.xAxisRange()[1]; \n");
+ if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
+ wholeScript.append(" if(((maxDate-minDate)/(1000*60*60*24)) > 6) \n");
+ wholeScript.append(" Dygraph.startZoom(event, g, context); \n");
+ } else if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
+ wholeScript.append(" if(((maxDate-minDate)/(1000*60*60)) > 6) \n");
+ wholeScript.append(" Dygraph.startZoom(event, g, context); \n");
+ } else if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
+ wholeScript.append(" if(((maxDate-minDate)/(1000*60*60*2)) > 6) \n");
+ wholeScript.append(" Dygraph.startZoom(event, g, context); \n");
+
+ } else {
+ wholeScript.append(" if(((maxDate-minDate)/(1000*60*60)) > 6) \n");
+ wholeScript.append(" Dygraph.startZoom(event, g, context); \n");
+ }
+ if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
+ wholeScript.append(" click=2;\n");
+ } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
+ wholeScript.append(" click=3;\n");
+ } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
+ wholeScript.append(" click=3;\n");
+ } else
+ wholeScript.append(" click=3;\n");
+ wholeScript.append(" } else if (event.ctrlKey) {\n");
+
+
+ wholeScript.append(" click++;\n");
+ wholeScript.append(" if(click == 1)\n");
+ wholeScript.append(" zoom_custom(3600);\n");
+ wholeScript.append(" else if(click == 2)\n");
+ wholeScript.append(" zoom_custom(12*3600);\n");
+ wholeScript.append(" else if(click == 3)\n");
+ wholeScript.append(" zoom_custom(86400);\n");
+ wholeScript.append(" else if (click == 4)\n");
+ wholeScript.append(" zoom_custom(7*86400);\n");
+ wholeScript.append(" else if (click == 5)\n");
+ wholeScript.append(" zoom_custom(30*86400);\n");
+ wholeScript.append(" else if (click == 6)\n");
+ wholeScript.append(" zoom_custom(90*86400);\n");
+ wholeScript.append(" else if (click == 7)\n");
+ wholeScript.append(" zoom_custom(180*86400);\n");
+ wholeScript.append(" else if (click == 8)\n");
+ wholeScript.append(" zoom_custom(365*86400);\n");
+ wholeScript.append(" else if (click == 10)\n");
+ wholeScript.append(" zoom_custom(5*365*86400);\n");
+ wholeScript.append(" else { \n");
+ wholeScript.append(" reset();\n");
+ wholeScript.append(" }\n");
+ //wholeScript.append(" \n");
+ wholeScript.append(" } else {\n");
+ wholeScript.append(" Dygraph.startPan(event, g, context); \n");
+ wholeScript.append(" } \n");
+ wholeScript.append(" } \n");
+ wholeScript.append("</script>\n ");
+ wholeScript.append("<style type=\"text/css\">\n");
+ wholeScript.append(".annotation {\n");
+ wholeScript.append("}");
+ wholeScript.append(".dygraph-title {\n");
+ wholeScript.append("color: black;\n");
+ wholeScript.append("font-weight:bold; \n");
+ wholeScript.append("}\n");
+ wholeScript.append(".dygraph-axis-label-x { ");
+ wholeScript.append("-webkit-transform:rotate(-0deg);");
+ wholeScript.append("display:block;");
+ /*position:absolute;
+ right:-5px;
+ top:15px;*/
+ wholeScript.append("}\n");
+
+ int widthInt = 0;
+ if(nvl(width).length() > 0) {
+ try {
+ widthInt = new Integer(width).intValue();
+ } catch(Exception ex) {
+ if(width.endsWith("px")) {
+ try {
+ widthInt = new Integer(width.substring(0, width.indexOf("px")));
+ } catch (Exception ex1) {
+ widthInt = 700;
+ }
+ } else {
+ widthInt = 700;
+ }
+ }
+ } else widthInt = 700;
+
+ wholeScript.append(".dygraph-legend {\n");
+ wholeScript.append(" left: "+(widthInt-200)+"px !important;\n");
+ wholeScript.append(" top: 5px !important;\n");
+ wholeScript.append("}\n");
+
+ wholeScript.append(".nodatadiv {\n");
+ wholeScript.append(" display: table-cell;\n");
+ wholeScript.append(" width: 700px;\n");
+ wholeScript.append(" height:370px;\n");
+ wholeScript.append(" text-align:center;\n");
+ wholeScript.append(" vertical-align: middle;\n");
+ wholeScript.append("}\n");
+ wholeScript.append(".nodatainner {\n");
+ wholeScript.append(" padding: 10px;\n");
+ wholeScript.append("}\n");
+
+ wholeScript.append("canvas {\n");
+ wholeScript.append(" -webkit-touch-callout: none; \n");
+ wholeScript.append(" -webkit-user-select: none;\n");
+ wholeScript.append(" -khtml-user-select: none;\n");
+ wholeScript.append(" -moz-user-select: none;\n");
+ wholeScript.append(" user-select: none;\n");
+ wholeScript.append(" user-select: none;\n");
+ wholeScript.append(" outline: none;\n");
+ wholeScript.append(" -webkit-tap-highlight-color: rgba(255, 255, 255, 0); /* mobile webkit */\n");
+ wholeScript.append("}\n");
+ wholeScript.append("</style>\n");
+ wholeScript.append("</head>\n");
+ wholeScript.append("<body> \n");
+
+/* if(showTitle)
+ wholeScript.append(" <p align=\"center\"><b> " + (AppUtils.nvl(reportRuntime.getReportTitle()).length()>0?reportRuntime.getReportTitle():reportRuntime.getReportName()) + "</b></p>\n");
+*/
+ wholeScript.append(" <table>\n");
+ if(showTitle) {
+ wholeScript.append(" <tr> \n ");
+ wholeScript.append(" <td> \n ");
+ wholeScript.append(" <div class=\"dygraph-label dygraph-title\" align=\"center\">"+title+"</div> \n");
+ wholeScript.append(" </td> \n ");
+ }
+
+ wholeScript.append(" </tr> \n ");
+
+ wholeScript.append(" <tr> \n ");
+ wholeScript.append(" <td> \n ");
+ if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()<=0 || reportRuntime.getLegendPosition().equals("top")) {
+ wholeScript.append(" <div id=\"labelDiv"+reportRuntime.getReportID()+"\"></div>\n");
+ }
+ wholeScript.append(" <div id=\"message"+reportRuntime.getReportID()+"\"></div> \n");
+ wholeScript.append(" </td> \n ");
+
+ wholeScript.append(" </tr> \n ");
+ wholeScript.append(" <tr>\n");
+ wholeScript.append(" <td>\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(" <div id=\"div_g"+reportRuntime.getReportID()+"\" style=\"width:"+ (widthInt-250)+ "px; \n" );
+ } else {
+ wholeScript.append(" <div id=\"div_g"+reportRuntime.getReportID()+"\" style=\"width:"+ (widthInt)+ "px; \n" );
+ }
+ wholeScript.append(" height:"+ heightInt +"px;\"></div> \n");
+ wholeScript.append(" </td>\n");
+ if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
+ wholeScript.append(" <td valign=\"top\">\n");
+ wholeScript.append(" <div id=\"labelDiv3716\" valign=\"top\" style=\"width:250px;height:"+ heightInt +"px;\"></div>\n");
+ wholeScript.append(" </td>\n");
+ }
+ wholeScript.append(" </tr>\n");
+ if(anomalyRec > 0) {
+ wholeScript.append(" <tr>\n");
+ wholeScript.append(" <td>\n");
+ wholeScript.append(" <table>\n");
+ wholeScript.append(" <tr>\n");
+ wholeScript.append(" <td align=\"center\"><font size=\"2px\"><B><align=\"center\">Anomaly Description</align></B></font></td>\n");
+ wholeScript.append(" </tr>\n");
+ wholeScript.append(" <tr>\n");
+ wholeScript.append(" <td><div id=\"list"+reportRuntime.getReportID()+"\" style=\"width:" + widthInt + "px; height:50px;\"></div></td>\n" );
+ wholeScript.append(" </tr>\n");
+ wholeScript.append(" </table>\n");
+ wholeScript.append(" </td>\n");
+ wholeScript.append(" </tr>\n");
+ }
+ wholeScript.append(" </table>\n");
+
+ wholeScript.append(" <script type=\"text/javascript\">\n");
+ wholeScript.append(" Dygraph.addEvent(document, \"mousewheel\", function() { lastClickedGraph = null; });\n");
+ wholeScript.append(" Dygraph.addEvent(document, \"click\", function() { lastClickedGraph = null; });\n");
+ wholeScript.append(" var data = []; \n");
+ wholeScript.append(" data = [\n ");
+ wholeScript.append( dataStrBuf.toString());
+ wholeScript.append(" ];\n");
+ wholeScript.append(" if(data.length > 0 ) { \n");
+ wholeScript.append(" var orig_range = [ data[0][0].valueOf(), data[data.length - 1][0].valueOf() ];\n");
+ if(!timeCharts) {
+ wholeScript.append(" function nameAnnotation(ann) { \n");
+ wholeScript.append(" return ann.shortText; \n");
+ //wholeScript.append(" var m = moment(ann.x);\n");
+ //wholeScript.append(" return \"(\" + ann.series + \", \" + m.format(\"YYYY-MM-DD HH\"); + \")\"; \n");
+ wholeScript.append(" }\n");
+ wholeScript.append(" anns = [];\n");
+ }
+ wholeScript.append(" var graph_initialized = false;\n");
+ wholeScript.append(" if(navigator.platform == 'iPad') { ");
+ wholeScript.append(" g = new Dygraph(\n");
+ wholeScript.append(" document.getElementById(\"div_g"+reportRuntime.getReportID()+"\"),\n");
+ //data here
+ /*wholeScript.append(" [\n");
+ wholeScript.append(dataStrBuf.toString());
+ wholeScript.append(" ],\n");*/
+ wholeScript.append(" data , \n");
+ wholeScript.append(" {\n");
+
+ //Labels here
+
+ dct = null;
+ StringBuffer labelStrBuf = new StringBuffer("");
+ StringBuffer colorsStrBuf = new StringBuffer("");
+ StringBuffer visibilityStrBuf = new StringBuffer("");
+ int countChartValues = 0;
+ 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().equals("anomaly_text")) {
+ countChartValues++;
+ labelStrBuf.append("'"+ dct.getDisplayName()+"',");
+ if(!AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))
+ colorsStrBuf.append("'"+ AppUtils.nvl(dct.getChartColor())+"',");
+ visibilityStrBuf.append("true,");
+ }
+ }
+ }
+ if(labelStrBuf.indexOf(",")!=-1) {
+ labelStrBuf.deleteCharAt(labelStrBuf.lastIndexOf(","));
+ visibilityStrBuf.deleteCharAt(visibilityStrBuf.lastIndexOf(","));
+ }
+ if(colorsStrBuf.indexOf(",")!=-1)
+ colorsStrBuf.deleteCharAt(colorsStrBuf.lastIndexOf(","));
+ //if(showTitle)
+ //wholeScript.append("title: '" + (AppUtils.nvl(reportRuntime.getReportTitle()).length()>0?reportRuntime.getReportTitle():reportRuntime.getReportName()) + "',\n");
+ wholeScript.append("maxNumberWidth:6,\n");
+ wholeScript.append("xAxisHeight: 70,\n");
+ wholeScript.append("yAxisLabelWidth: 70,\n");
+ wholeScript.append("xAxisLabelWidth: 45,\n");
+ wholeScript.append("axes: {\n");
+ wholeScript.append("x: {\n");
+ wholeScript.append(" axisLabelFormatter: function(d, gran) {\n");
+ wholeScript.append(" var month = d.getMonth()+1;\n");
+ wholeScript.append(" var day = d.getDate();\n");
+ wholeScript.append(" var year = d.getFullYear();\n");
+ wholeScript.append(" var hour = d.getHours();\n");
+ wholeScript.append(" var minutes = d.getMinutes();\n");
+ wholeScript.append(" var seconds = d.getSeconds();\n");
+ wholeScript.append(" var wholeString = Dygraph.zeropad(month)+'/'+Dygraph.zeropad(day);\n");
+ // wholeScript.append(" if(hour >= 0 && minutes > 0 && seconds > 0) {\n");
+ //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n");
+ //wholeScript.append(" } else if (hour >= 0 && minutes > 0 && seconds == 0) {\n");
+ if(AppUtils.nvl(reportRuntime.getTimeAxisType()).length()==0 || AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly"))
+ wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes);\n");
+ //wholeScript.append(" } else if (hour >= 0 && (minutes >= 0 && seconds > 0)) {\n");
+ //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n");
+ //wholeScript.append(" } else if (hour >= 0) { \n");
+ //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour); \n");
+ //wholeScript.append(" } \n");
+ wholeScript.append(" return wholeString; \n");
+ wholeScript.append(" },\n");
+ wholeScript.append(" ticker: function (a, b, pixels, opts, dygraph, vals) { \n ");
+ wholeScript.append(" if(((b-a)/(1000*60*60)) <= 6) { \n");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.THIRTY_MINUTELY, opts, dygraph); \n");
+ wholeScript.append(" } else if(((b-a)/(1000*60*60)) <= 12) { \n");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.HOURLY, opts, dygraph); \n");
+ wholeScript.append(" } else if (((b-a)/(1000*60*60)) <= 25) \n ");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.TWO_HOURLY, opts, dygraph); \n ");
+ wholeScript.append(" else if(((b-a)/(1000*60*60)) <= 78) \n ");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.SIX_HOURLY, opts, dygraph); \n ");
+ wholeScript.append(" else if(((b-a)/(1000*60*60*24)) <= 12)\n");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.DAILY, opts, dygraph); \n");
+ wholeScript.append(" else if(((b-a)/(1000*60*60*24)) <= 90) \n");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.WEEKLY, opts, dygraph); \n");
+ wholeScript.append(" else \n");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.MONTHLY, opts, dygraph); \n");
+ wholeScript.append(" }, \n");
+ wholeScript.append(" valueFormatter: function(ms) { \n");
+ wholeScript.append(" return new Date(ms).strftime(\"%m/%d/%Y %H:%M\"); \n");
+ wholeScript.append( " }\n" );
+ wholeScript.append(" }\n");
+ wholeScript.append("},\n");
+ wholeScript.append(" interactionModel : { \n");
+ wholeScript.append(" 'mousedown' : downV4,\n");
+ wholeScript.append(" touchstart : newDygraphTouchstart,\n");
+ wholeScript.append(" touchend : Dygraph.defaultInteractionModel.touchend,\n");
+ wholeScript.append(" touchmove : Dygraph.defaultInteractionModel.touchmove\n");
+ //wholeScript.append(" 'dblclick' : dblClickV3,\n");
+ //wholeScript.append(" 'mousewheel' : scrollV3\n");
+
+ /*wholeScript.append(" 'mousedown' : downV3,\n");
+ wholeScript.append(" 'mousemove' : moveV3,\n");
+ wholeScript.append(" 'mouseup' : upV3,\n");
+ wholeScript.append(" 'click' : clickV3,\n");
+ wholeScript.append(" 'dblclick' : dblClickV3,\n");
+ wholeScript.append(" 'mousewheel' : scrollV3\n");*/
+ wholeScript.append("},\n");
+ /*wholeScript.append(" zoomCallback: function(minDate, maxDate, yRanges) { \n");
+ if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
+ wholeScript.append(" if(((maxDate-minDate)/(1000*60*60*24)) < 6) { \n");
+ wholeScript.append(" maxDate = new Date(minDate).setMinutes(6*24*60);\n");
+ wholeScript.append(" g.updateOptions({\n");
+ wholeScript.append(" interactionModel: {},\n");
+ wholeScript.append(" dateWindow: [minDate, maxDate]\n");
+ wholeScript.append(" });\n");
+ } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
+ wholeScript.append(" if(((maxDate-minDate)/(1000*60*60)) <= 6) { \n");
+ wholeScript.append(" maxDate = new Date(minDate).setMinutes(360);\n");
+ wholeScript.append(" g.updateOptions({\n");
+ wholeScript.append(" interactionModel: {},\n");
+ wholeScript.append(" dateWindow: [minDate, maxDate]\n");
+ wholeScript.append(" });\n");
+ } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
+ wholeScript.append(" if(((maxDate-minDate)/(1000*60*60)) <= 3) { \n");
+ wholeScript.append(" maxDate = new Date(minDate).setMinutes(180);\n");
+ wholeScript.append(" g.updateOptions({\n");
+ wholeScript.append(" interactionModel: {},\n");
+ wholeScript.append(" dateWindow: [minDate, maxDate]\n");
+ wholeScript.append(" });\n");
+ } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("weekly")) {
+ wholeScript.append(" if(((maxDate-minDate)/(1000*60*60*24)) < 7) { \n");
+ wholeScript.append(" maxDate = new Date(minDate).setMinutes(7*24*60);\n");
+ wholeScript.append(" g.updateOptions({\n");
+ wholeScript.append(" interactionModel: {},\n");
+ wholeScript.append(" dateWindow: [minDate, maxDate]\n");
+ wholeScript.append(" });\n");
+ }
+ wholeScript.append(" } else {\n");
+ wholeScript.append(" g.updateOptions({\n");
+ wholeScript.append(" interactionModel : {\n");
+ wholeScript.append(" 'mousedown' : downV3,\n");
+ wholeScript.append(" 'mousemove' : moveV3,\n");
+ wholeScript.append(" 'mouseup' : upV3,\n");
+ wholeScript.append(" 'click' : clickV3,\n");
+ wholeScript.append(" 'dblclick' : dblClickV3,\n");
+ wholeScript.append(" 'mousewheel' : scrollV3\n");
+ wholeScript.append(" }\n");
+ wholeScript.append(" });\n");
+ wholeScript.append(" } \n");
+ wholeScript.append(" } ,\n");*/
+ wholeScript.append("dateWindow: ["+minDate+", "+maxDate+"],\n");
+ wholeScript.append("labels: ["+ labelStrBuf +"],\n");
+ wholeScript.append("labelsDiv: \"labelDiv"+reportRuntime.getReportID()+"\",\n");
+ wholeScript.append("labelsShowZeroValues: true,\n");
+ if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
+ wholeScript.append("labelsSeparateLines: true,\n");
+ }
+ wholeScript.append("labelsDivWidth: 200,\n");
+
+ wholeScript.append("animatedZooms: true,\n");
+ wholeScript.append("strokeWidth: 3.0,\n");
+ wholeScript.append("strokeBorderWidth: 2.0,\n");
+ /*wholeScript.append(" labelsDivStyles: { \n");
+ wholeScript.append(" 'backgroundColor': 'rgba(200, 200, 255, 0.75)',\n");
+ wholeScript.append(" 'padding': '4px',\n");
+ wholeScript.append(" 'border': '1px solid black',\n");
+ wholeScript.append(" 'borderRadius': '10px',\n");
+ wholeScript.append(" 'boxShadow': '4px 4px 4px #888',\n");
+ wholeScript.append(" 'width': '50px'\n");
+ wholeScript.append("}, \n");
+ */
+ wholeScript.append("visibility: ["+ visibilityStrBuf +"],\n");
+ if(colorsStrBuf.length() > 0 && colorsStrBuf.length()>=(countChartValues*3+5))
+ wholeScript.append("colors: ["+ colorsStrBuf +"],\n");
+
+ wholeScript.append(" legend: 'always', \n");
+ //Yaxis label here
+ wholeScript.append(" ylabel: '"+ chartLeftAxisLabel +"' , \n");
+
+ //Xaxis label here
+ wholeScript.append(" xlabel: '"+ xAxisLabel +"' , \n");
+
+ //draw points
+ wholeScript.append(" drawPoints: true, \n");
+
+ //stacked graph
+ wholeScript.append(" stackedGraph: false, \n");
+
+ dct = null;
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ dct = (DataColumnType) iter.next();
+ if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) {
+ if(!AppUtils.nvl(dct.getDisplayName()).toLowerCase().equals("anomaly_text")) {
+ if(dct.getChartSeq()!=null && dct.getChartSeq() >=0) {
+ wholeScript.append(" '"+ dct.getDisplayName() + "': {\n");
+ if(AppUtils.nvl(dct.getChartLineType()).length()>0)
+ wholeScript.append(" strokePattern: Dygraph.DASHED_LINE,\n");
+ if(dct.isIsRangeAxisFilled()!=null && dct.isIsRangeAxisFilled().booleanValue()) {
+ wholeScript.append(" fillGraph: true\n");
+ }
+ wholeScript.append(" },\n");
+ }
+ }
+ }
+ }
+
+/* //each labels
+ wholeScript.append(" 'Forecast': {\n");
+
+ //if dashed line
+ wholeScript.append(" strokePattern: Dygraph.DASHED_LINE,\n");
+
+ //if fillable
+ wholeScript.append(" fillGraph: true\n");
+
+ // close each labels
+ wholeScript.append(" }\n");
+*/
+ // callback method
+ if(anomalyRec > 0) {
+ wholeScript.append(" drawCallback: function(g, is_initial) { \n");
+ wholeScript.append(" if (is_initial) { \n");
+ wholeScript.append(" graph_initialized = true; \n");
+ wholeScript.append(" if (anns.length > 0) { \n");
+ wholeScript.append(" g.setAnnotations(anns); \n");
+ wholeScript.append(" }\n");
+ wholeScript.append(" }\n");
+
+ wholeScript.append(" var anns1 = g.annotations();\n");
+ //wholeScript.append(" var html = \"\";\n");
+ wholeScript.append(" var html = \"<select id='x' size='1' style='width: "+ widthInt +"px; font-family : courier; font-size:8pt; font-weight:bold;'>\";\n");
+ wholeScript.append(" for (var i = anns1.length-1; i >= 0 ; i--) {\n");
+ wholeScript.append(" var name = nameAnnotation(anns1[i]);\n");
+ //wholeScript.append(" html += \"<span id='\" + name + \"'>\"\n");
+ wholeScript.append(" if(i==anns1.length-1)\n");
+ wholeScript.append(" html += \"<option value='\" + name + \"' selected ><font size=1>\" \n");
+ wholeScript.append(" else \n");
+ wholeScript.append(" html += \"<option value='\" + name + \"'><font size=1>\" \n");
+ wholeScript.append(" html += name \n");
+ //wholeScript.append(" html += name + \": \" + (anns1[i].shortText || '(icon)')\n");
+ //wholeScript.append(" html += \" -> \" + anns1[i].text + \"</span><br/>\";\n");
+ wholeScript.append(" html += \" : \" + anns1[i].text + \"</font></option>\";\n");
+ wholeScript.append(" }\n");
+ wholeScript.append(" html += \"</select>\" \n");
+ wholeScript.append(" document.getElementById(\"list"+reportRuntime.getReportID()+"\").innerHTML = html;\n");
+ wholeScript.append(" }\n");
+
+
+ wholeScript.append(" }\n");
+ wholeScript.append(" )\n");
+
+ //push annotations
+ wholeScript.append(annotationsStrBuf.toString());
+
+ wholeScript.append(" if (graph_initialized) {\n");
+ wholeScript.append(" g.setAnnotations(anns);\n");
+ wholeScript.append(" } \n");
+ //upate handler script
+
+ wholeScript.append(" var saveBg = '';\n");
+ wholeScript.append(" var num = 0;\n");
+ wholeScript.append(" g.updateOptions( {\n");
+ wholeScript.append(" annotationMouseOverHandler: function(ann) { \n");
+ //wholeScript.append(" document.getElementById(nameAnnotation(ann)).style.fontWeight = 'bold';\n");
+ //wholeScript.append(" saveBg = ann.div.style.backgroundColor;\n");
+ //wholeScript.append(" ann.div.style.backgroundColor = '#ddd';\n");
+ wholeScript.append(" var selectobject = document.getElementById(\"x\");\n");
+ wholeScript.append(" for(var i=0; i<selectobject.length;i++) {\n ");
+ wholeScript.append(" if(selectobject.options[i].value == nameAnnotation(ann)) {\n ");
+ wholeScript.append(" selectobject.options[i].selected = true; \n ");
+ wholeScript.append(" } ");
+ wholeScript.append(" } ");
+
+ wholeScript.append(" },\n");
+ wholeScript.append(" annotationMouseOutHandler: function(ann) {\n");
+ wholeScript.append(" document.getElementById(nameAnnotation(ann)).style.fontWeight = 'normal';\n");
+ wholeScript.append(" ann.div.style.backgroundColor = saveBg;\n");
+ //wholeScript.append(" var selectobject = document.getElementById(\"x\");\n");
+ //wholeScript.append(" for(var i=0; i<selectobject.length;i++) {\n ");
+ //wholeScript.append(" if(selectobject.options[i].value == nameAnnotation(ann)) {\n ");
+ //wholeScript.append(" selectobject.options[i].selected = false; \n ");
+ //wholeScript.append(" } ");
+ //wholeScript.append(" } ");
+
+ wholeScript.append(" }\n");
+ }
+ wholeScript.append(" });\n");
+
+ //Other devices
+ wholeScript.append("} else { \n");
+
+ wholeScript.append(" g = new Dygraph(\n");
+ wholeScript.append(" document.getElementById(\"div_g"+reportRuntime.getReportID()+"\"),\n");
+ //data here
+ /*wholeScript.append(" [\n");
+ wholeScript.append(dataStrBuf.toString());
+ wholeScript.append(" ],\n");*/
+ wholeScript.append(" data , \n");
+ wholeScript.append(" {\n");
+
+ //Labels here
+
+ dct = null;
+ labelStrBuf = new StringBuffer("");
+ colorsStrBuf = new StringBuffer("");
+ visibilityStrBuf = new StringBuffer("");
+ countChartValues = 0;
+ 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().equals("anomaly_text")) {
+ countChartValues++;
+ labelStrBuf.append("'"+ dct.getDisplayName()+"',");
+ if(!AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))
+ colorsStrBuf.append("'"+ AppUtils.nvl(dct.getChartColor())+"',");
+ visibilityStrBuf.append("true,");
+ }
+ }
+ }
+ if(labelStrBuf.indexOf(",")!=-1) {
+ labelStrBuf.deleteCharAt(labelStrBuf.lastIndexOf(","));
+ visibilityStrBuf.deleteCharAt(visibilityStrBuf.lastIndexOf(","));
+ }
+ if(colorsStrBuf.indexOf(",")!=-1)
+ colorsStrBuf.deleteCharAt(colorsStrBuf.lastIndexOf(","));
+ //if(showTitle)
+ //wholeScript.append("title: '" + (AppUtils.nvl(reportRuntime.getReportTitle()).length()>0?reportRuntime.getReportTitle():reportRuntime.getReportName()) + "',\n");
+ wholeScript.append("maxNumberWidth:6,\n");
+ wholeScript.append("xAxisHeight: 70,\n");
+ wholeScript.append("yAxisLabelWidth: 70,\n");
+ wholeScript.append("xAxisLabelWidth: 45,\n");
+ wholeScript.append("axes: {\n");
+ wholeScript.append("x: {\n");
+ wholeScript.append(" axisLabelFormatter: function(d, gran) {\n");
+ wholeScript.append(" var month = d.getMonth()+1;\n");
+ wholeScript.append(" var day = d.getDate();\n");
+ wholeScript.append(" var year = d.getFullYear();\n");
+ wholeScript.append(" var hour = d.getHours();\n");
+ wholeScript.append(" var minutes = d.getMinutes();\n");
+ wholeScript.append(" var seconds = d.getSeconds();\n");
+ wholeScript.append(" var wholeString = Dygraph.zeropad(month)+'/'+Dygraph.zeropad(day);\n");
+ // wholeScript.append(" if(hour >= 0 && minutes > 0 && seconds > 0) {\n");
+ //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n");
+ //wholeScript.append(" } else if (hour >= 0 && minutes > 0 && seconds == 0) {\n");
+ if(AppUtils.nvl(reportRuntime.getTimeAxisType()).length()==0 || AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly"))
+ wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes);\n");
+ //wholeScript.append(" } else if (hour >= 0 && (minutes >= 0 && seconds > 0)) {\n");
+ //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n");
+ //wholeScript.append(" } else if (hour >= 0) { \n");
+ //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour); \n");
+ //wholeScript.append(" } \n");
+ wholeScript.append(" return wholeString; \n");
+ wholeScript.append(" },\n");
+ wholeScript.append(" ticker: function (a, b, pixels, opts, dygraph, vals) { \n ");
+ wholeScript.append(" if(((b-a)/(1000*60*60)) <= 6) { \n");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.THIRTY_MINUTELY, opts, dygraph); \n");
+ wholeScript.append(" } else if(((b-a)/(1000*60*60)) <= 12) { \n");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.HOURLY, opts, dygraph); \n");
+ wholeScript.append(" } else if (((b-a)/(1000*60*60)) <= 25) \n ");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.TWO_HOURLY, opts, dygraph); \n ");
+ wholeScript.append(" else if(((b-a)/(1000*60*60)) <= 78) \n ");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.SIX_HOURLY, opts, dygraph); \n ");
+ wholeScript.append(" else if(((b-a)/(1000*60*60*24)) <= 12)\n");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.DAILY, opts, dygraph); \n");
+ wholeScript.append(" else if(((b-a)/(1000*60*60*24)) <= 90) \n");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.WEEKLY, opts, dygraph); \n");
+ wholeScript.append(" else \n");
+ wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.MONTHLY, opts, dygraph); \n");
+ wholeScript.append(" }, \n");
+ wholeScript.append(" valueFormatter: function(ms) { \n");
+ wholeScript.append(" return new Date(ms).strftime(\"%m/%d/%Y %H:%M\"); \n");
+ wholeScript.append( " }\n" );
+ wholeScript.append(" }\n");
+ wholeScript.append("},\n");
+ wholeScript.append(" interactionModel : { \n");
+
+ wholeScript.append(" 'mousedown' : downV3,\n");
+ wholeScript.append(" 'mousemove' : moveV3,\n");
+ wholeScript.append(" 'mouseup' : upV3,\n");
+ wholeScript.append(" 'click' : clickV3,\n");
+ wholeScript.append(" 'dblclick' : dblClickV3,\n");
+ wholeScript.append(" 'mousewheel' : scrollV3\n");
+ wholeScript.append("},\n");
+ wholeScript.append(" zoomCallback: function(minDate, maxDate, yRanges) { \n");
+ if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
+ wholeScript.append(" if(((maxDate-minDate)/(1000*60*60*24)) < 6) { \n");
+ wholeScript.append(" maxDate = new Date(minDate).setMinutes(6*24*60);\n");
+ wholeScript.append(" g.updateOptions({\n");
+ wholeScript.append(" interactionModel: {},\n");
+ wholeScript.append(" dateWindow: [minDate, maxDate]\n");
+ wholeScript.append(" });\n");
+ } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
+ wholeScript.append(" if(((maxDate-minDate)/(1000*60*60)) <= 6) { \n");
+ wholeScript.append(" maxDate = new Date(minDate).setMinutes(360);\n");
+ wholeScript.append(" g.updateOptions({\n");
+ wholeScript.append(" interactionModel: {},\n");
+ wholeScript.append(" dateWindow: [minDate, maxDate]\n");
+ wholeScript.append(" });\n");
+ } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
+ wholeScript.append(" if(((maxDate-minDate)/(1000*60*60)) <= 3) { \n");
+ wholeScript.append(" maxDate = new Date(minDate).setMinutes(180);\n");
+ wholeScript.append(" g.updateOptions({\n");
+ wholeScript.append(" interactionModel: {},\n");
+ wholeScript.append(" dateWindow: [minDate, maxDate]\n");
+ wholeScript.append(" });\n");
+ } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("weekly")) {
+ wholeScript.append(" if(((maxDate-minDate)/(1000*60*60*24)) < 7) { \n");
+ wholeScript.append(" maxDate = new Date(minDate).setMinutes(7*24*60);\n");
+ wholeScript.append(" g.updateOptions({\n");
+ wholeScript.append(" interactionModel: {},\n");
+ wholeScript.append(" dateWindow: [minDate, maxDate]\n");
+ wholeScript.append(" });\n");
+ }
+ wholeScript.append(" } else {\n");
+ wholeScript.append(" g.updateOptions({\n");
+ wholeScript.append(" interactionModel : {\n");
+ wholeScript.append(" 'mousedown' : downV3,\n");
+ wholeScript.append(" 'mousemove' : moveV3,\n");
+ wholeScript.append(" 'mouseup' : upV3,\n");
+ wholeScript.append(" 'click' : clickV3,\n");
+ wholeScript.append(" 'dblclick' : dblClickV3,\n");
+ wholeScript.append(" 'mousewheel' : scrollV3\n");
+ wholeScript.append(" }\n");
+ wholeScript.append(" });\n");
+ wholeScript.append(" } \n");
+ wholeScript.append(" } ,\n");
+ wholeScript.append("dateWindow: ["+minDate+", "+maxDate+"],\n");
+ wholeScript.append("labels: ["+ labelStrBuf +"],\n");
+ wholeScript.append("labelsDiv: \"labelDiv"+reportRuntime.getReportID()+"\",\n");
+ wholeScript.append("labelsShowZeroValues: true,\n");
+ if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
+ wholeScript.append("labelsSeparateLines: true,\n");
+ }
+ wholeScript.append("labelsDivWidth: 200,\n");
+
+
+ wholeScript.append("animatedZooms: true,\n");
+ wholeScript.append("strokeWidth: 3.0,\n");
+ wholeScript.append("strokeBorderWidth: 2.0,\n");
+
+ /*wholeScript.append(" labelsDivStyles: { \n");
+ wholeScript.append(" 'backgroundColor': 'rgba(200, 200, 255, 0.75)',\n");
+ wholeScript.append(" 'padding': '4px',\n");
+ wholeScript.append(" 'border': '1px solid black',\n");
+ wholeScript.append(" 'borderRadius': '10px',\n");
+ wholeScript.append(" 'boxShadow': '4px 4px 4px #888',\n");
+ wholeScript.append(" 'width': '50px'\n");
+ wholeScript.append("}, \n");
+ */
+ wholeScript.append("visibility: ["+ visibilityStrBuf +"],\n");
+ if(colorsStrBuf.length() > 0 && colorsStrBuf.length()>=(countChartValues*3+5))
+ wholeScript.append("colors: ["+ colorsStrBuf +"],\n");
+
+ wholeScript.append(" legend: 'always', \n");
+ //Yaxis label here
+ wholeScript.append(" ylabel: '"+ chartLeftAxisLabel +"' , \n");
+
+ //Xaxis label here
+ wholeScript.append(" xlabel: '"+ xAxisLabel +"' , \n");
+
+
+ //draw points
+ wholeScript.append(" drawPoints: true, \n");
+
+ //stacked graph
+ wholeScript.append(" stackedGraph: false, \n");
+
+ dct = null;
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
+ dct = (DataColumnType) iter.next();
+ if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) {
+ if(!AppUtils.nvl(dct.getDisplayName()).toLowerCase().equals("anomaly_text")) {
+ if(dct.getChartSeq()!=null && dct.getChartSeq() >=0) {
+ wholeScript.append(" '"+ dct.getDisplayName() + "': {\n");
+ if(AppUtils.nvl(dct.getChartLineType()).length()>0)
+ wholeScript.append(" strokePattern: Dygraph.DASHED_LINE,\n");
+ if(dct.isIsRangeAxisFilled()!=null && dct.isIsRangeAxisFilled().booleanValue()) {
+ wholeScript.append(" fillGraph: true\n");
+ }
+ wholeScript.append(" },\n");
+ }
+ }
+ }
+ }
+
+/* //each labels
+ wholeScript.append(" 'Forecast': {\n");
+
+ //if dashed line
+ wholeScript.append(" strokePattern: Dygraph.DASHED_LINE,\n");
+
+ //if fillable
+ wholeScript.append(" fillGraph: true\n");
+
+ // close each labels
+ wholeScript.append(" }\n");
+*/
+ // callback method
+ if(anomalyRec > 0) {
+ wholeScript.append(" drawCallback: function(g, is_initial) { \n");
+ wholeScript.append(" if (is_initial) { \n");
+ wholeScript.append(" graph_initialized = true; \n");
+ wholeScript.append(" if (anns.length > 0) { \n");
+ wholeScript.append(" g.setAnnotations(anns); \n");
+ wholeScript.append(" }\n");
+ wholeScript.append(" }\n");
+
+ wholeScript.append(" var anns1 = g.annotations();\n");
+ //wholeScript.append(" var html = \"\";\n");
+ wholeScript.append(" var html = \"<select id='x' size='1' style='width: "+ widthInt +"px; font-family : courier; font-size:8pt; font-weight:bold;'>\";\n");
+ wholeScript.append(" for (var i = anns1.length-1; i >= 0 ; i--) {\n");
+ wholeScript.append(" var name = nameAnnotation(anns1[i]);\n");
+ //wholeScript.append(" html += \"<span id='\" + name + \"'>\"\n");
+ wholeScript.append(" if(i==anns1.length-1)\n");
+ wholeScript.append(" html += \"<option value='\" + name + \"' selected ><font size=1>\" \n");
+ wholeScript.append(" else \n");
+ wholeScript.append(" html += \"<option value='\" + name + \"'><font size=1>\" \n");
+ wholeScript.append(" html += name \n");
+ //wholeScript.append(" html += name + \": \" + (anns1[i].shortText || '(icon)')\n");
+ //wholeScript.append(" html += \" -> \" + anns1[i].text + \"</span><br/>\";\n");
+ wholeScript.append(" html += \" : \" + anns1[i].text + \"</font></option>\";\n");
+ wholeScript.append(" }\n");
+ wholeScript.append(" html += \"</select>\" \n");
+ wholeScript.append(" document.getElementById(\"list"+reportRuntime.getReportID()+"\").innerHTML = html;\n");
+ wholeScript.append(" }\n");
+
+
+ wholeScript.append(" }\n");
+ wholeScript.append(" )\n");
+
+ //push annotations
+ wholeScript.append(annotationsStrBuf.toString());
+
+ wholeScript.append(" if (graph_initialized) {\n");
+ wholeScript.append(" g.setAnnotations(anns);\n");
+ wholeScript.append(" } \n");
+ //upate handler script
+
+ wholeScript.append(" var saveBg = '';\n");
+ wholeScript.append(" var num = 0;\n");
+ wholeScript.append(" g.updateOptions( {\n");
+ wholeScript.append(" annotationMouseOverHandler: function(ann) { \n");
+ //wholeScript.append(" document.getElementById(nameAnnotation(ann)).style.fontWeight = 'bold';\n");
+ //wholeScript.append(" saveBg = ann.div.style.backgroundColor;\n");
+ //wholeScript.append(" ann.div.style.backgroundColor = '#ddd';\n");
+ wholeScript.append(" var selectobject = document.getElementById(\"x\");\n");
+ wholeScript.append(" for(var i=0; i<selectobject.length;i++) {\n ");
+ wholeScript.append(" if(selectobject.options[i].value == nameAnnotation(ann)) {\n ");
+ wholeScript.append(" selectobject.options[i].selected = true; \n ");
+ wholeScript.append(" } ");
+ wholeScript.append(" } ");
+
+ wholeScript.append(" },\n");
+ wholeScript.append(" annotationMouseOutHandler: function(ann) {\n");
+ //wholeScript.append(" document.getElementById(nameAnnotation(ann)).style.fontWeight = 'normal';\n");
+ wholeScript.append(" ann.div.style.backgroundColor = saveBg;\n");
+ //wholeScript.append(" var selectobject = document.getElementById(\"x\");\n");
+ //wholeScript.append(" for(var i=0; i<selectobject.length;i++) {\n ");
+ //wholeScript.append(" if(selectobject.options[i].value == nameAnnotation(ann)) {\n ");
+ //wholeScript.append(" selectobject.options[i].selected = false; \n ");
+ //wholeScript.append(" } ");
+ //wholeScript.append(" } ");
+
+ wholeScript.append(" }\n");
+ }
+ wholeScript.append(" });\n");
+
+
+ wholeScript.append("} \n");
+ //}
+ wholeScript.append("} else {\n");
+ wholeScript.append("document.getElementById(\"message"+ reportRuntime.getReportID()+"\").display = \"none\";\n");
+ wholeScript.append("document.getElementById(\"labelDiv"+ reportRuntime.getReportID()+"\").display=\"none\";\n");
+ wholeScript.append("document.getElementById(\"div_g"+reportRuntime.getReportID()+"\").display=\"none\";\n");
+
+ wholeScript.append("document.getElementById(\"div_g"+reportRuntime.getReportID()+"\").innerHTML = \"<div id='noData'><b>No Data Available</b></div>\";\n");
+ wholeScript.append("document.getElementById(\"div_g"+reportRuntime.getReportID()+"\").className=\"nodatadiv\";\n");
+ wholeScript.append("document.getElementById(\"nodata\").className=\"nodatainner\";\n");
+ if(!timeCharts)
+ wholeScript.append("document.getElementById(\"list"+reportRuntime.getReportID()+"\").display=\"none\";\n");
+ wholeScript.append("}\n");
+ wholeScript.append(" </script>\n");
+ wholeScript.append(" </body>\n");
+ wholeScript.append("</html>");
+
+
+ } else if (chartType.equals(AppConstants.GT_SCATTER)) {
+
+ wholeScript.append("<link href=\""+ chartScriptsPath +"d3/css/nv.d3.css\" rel=\"stylesheet\" type=\"text/css\">\n");
+ wholeScript.append("<style>\n " +
+ " body { \n" +
+ " overflow-y:scroll; \n" +
+ " } \n" +
+ " text { \n" +
+ " font: 12px sans-serif; \n" +
+ " } \n" +
+ " tr.z-row-over > td.z-row-inner, tr.z-row-over > .z-cell {" +
+ " background-color: rgb(255, 255, 255); "+
+ "} "+
+ " svg { display: block; } " +
+ " #chart1 svg { \n" +
+ " height: 420px; \n" +
+ " width: 800px; \n" +
+ " min-width: 100px; \n" +
+ " min-height: 100px; \n" +
+ " } \n" +
+
+ " </style> \n" );
+ wholeScript.append("<body> \n");
+ wholeScript.append("<div id=\"chart1\"><svg></svg></div>");
+ //js files
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/d3.v2.js\"></script>\n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/nv.d3.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/tooltip.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/utils.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/legend.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/axis.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/distribution.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/scatter.js\"></script> \n");
+ wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/scatterChart.js\"></script> \n");
+ wholeScript.append("<script> \n");
+ wholeScript.append("nv.addGraph(function() { \n" +
+ " var width1=900, height1=220; \n" +
+ " var chart = nv.models.scatterChart() \n" +
+ " .showDistX(true) \n" +
+ " .showDistY(true) \n" +
+ " .useVoronoi(true) \n" +
+ " .color(d3.scale.category10().range()); \n" +
+/* " .width(width1) \n" +
+ " .height(height1); \n" +
+*/ " chart.xAxis\n" +
+ " .axisLabel('" +legendColumnName + "')\n" +
+ " .tickFormat(d3.format('.02f'));\n" +
+ " chart.yAxis\n" +
+ " .axisLabel('" + chartLeftAxisLabel + "')\n" +
+ " .tickFormat(d3.format('.02f'));\n" +
+ " d3.select('#chart1 svg') \n" +
+ " .datum(getData()) \n" );
+ if(animation)
+ wholeScript.append(" .transition().duration(1200) \n" );
+/* " .attr(\"width\", width1) \n" +
+ " .attr(\"height\", height1) \n" +
+*/ wholeScript.append(" .call(chart); \n" +
+ " nv.utils.windowResize(chart.update);\n"+
+ "return chart; \n" +
+ "}); \n");
+
+ String dateStr = "";
+ Object uniqueElements [] = null;
+ TreeSet ts = new TreeSet();
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ dateStr = ds.getString(i, 2);
+ if(dateStr.length()>0)
+ ts.add(dateStr);
+ }
+ SortedSet s = Collections.synchronizedSortedSet(ts);
+ uniqueElements = s.toArray();
+
+ wholeScript.append(" function getData() { \n " +
+ " var data = [];\n ");
+ for (int i = 0; i < uniqueElements.length; i++) {
+ wholeScript.append(" data.push( {key:'"+ uniqueElements[i]+ "', values:[]})\n");
+ }
+
+
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ for (int k = 0; k < uniqueElements.length; k++) {
+ if(ds.getString(i, 2).equals(uniqueElements[k])) {
+ wholeScript.append("data["+k+"].values.push({x:"+ ds.getString(i, 1) +",y:"+ds.getString(i, 3) + ", size: Math.random() });\n");
+ }
+ }
+ }
+
+ wholeScript.append("return data; } </script></body>\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)<Integer.parseInt(level))
+ dataStr.append("},\n");
+ dataStr.append("\""+ mid +"\": { \n");
+ }
+
+ mid_old = mid;
+ level_old = level;
+ }
+ if(dataStr.toString().endsWith(","))
+ dataStr.deleteCharAt(dataStr.lastIndexOf(","));
+ dataStr.append("}\n");
+ dataStr.append("}\n");
+ try {
+ String formattedReportName = new HtmlStripper().stripSpecialCharacters(reportRuntime.getReportName());
+ String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new java.util.Date());
+ String filename=formattedReportName+formattedDate+user_id+".json";
+ String filenamepath = AppUtils.getExcelTemplatePath()+"../../json/"+filename;
+ System.out.println("filenamepath " + filenamepath);
+ BufferedWriter out = new BufferedWriter(new FileWriter(filenamepath));
+ out.write(dataStr.toString());
+ out.close();
+ request.getSession().setAttribute("jsonFileName", filename);
+ } catch (IOException e) {
+ e.printStackTrace();
+ System.out.println("Exception ");
+ }
+ } else if (chartType.equals(AppConstants.GT_HIERARCHICAL)) {
+
+ StringBuffer dataStr = new StringBuffer("");
+ StringBuffer groupBuffer = new StringBuffer("");
+ StringBuffer s = new StringBuffer("");
+ dataStr.append("{");
+ dataStr.append(" \"groups\":[");
+
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ if(ds.getString(i,"group_ind").equals("Y")) {
+ groupBuffer.append(" { \"name\": \""+ ds.getString(i,"ei1") +"\" },\n");
+ }
+
+ }
+ groupBuffer.deleteCharAt(groupBuffer.lastIndexOf(","));
+ dataStr.append(groupBuffer.toString());
+ dataStr.append("],");
+ dataStr.append("\"nodes\":[");
+ int rowCount = ds.getRowCount();
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ s.append("{ \"name\": \""+ ds.getString(i,"ei1") +"\" , \"group\":"+ ds.getString(i,"groups") +", \"level\":2 }");
+ if (i < (rowCount-1)) s.append(",");
+ dataStr.append(s);
+ s = new StringBuffer("");
+ }
+
+ dataStr.append("],");
+ dataStr.append("\"links\":[");
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ s.append("{ \"source\": "+ ds.getString(i,"source") +" , \"target\":"+ ds.getString(i,"target") +", \"value\":2 }");
+ if (i < (rowCount-1)) s.append(",");
+ dataStr.append(s);
+ s = new StringBuffer("");
+ }
+ dataStr.append("]}");
+ try {
+ String formattedReportName = new HtmlStripper().stripSpecialCharacters(reportRuntime.getReportName());
+ String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new java.util.Date());
+ String filename=formattedReportName+formattedDate+user_id+".json";
+ String filenamepath = AppUtils.getExcelTemplatePath()+"../../json/"+filename;
+ System.out.println("filenamepath " + filenamepath);
+ BufferedWriter out = new BufferedWriter(new FileWriter(filenamepath));
+ out.write(dataStr.toString());
+ out.close();
+ request.getSession().setAttribute("jsonFileName", filename);
+ } catch (IOException e) {
+ e.printStackTrace();
+ System.out.println("Exception ");
+ }
+ }
+
+ }
+ }
+ try {
+ BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
+ out.write(wholeScript.toString());
+ out.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ System.out.println("Exception ");
+ }
+ return wholeScript.toString();
+ }
+
+ public String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ public String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+ public static String nvls(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ public static String nvls(String s, String sDefault) {
+ return nvls(s).equals("") ? sDefault : s;
+ }
+
+ public boolean getFlagInBoolean(String s) {
+ return nvl(s).toUpperCase().startsWith("Y") || nvl(s).toLowerCase().equals("true");
+ }
+
+ public DataSet loadChartData(String userId, HttpServletRequest request) throws RaptorException {
+ if (nvl(getChartType()).length() == 0)
+ return null;
+ //TODO: display chart function to be added.
+ //if (!getDisplayChart())
+ // return null;
+
+ String sql = null;
+ sql = generateChartSQL(userId, request);
+ logger.debug(EELFLoggerDelegate.debugLogger, ("SQL generated " + sql));
+ String dbInfo = reportRuntime.getDBInfo();
+ DataSet ds = ConnectionUtils.getDataSet(sql, dbInfo);
+ if(ds.getRowCount()<=0) {
+ logger.debug(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
+ logger.debug(EELFLoggerDelegate.debugLogger, (getChartType().toUpperCase()+" - " + "Report ID : " + reportRuntime.getReportID() + " DATA IS EMPTY" ));
+ logger.debug(EELFLoggerDelegate.debugLogger, ("QUERY - " + sql));
+ logger.debug(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
+ }
+
+ return ds;
+ } // loadChartData
+
+ public String generateChartSQL(String userId, HttpServletRequest request ) throws RaptorException {
+ List reportCols = reportRuntime.getAllColumns();
+ List chartValueCols = getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, null); // parameter is 0 has this requires all columns.
+ String reportSQL = reportRuntime.getWholeSQL();
+
+ //Add order by clause
+ Pattern re1 = Pattern.compile("(^[\r\n]*|([\\s]))[Oo][Rr][Dd][Ee][Rr](.*?[^\r\n]*)[Bb][Yy]",Pattern.DOTALL);
+ //Pattern re1 = Pattern.compile("order(.*?[^\r\n]*)by", Pattern.DOTALL);
+ Matcher matcher = re1.matcher(reportSQL);
+ //Pattern re1 = Pattern.compile("(^[\r\n]*|([\\s]))[Oo][Rr][Dd][Ee][Rr][Tt](.*?[^\r\n]*)[Bb][Yy]",Pattern.DOTALL);
+ //int startPoint = sql.length()-30;
+
+ reportSQL = reportSQL + " ";
+ reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" SELECT ");
+ //reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ff][Rr][Oo][Mm]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" FROM ");
+ reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" WHERE ");
+ reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Nn]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" WHEN ");
+ reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" AND ");
+
+ if(!reportRuntime.getReportType().equals(AppConstants.RT_HIVE)) {
+ int startPoint = reportSQL.lastIndexOf(" FROM ");
+ if(startPoint <= 0) {
+ startPoint = reportSQL.lastIndexOf(" from ");
+ }
+ if(startPoint <= 0) {
+ startPoint = reportSQL.lastIndexOf("from ");
+ }
+ if(startPoint <= 0) {
+ startPoint = reportSQL.lastIndexOf("FROM ");
+ }
+
+ if (!matcher.find(startPoint)) {
+ reportSQL = reportSQL + " ORDER BY 1" ;
+ }
+ }
+ reportRuntime.setWholeSQL(reportSQL);
+
+ logger.debug(EELFLoggerDelegate.debugLogger, (" *************************************************************************************** "));
+ logger.debug(EELFLoggerDelegate.debugLogger, ("WHOLE_SQL" + reportSQL));
+ logger.debug(EELFLoggerDelegate.debugLogger, (" *************************************************************************************** "));
+
+ 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);
+ String paramValue = nvl(formfield_value);
+ if(paramValue.length()>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<String,String>) 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<String> 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<String> 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;
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+import org.onap.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 <FormFieldJSON> formFieldList;
+ private ArrayList <ChartColumnJSON> 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 <RangeAxisJSON> rangeAxisList;
+ private ArrayList <RangeAxisJSON> rangeAxisRemoveList;
+
+ private ArrayList <ArrayList<Row>> 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<FormFieldJSON> getFormFieldList() {
+ return formFieldList;
+ }
+ public void setFormFieldList(ArrayList<FormFieldJSON> 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<RangeAxisJSON> getRangeAxisList() {
+ return rangeAxisList;
+ }
+ public void setRangeAxisList(ArrayList<RangeAxisJSON> 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<Row> getRowList() {
+ return rowList;
+ }
+ public void setRowList(ArrayList<Row> rowList) {
+ this.rowList = rowList;
+ }*/
+
+ public ArrayList<ArrayList<Row>> getWholeList() {
+ return wholeList;
+ }
+ public void setWholeList(ArrayList<ArrayList<Row>> wholeList) {
+ this.wholeList = wholeList;
+ }
+ //private ArrayList<ColumnHeader> reportDataColumns;
+ //private ArrayList<Map<String,Object>> reportDataRows;
+ public ArrayList<ChartColumnJSON> getChartColumnJSONList() {
+ return chartColumnJSONList;
+ }
+ public void setChartColumnJSONList(ArrayList<ChartColumnJSON> 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 "";
+ }
+ public ArrayList<RangeAxisJSON> getRangeAxisRemoveList() {
+ return rangeAxisRemoveList;
+ }
+ public void setRangeAxisRemoveList(ArrayList<RangeAxisJSON> rangeAxisRemoveList) {
+ this.rangeAxisRemoveList = rangeAxisRemoveList;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.model.ReportHandler;
+import org.onap.portalsdk.analytics.model.base.ChartSeqComparator;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.ConnectionUtils;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
+import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.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 {
+
+ private static final 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<String, String> chartOptionsMap = new HashMap<String, String>();
+ 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<String,String> chartOptionsMap = new HashMap<String, String>();
+ 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<String,String> 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<DataColumnType> dcList = reportRuntime.getOnlyVisibleColumns();
+ int countIndex = 0;
+ ArrayList<ChartColumnJSON> chartColumnJSONList = new ArrayList<ChartColumnJSON>();
+ 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<IdNameValue> formFieldValues = new ArrayList<IdNameValue>();
+ ArrayList<FormFieldJSON> formFieldJSONList = new ArrayList<FormFieldJSON>();
+ if(reportRuntime.getReportFormFields()!=null) {
+ formFieldJSONList = new ArrayList<FormFieldJSON>(reportRuntime.getReportFormFields().size());
+ for (Iterator iter = reportRuntime.getReportFormFields().iterator(); iter.hasNext();) {
+ formFieldValues = new ArrayList<IdNameValue>();
+ 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<DataColumnType> reportCols = reportRuntime.getAllColumns();
+ boolean hasSeriesColumn = false;
+ //ArrayList<Item>
+ for (Iterator<DataColumnType> 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<DataColumnType> 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<RangeAxisJSON> rangeAxisJSONList = new ArrayList<RangeAxisJSON>();
+ 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<ArrayList<Row>> wholeList = new ArrayList<ArrayList<Row>>();
+
+ ArrayList<Row> rowList = new ArrayList<Row>();
+ if(showData) {
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ rowList = new ArrayList<Row>();
+ for (int j = 0; j<ds.getColumnCount(); j++) {
+ Row row = new Row();
+ row.setColId(ds.getColumnName(j));
+ row.setDisplayValue(ds.getString(i, j));
+ row.setDataType(ds.getColumnType(j));
+ rowList.add(row);
+ }
+ wholeList.add(rowList);
+
+ }
+
+ chartJSON.setWholeList(wholeList);
+ }
+ }
+
+
+
+
+
+ }
+ } else {
+ // chart is not visible
+ chartJSON.setReportID(reportRuntime.getReportID());
+ chartJSON.setReportName(reportRuntime.getReportName());
+ chartJSON.setReportDescr(reportRuntime.getReportDescr());
+ chartJSON.setReportTitle(reportRuntime.getReportTitle());
+ chartJSON.setReportSubTitle(reportRuntime.getReportSubTitle());
+ chartJSON.setChartAvailable(displayChart);
+ ChartTypeJSON chartTypeJSON = new ChartTypeJSON();
+ chartTypeJSON.setIndex(0);
+ chartTypeJSON.setTitle("");
+ chartTypeJSON.setValue(chartType);
+ chartJSON.setChartTypeJSON(chartTypeJSON);
+ }
+ //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(chartJSON);
+ } catch (Exception ex) {
+ ex.printStackTrace();
+
+ }
+
+ return jsonInString;
+ }
+
+ public String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ public String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+ public static String nvls(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ public static String nvls(String s, String sDefault) {
+ return nvls(s).equals("") ? sDefault : s;
+ }
+
+ public boolean getFlagInBoolean(String s) {
+ return nvl(s).toUpperCase().startsWith("Y") || nvl(s).toLowerCase().equals("true");
+ }
+
+ public DataSet loadChartData(String userId, HttpServletRequest request) throws RaptorException {
+ if (nvl(getChartType()).length() == 0)
+ return null;
+ //TODO: display chart function to be added.
+ //if (!getDisplayChart())
+ // return null;
+
+ String sql = null;
+ sql = generateChartSQL(userId, request);
+ logger.debug(EELFLoggerDelegate.debugLogger, ("SQL generated " + sql));
+ String dbInfo = reportRuntime.getDBInfo();
+ DataSet ds = ConnectionUtils.getDataSet(sql, dbInfo);
+ if(ds.getRowCount()<=0) {
+ logger.info(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
+ logger.info(EELFLoggerDelegate.debugLogger, (getChartType().toUpperCase()+" - " + "Report ID : " + reportRuntime.getReportID() + " DATA IS EMPTY"));
+ logger.info(EELFLoggerDelegate.debugLogger, ("QUERY - " + sql));
+ logger.info(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
+ }
+
+ return ds;
+ } // loadChartData
+
+ public String generateChartSQL(String userId, HttpServletRequest request ) throws RaptorException {
+ List reportCols = reportRuntime.getAllColumns();
+ List chartValueCols = getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, null); // parameter is 0 has this requires all columns.
+ String reportSQL = reportRuntime.getWholeSQL();
+
+ //Add order by clause
+ Pattern re1 = Pattern.compile("(^[\r\n]*|([\\s]))[Oo][Rr][Dd][Ee][Rr](.*?[^\r\n]*)[Bb][Yy]",Pattern.DOTALL);
+ //Pattern re1 = Pattern.compile("order(.*?[^\r\n]*)by", Pattern.DOTALL);
+ Matcher matcher = re1.matcher(reportSQL);
+ //Pattern re1 = Pattern.compile("(^[\r\n]*|([\\s]))[Oo][Rr][Dd][Ee][Rr][Tt](.*?[^\r\n]*)[Bb][Yy]",Pattern.DOTALL);
+ //int startPoint = sql.length()-30;
+
+ reportSQL = reportSQL + " ";
+ reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" SELECT ");
+ //reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ff][Rr][Oo][Mm]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" FROM ");
+ reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" WHERE ");
+ reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Nn]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" WHEN ");
+ reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" AND ");
+
+ if(!reportRuntime.getReportType().equals(AppConstants.RT_HIVE)) {
+ int startPoint = reportSQL.lastIndexOf(" FROM ");
+ if(startPoint <= 0) {
+ startPoint = reportSQL.lastIndexOf(" from ");
+ }
+ if(startPoint <= 0) {
+ startPoint = reportSQL.lastIndexOf("from ");
+ }
+ if(startPoint <= 0) {
+ startPoint = reportSQL.lastIndexOf("FROM ");
+ }
+
+ if (!matcher.find(startPoint)) {
+ reportSQL = reportSQL + " ORDER BY 1" ;
+ }
+ }
+ reportRuntime.setWholeSQL(reportSQL);
+
+ logger.debug(EELFLoggerDelegate.debugLogger, (" *************************************************************************************** "));
+ logger.debug(EELFLoggerDelegate.debugLogger, ("WHOLE_SQL" + reportSQL));
+ logger.debug(EELFLoggerDelegate.debugLogger, (" *************************************************************************************** "));
+
+ 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);
+ String paramValue = nvl(formfield_value);
+ if(paramValue.length()>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 "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<String,String>) 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<String> 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<String> 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;
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.model.ReportHandler;
+import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.view.ReportData;
+import org.onap.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<String, Object> params = new HashMap<String, Object>();
+
+ //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<String, Object> params = new HashMap<String, Object>();
+ 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<String, String> chartOptionsMap = new HashMap<String, String>();
+
+ 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<String> 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<String,String> chartOptionsMap) {
+ drawD3Charts(chartOptionsMap);
+
+ }
+ */
+
+ public String drawD3Charts(HashMap<String,String> 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<String,String> 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 "";
+
+ }
+
+ }
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.model.base.IdNameValue;
+import org.onap.portalsdk.analytics.view.ColumnHeader;
+import org.onap.portalsdk.analytics.view.DataValue;
+import org.onap.portalsdk.analytics.xmlobj.ColFilterList;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnList;
+import org.onap.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;
+ }
+
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+/* ===========================================================================================
+ * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
+ * 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.onap.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.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
+import org.onap.portalsdk.analytics.error.UserDefinedException;
+import org.onap.portalsdk.analytics.model.base.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+import org.onap.portalsdk.analytics.xmlobj.*;
+
+public class FormField extends org.onap.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 "<a title=\"" + helpText + "\">" + fieldDisplayName + "</a>";
+ 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 "<a href=\"#\" onclick=\"javascript:ShowContent('" + fieldName + "_div')\"><img src=\""+AppUtils.getBaseFolderURL()+"images/quickhelp_dk.gif\" width=\"12\" height=\"12\" alt=\"\" border=\"0\" class=\"qh-element\" /></a>";
+ return ((getHelpText()!=null && getHelpText().length()>0)? "tooltipText=\""+ getHelpText()+"\">": ">");
+ //return ((getHelpText()!=null && getHelpText().length()>0)? "<img src=\"static/fusion/raptor/images/quickhelp_lt.gif\" tooltipText=\""+ getHelpText() + "\"/>": "");
+ }
+
+
+ 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 "<input type=text class=\"text\" size=30 maxlength=50 id=\"" + fieldName +"\" name=\"" + fieldName + "\" value=\""
+ + nvl(fieldDefValue) + "\">\n" + "<a href=\"javascript:showArgPopupNew('"
+ + fieldName + "', 'document.formd." + fieldName
+ + "')\"><img border=0 src=\"" + AppUtils.getImgFolderURL()
+ + "shareicon.gif\" " + getHelpLink(fieldName);
+ */
+ return "obj.value=\""+Utils.singleQuoteEncode(nvl(fieldDefValue))+"\";";
+
+ } else
+ return "";
+ } else if (fieldType.equals(FFT_HIDDEN) || fieldType.equals(FFT_TEXT) || fieldType.equals(FFT_TEXTAREA) ) {
+ StringBuffer sb = new StringBuffer();
+ String oldSQL = "";
+ try {
+ IdNameList lookup = getLookupList();
+ //if(dependsOn != null && dependsOn != "") {
+ //if(dependsOn != null && dependsOn != "" ) {
+ IdNameSql lu = (IdNameSql) lookup;
+ String SQL = lu.getSql();
+ //System.out.println("SQL HIDDEN 1 " + SQL);
+ 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(value == null || value.trim().length()<=0) {
+ value = "NULL";
+ }
+ if(inSchedule) {
+ try {
+ value = java.net.URLDecoder.decode(value, "UTF-8");
+ } catch (UnsupportedEncodingException ex) {
+
+ }
+ }
+ //System.out.println("HIDDEN " + "["+entry.getKey()+"]" + "-" + value);
+ SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", value);
+ }
+
+ lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL());
+ }
+ //System.out.println("SQL HIDDEN 2 " + SQL);
+ //}
+ lookupList = lookup;
+ //}
+ if(nvl(fieldValue).length()>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 "<input type=text class=\"text\" size=30 maxlength=50 id=\"" + fieldName +"\" name=\"" + fieldName + "\" value=\""
+ + nvl(fieldDefValue) + "\">\n" + "<a href=\"javascript:showArgPopupNew('"
+ + fieldName + "', 'document.formd." + fieldName
+ + "')\"><img border=0 src=\"" + AppUtils.getImgFolderURL()
+ + "shareicon.gif\" " + getHelpLink(fieldName);
+ */
+ String progress = "<div id=\""+fieldName+"_content\" style=\"display:none;width:100%;height:100%;align:center;\"> <img src=\""+AppUtils.getImgFolderURL()+"progress.gif\" border=\"0\" alt=\"Loading, please wait...\" /></div> ";
+
+ return progress+"<input type=\"text\" class=\"text\" name=\""+getFieldName()+"_display\" readonly=true value=\""+ fieldDefDisplay +"\""+ getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName) + " \n "
+ +"<input type=\"hidden\" name=\""+getFieldName()+"\" value=\""+nvl(fieldDefValue)+"\"/> \n \n"
+ + "<a href=\"javascript:showArgPopupNew('"
+ + fieldName + "', 'document.formd." + fieldName
+ + "')\"><img border=0 src=\"" + AppUtils.getImgFolderURL()
+ + "shareicon.gif\" " + getHelpLink(fieldName);
+
+ } else
+ return "";
+ } else if (fieldType.equals(FFT_TEXT)) {
+ IdNameValue value = null;
+ String strValue = "";
+ boolean avail_ReadOnly = false;
+ try {
+ IdNameList lookup = getLookupList();
+ IdNameSql lu = null;
+ String valueSQL = "";
+ String oldSQL = "";
+ if(lookup instanceof IdNameSql) {
+ lu = (IdNameSql) lookup;
+ if(lu.getSql().length() > 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 = "<input type=text class=\"text\" size="+(validationType.equals(VT_DATE)?"10":"30") +" maxlength=50 id=\"" + fieldName +"\" name=\""
+ + fieldName + "\" id='"+ fieldName + "' "
+ + (((validationType.equals(VT_DATE)||validationType.equals(VT_TIMESTAMP_HR) ||validationType.equals(VT_TIMESTAMP_MIN) ||validationType.equals(VT_TIMESTAMP_SEC))&& !inSchedule) ? "" : "")
+ + getCallableJavascript(getFieldName(), rr) + " " + (readOnly?" readonly ":" ") + " value=\"";
+
+
+ /*if(getFieldDefaultSQL()!=null)
+ returnString += nvl(value.getId());
+ else
+ returnString += fieldValue;
+ */
+ if(fieldValue!=null && fieldValue.length()>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<a href=\"#\" onClick=\"window.dateField=document."
+ + HTML_FORM
+ + "."
+ + fieldName
+ + ";calendar=window.open('"
+ + AppUtils.getRaptorActionURL()
+ + "popup.calendar','cal','WIDTH=200,HEIGHT=250');return false;\">"
+ + "\n\t\t\t\t<img src=\""
+ + AppUtils.getImgFolderURL()
+ + "calender_icon.gif\" align=absmiddle border=0 width=20 height=20></a>"
+ : ""); */
+
+ 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<img src='" + AppUtils.getImgFolderURL()+ "calender_icon.gif' align=absmiddle border=0 width='20' height='20' onClick=" + calendarOnClickMethodCall + " style='cursor:hand'>"
+ : "");
+ if(validationType.equals(VT_TIMESTAMP_HR) || validationType.equals(VT_TIMESTAMP_MIN) || validationType.equals(VT_TIMESTAMP_SEC) ) {
+ //Add Hours/Minutes and Seconds.
+ timeStampStr = " <font class=rtabletext>Hour </font><select id = \""+ fieldName+ "_Hr\" name=\""+ fieldName+ "_Hr\" "+ (readOnly?"disabled":"")+" >";
+ int hour = 0;
+ int t_hr = 0;
+ try {
+ hour = Integer.parseInt(nvl(rr.getParamValue(fieldName+"_Hr"),"0"));
+ if(hour == 0) {
+ if(inSchedule) hour = Integer.parseInt(nvl(((String)formValues.get(fieldName+"_Hr")),"0"));
+ }
+// System.out.println("Hour =" + hour);
+ } catch (NumberFormatException ex) { hour = 0; }
+ try {
+ t_hr = Integer.parseInt(timestamphr);
+// System.out.println("THR =" + t_hr);
+ } catch (NumberFormatException ex) { t_hr = 0;}
+
+ if(hour <= 0) hour = t_hr;
+ // System.out.println("Form Values 887 " + formValues);
+ /*if (formValues.containsKey(fieldDisplayName+"_Hr")){
+ formValues.remove(fieldDisplayName+"_Hr");
+ formValues.put(fieldDisplayName+"_Hr", hour);
+ } else
+ formValues.put(fieldDisplayName+"_Hr", hour);
+ System.out.println("Form Values 887 " + formValues);
+ */
+
+ //int t_min = Integer.parseInt(timestampmin);
+ //int t_sec = Integer.parseInt(timestampsec);
+ for (int i = 0; i < 24; i++) {
+ if(i==0) timeStampStr += "<option value=\"" + i + "\""+ ((hour==i)?" selected":"") +">00</option>";
+ else if(i<10) timeStampStr += "<option value=\"" + i + "\""+ ((hour==i)?" selected":"") +">" + "0"+i + "</option>";
+ else timeStampStr += "<option value=\"" + i + "\""+ ((hour==i)?" selected":"") +">" + i + "</option>";
+
+ }
+ timeStampStr += "</select>";
+ }
+ //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 += " <font class=rtabletext>Min </font><select id = \""+ fieldName+ "_Min\" name=\""+ fieldName+ "_Min\" "+ (readOnly?"disabled":"")+" >";
+ for (int i = 0; i < 60; i++) {
+ if(i==0) timeStampStr += "<option value=\"" + i + "\""+ ((minutes==i)?" selected":"") +">00</option>";
+ else if(i<10) timeStampStr += "<option value=\"" + i + "\""+ ((minutes==i)?" selected":"") +">" + "0"+i + "</option>";
+ else timeStampStr += "<option value=\"" + i + "\""+ ((minutes==i)?" selected":"") +">" + i + "</option>";
+ }
+ timeStampStr += "</select>";
+ }
+ //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 += " <font class=rtabletext>Sec </font><select id = \""+ fieldName+ "_Sec\" name=\""+ fieldName+ "_Sec\" "+ (readOnly?"disabled":"")+" >";
+ for (int i = 0; i < 60; i++) {
+ if(i==0) timeStampStr += "<option value=\"" + i + "\""+ ((seconds==i)?" selected":"") +">00</option>";
+ else if(i<10) timeStampStr += "<option value=\"" + i + "\""+ ((seconds==i)?" selected":"") +">" + "0"+i + "</option>";
+ else timeStampStr += "<option value=\"" + i + "\""+ ((seconds==i)?" selected":"") +">" + i + "</option>";
+ }
+ timeStampStr += "</select>";
+ }
+
+ 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 +" "+ */ "<input type=\"checkbox\" name=\""+getFieldName()+"_auto\" value=\"_auto\" checked/>";
+ } else {
+ checkboxStr = /*checkboxStr +" "+ */"<input type=\"hidden\" name=\""+getFieldName()+"_auto\" value=\"_auto\"/>";
+ }
+ /*if(validationType.equals(VT_TIMESTAMP_HR) || validationType.equals(VT_TIMESTAMP_MIN) || validationType.equals(VT_TIMESTAMP_SEC)) {
+ checkboxStr = checkboxStr +" "+ "<input type=\"hidden\" name=\""+getFieldName()+"_Hr_auto\" value=\"_auto\"/>";
+ }
+ if(validationType.equals(VT_TIMESTAMP_MIN) || validationType.equals(VT_TIMESTAMP_SEC)) {
+ checkboxStr = checkboxStr +" "+ "<input type=\"hidden\" name=\""+getFieldName()+"_Min_auto\" value=\"_auto\"/>";
+ }
+ if(validationType.equals(VT_TIMESTAMP_SEC)) {
+ checkboxStr = checkboxStr +" "+ "<input type=\"hidden\" name=\""+getFieldName()+"_Sec_auto\" value=\"_auto\"/>";
+ }*/
+ }
+ 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 "<textarea rows=4 cols=30 id=\"" + fieldName +"\" name=\"" + fieldName + "\""+ getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName) + nvl(fieldValue)
+ + "</textarea>";
+ else
+ return "";
+ } else if (fieldType.equals(FFT_COMBO_BOX)) {
+ StringBuffer sb = new StringBuffer();
+ //System.out.println("COMBO BOX " + fieldName);
+ String oldSQL = "";
+
+ IdNameList lookup = getLookupList();
+ try {
+ if(!hasPredefinedList) {
+ //if(dependsOn != null && dependsOn != "") {
+ //if(dependsOn != null && dependsOn != "" ) {
+ IdNameSql lu = (IdNameSql) lookup;
+ String SQL = lu.getSql();
+ //System.out.println("FORMFIELD 6666667 First" + ((IdNameSql)lookup).getSql());
+ 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 (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();
+
+ for (lookup.resetNext(); lookup.hasNext();) {
+ IdNameValue value = lookup.getNext();
+ readOnly = value.isReadOnly();
+ break;
+ }
+
+ String selectedValue = "";
+ int count = 0;
+ sb.append("<div id=\""+fieldName+"_content\" style=\"display:none;width:100%;height:100%;align:center;\"> <img src=\""+AppUtils.getImgFolderURL()+"progress.gif\" border=\"0\" alt=\"Loading, please wait...\" /></div>");
+ sb.append("<select id=\"" + fieldName +"\" name=\"");
+ sb.append(fieldName);
+ sb.append("\" "+ (readOnly?"disabled":"")+" size=1 " + getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName));
+ if (!required)
+ sb.append("<option value=\"\">-->select value<--");
+
+ 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("<option value=\"");
+ sb.append(value.getId());
+
+ if (nvl(fieldValue).length()>0) {
+ if (fieldValue.equals(value.getId())) { // || (value.isDefaultValue()))
+ sb.append("\" selected>");
+ selectedValue = value.getId();
+ }
+ else
+ sb.append("\">");
+ } else {
+ if(value!=null && value.isDefaultValue()) {
+ sb.append("\" selected>");
+ selectedValue = value.getId();
+ } else {
+ sb.append("\">");
+ }
+ }
+
+ sb.append(value.getName());
+ sb.append("</option>\n");
+ }
+ } // 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(sb.length()<=0) {
+ sb.append("<div id=\""+fieldName+"_content\" style=\"display:none;width:100%;height:100%;align:center;\"> <img src=\""+AppUtils.getImgFolderURL()+"progress.gif\" border=\"0\" alt=\"Loading, please wait...\" /></div>");
+ sb.append("<select id=\"" + fieldName +"\" name=\"");
+ sb.append(fieldName);
+ sb.append("\" "+ (readOnly?"disabled":"")+" size=1 " + getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName));
+ }
+
+ sb.append("</select>");
+ if( isVisible())
+ return sb.toString();
+ else return "";
+ } else if (fieldType.equals(FFT_LIST_BOX)) {
+ StringBuffer sb = new StringBuffer();
+ String oldSQL = "";
+ IdNameList lookup = null;
+
+ lookup = getLookupList();
+ String selectedValue = "";
+ try {
+ if(!hasPredefinedList) {
+ //if(dependsOn != null && dependsOn != "") {
+ //if(dependsOn != null && dependsOn != "" ) {
+ IdNameSql lu = (IdNameSql) lookup;
+ String SQL = lu.getSql();
+ 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);
+ }
+ 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();
+
+ for (lookup.resetNext(); lookup.hasNext();) {
+ IdNameValue value = lookup.getNext();
+ readOnly = value.isReadOnly();
+ break;
+ }
+
+ int iCnt = 0;
+ sb.append("<select id=\"" + fieldName +"\" name=\"");
+ sb.append(fieldName);
+ sb.append("\" "+ (readOnly?"disabled":"")+" size=4 " + getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName));
+ if (!required)
+ sb.append("<option value=\"\">-->select value<--");
+
+ for (lookup.resetNext(); lookup.hasNext(); iCnt++) {
+ IdNameValue value = lookup.getNext();
+ sb.append("<option value=\"");
+ sb.append((value!=null)?value.getId():"");
+ if (nvl(fieldValue).length()>0) {
+ if (fieldValue.equals((value!=null)?value.getId():"") || (fieldValue.equals("") && required && iCnt == 0)) {
+ sb.append("\" selected>");
+ selectedValue = value.getId();
+ } else {
+ sb.append("\">");
+ }
+ } else {
+ if(value!=null && value.isDefaultValue()) {
+ sb.append("\" selected>");
+ selectedValue = value.getId();
+ } else {
+ sb.append("\">");
+ }
+ }
+ if (formValues.containsKey(fieldDisplayName)){
+ formValues.remove(fieldDisplayName);
+ }
+ formValues.put(fieldDisplayName, selectedValue);
+
+ sb.append((value!=null)?value.getName():"");
+ sb.append("</option>\n");
+ } // for
+
+ // lookup.clearData();
+ } catch (Exception e) {
+ //throw new RaptorRuntimeException(e);
+ }
+
+ if(sb.length()<=0) {
+ sb.append("<select id=\"" + fieldName +"\" name=\"");
+ sb.append(fieldName);
+ sb.append("\" "+ (readOnly?"disabled":"")+" size=4 " + getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName));
+ }
+
+ sb.append("</select>");
+
+ if(!hasPredefinedList) {
+ if(oldSQL != null && !oldSQL.equals("")) {
+ ((IdNameSql)lookup).setSQL(oldSQL);
+ }
+ }
+
+ if(isVisible())
+ return sb.toString();
+ else
+ return "";
+ } else if (fieldType.equals(FFT_HIDDEN)) {
+ StringBuffer sb = new StringBuffer();
+ String oldSQL = "";
+ String progress = "<div id=\""+fieldName+"_content\" style=\"display:none;width:100%;height:100%;align:center;\"> <img src=\""+AppUtils.getImgFolderURL()+"progress.gif\" border=\"0\" alt=\"Loading, please wait...\" /></div> ";
+ sb.append(progress);
+ sb.append("<input id=\"" + fieldName +"\" name=\"");
+ sb.append(fieldName);
+ sb.append("\" type=\"hidden\"");
+ IdNameList lookup = null;
+
+ try {
+ lookup = getLookupList();
+ if(lookup != null) {
+ //if(dependsOn != null && dependsOn != "") {
+ //if(dependsOn != null && dependsOn != "" ) {
+ IdNameSql lu = (IdNameSql) lookup;
+ String SQL = lu.getSql();
+ //System.out.println("SQL HIDDEN 1 " + SQL);
+ 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();
+ //System.out.println("HIDDEN " + "["+entry.getKey()+"]" + "-" + value);
+ SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", value);
+ }
+
+ lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL());
+ }
+ //System.out.println("SQL HIDDEN 2 " + SQL);
+ //}
+ lookupList = lookup;
+ //}
+ if(nvl(fieldValue).length()>0 && (dependsOn == null || dependsOn.length()<=0)) {
+ sb.append(" value=\"");
+ sb.append((fieldValue!=null)?fieldValue:"");
+ sb.append("\">");
+ } 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=\"");
+ sb.append((value!=null)?value.getId():"");
+ sb.append("\">");
+ break;
+ } // for
+ if(lookup.size()<=0) {
+ sb.append(" value=\"");
+ sb.append("\">");
+
+ }
+ } else {
+ sb.append(" value=\"");
+ sb.append((fieldValue!=null)?fieldValue:"");
+ sb.append("\"/>");
+ }
+ } else {
+ sb.append(" value=\"");
+ sb.append((fieldValue!=null)?fieldValue:"");
+ sb.append("\"/>");
+ }
+ if(oldSQL != null && !oldSQL.equals("")) {
+ ((IdNameSql)lookup).setSQL(oldSQL);
+ }
+ // lookup.clearData();
+ } catch (Exception e) {
+ sb.append(" value=\"\"/>");
+ //throw new RaptorRuntimeException(e);
+ }
+
+ if(!hasPredefinedList) {
+ if(oldSQL != null && !oldSQL.equals("")) {
+ ((IdNameSql)lookup).setSQL(oldSQL);
+ }
+ }
+ //if(isVisible())
+ return sb.toString() ;
+ } else if (fieldType.equals(FFT_RADIO_BTN)) {
+ StringBuffer sb = new StringBuffer();
+ if (!required) {
+ sb.append("<input id=\"" + fieldName +"\" type=radio name=\"");
+ sb.append(fieldName);
+ sb.append("\" value=\"\"");
+ if (fieldValue.length() == 0)
+ sb.append(" checked");
+ //sb.append( getCallableJavascript(getFieldName(), rr) );
+ sb.append(getHelpLink(fieldName)+ " Any<br>\n");
+ }
+
+ try {
+ IdNameList lookup = getLookupList();
+ lookup.loadUserData(0, "", getDbInfo(),getUserId());
+ String selectedValue = "";
+
+ int iCnt = 0;
+ for (lookup.resetNext(); lookup.hasNext(); iCnt++) {
+ IdNameValue value = lookup.getNext();
+ sb.append("<input id=\"" + fieldName +"\" type=radio name=\"");
+ sb.append(fieldName);
+ sb.append("\" value=\"");
+ sb.append((value!=null)?value.getId():"");
+ if (nvl(fieldValue).length()>0) {
+ if (fieldValue.equals((value!=null)?value.getId():"") || (fieldValue.equals("") && required && iCnt == 0)) {
+ sb.append("\" checked>");
+ selectedValue = value.getId();
+ } else {
+ sb.append("\">");
+ }
+ } else {
+ if(value!=null && value.isDefaultValue()) {
+ sb.append("\" checked>");
+ selectedValue = value.getId();
+ } else {
+ sb.append("\">");
+ }
+ }
+ sb.append((value!=null)?value.getName():"");
+ sb.append("<br>\n");
+ } // for
+ if (formValues.containsKey(fieldDisplayName)){
+ formValues.remove(fieldDisplayName);
+ }
+ formValues.put(fieldDisplayName, selectedValue);
+
+ // lookup.clearData();
+ } catch (Exception e) {
+ throw new RaptorRuntimeException(e);
+ }
+ if(isVisible())
+ return sb.toString() ;
+ else
+ return "";
+ } else if (fieldType.equals(FFT_CHECK_BOX)) {
+ StringBuffer sb = new StringBuffer();
+
+ fieldValue = '|' + fieldValue + '|';
+ int count = 0 ;
+ try {
+ String selectedValue = "";
+ IdNameList lookup = getLookupList();
+ if(lookup != null) {
+ lookup.loadUserData(0, "", getDbInfo(), getUserId());
+
+ for (lookup.resetNext(); lookup.hasNext();) {
+ count++;
+ IdNameValue value = lookup.getNext();
+ sb.append("<input id=\"" + fieldName +"\" type=checkbox name=\"");
+ sb.append(fieldName);
+ sb.append("\" value=\"");
+ sb.append((value!=null)?value.getId():"");
+
+ if (!fieldValue.equals("||")) {
+ if (fieldValue.indexOf('|' + ((value!=null)?value.getId():"") + '|') >= 0) { // || (value.isDefaultValue()))
+ sb.append("\" checked " + getHelpLink(fieldName));
+ selectedValue = value.getId();
+ }
+ else
+ sb.append("\"" + getHelpLink(fieldName));
+ } else {
+ if(value!=null && value.isDefaultValue()) {
+ sb.append("\" checked " + getHelpLink(fieldName));
+ selectedValue = value.getId();
+ } else {
+ sb.append("\"" + getHelpLink(fieldName));
+ }
+ }
+
+ if(!(/*(value.getName().equals("Y")||value.getName().equals("N")) && */(!lookup.hasNext()) && count == 1))
+ sb.append((value!=null)?value.getName():"");
+ sb.append("<br>\n");
+ } // for
+
+ if (formValues.containsKey(fieldDisplayName)){
+ formValues.remove(fieldDisplayName);
+ }
+ formValues.put(fieldDisplayName, selectedValue);
+ }
+
+ // lookup.clearData();
+ } catch (Exception e) {
+ throw new RaptorRuntimeException(e);
+ }
+ 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 = lu.getSql();
+ 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);
+ }
+ lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL());
+ }
+ //}
+ lookupList = lookup;
+ //}
+
+ lookup.loadUserData(0, "", getDbInfo(),getUserId());
+ }
+ for (lookup.resetNext(); lookup.hasNext();) {
+ IdNameValue value = lookup.getNext();
+ readOnly = value.isReadOnly();
+ break;
+ }
+
+ sb.append("<div id=\""+fieldName+"_content\" style=\"display:none;width:100%;height:100%;align:center;\"> <img src=\""+AppUtils.getImgFolderURL()+"progress.gif\" border=\"0\" alt=\"Loading, please wait...\" /></div>");
+ sb.append("<select id=\"" + fieldName +"\" name=\"");
+ sb.append(fieldName);
+ sb.append("\" "+ (readOnly?"disabled":"")+" size=\""+ multiSelectListSize +"\" multiple " + getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName));
+
+ for (lookup.resetNext(); lookup.hasNext();) {
+ IdNameValue value = lookup.getNext();
+ sb.append("<option value=\"");
+ sb.append((value!=null)?value.getId():"");
+ if (!fieldValue.equals("||")) {
+ if (fieldValue.indexOf('|' + ((value!=null)?value.getId():"") + '|') >= 0) // || (value.isDefaultValue()))
+ sb.append("\" selected>");
+ else
+ sb.append("\">");
+ } else {
+ if(value!=null && value.isDefaultValue()) {
+ sb.append("\" selected>");
+ } else {
+ sb.append("\">");
+ }
+ }
+ sb.append((value!=null)?value.getName():"");
+ sb.append("</option>\n");
+ } // for
+
+ // lookup.clearData();
+ } catch (Exception e) {
+ //throw new RaptorRuntimeException(e);
+ }
+ if(!hasPredefinedList) {
+ if(oldSQL != null && !oldSQL.equals("")) {
+ ((IdNameSql)lookup).setSQL(oldSQL);
+ }
+ }
+ if(sb.length()<=0) {
+ sb.append("<div id=\""+fieldName+"_content\" style=\"display:none;width:100%;height:100%;align:center;\"> <img src=\""+AppUtils.getImgFolderURL()+"progress.gif\" border=\"0\" alt=\"Loading, please wait...\" /></div>");
+ sb.append("<select id=\"" + fieldName +"\" name=\"");
+ sb.append(fieldName);
+ sb.append("\" "+ (readOnly?"disabled":"")+" size=\""+ multiSelectListSize +"\" multiple " + getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName));
+ }
+ sb.append("</select>");
+ if(isVisible())
+ return sb.toString();
+ else
+ return "";
+ } else if (fieldType.equals(FFT_BLANK)) {
+ StringBuffer sb = new StringBuffer();
+ sb.append(" ");
+ return sb.toString();
+ } else
+ throw new org.onap.portalsdk.analytics.error.RaptorRuntimeException("FormField.getHtml: Unsupported form field type");
+ } // getHtml
+
+ public String getValidateJavaScript() {
+ StringBuffer javaScript = new StringBuffer();
+
+ if (fieldType.equals(FFT_TEXT_W_POPUP) || fieldType.equals(FFT_TEXT)
+ || fieldType.equals(FFT_TEXTAREA)) {
+ if (required) {
+ javaScript.append("\n\tif(document.");
+ javaScript.append(HTML_FORM);
+ javaScript.append(".");
+ javaScript.append(fieldName);
+ javaScript.append(".value==\"\") {\n\t\talert(\"Please enter value for ");
+ javaScript.append(fieldDisplayName);
+ javaScript.append("\");\n\t\tdocument.");
+ javaScript.append(HTML_FORM);
+ javaScript.append(".");
+ javaScript.append(fieldName);
+ javaScript.append(".focus();\n\t\tdocument.");
+ javaScript.append(HTML_FORM);
+ javaScript.append(".");
+ javaScript.append(fieldName);
+ javaScript.append(".select();\n\t\treturn false;\n\t}\n");
+ } // if
+
+ if (!validationType.equals(VT_NONE)) {
+ javaScript.append("\n\tif(! ");
+ if (validationType.equals(VT_DATE)||validationType.equals(VT_TIMESTAMP_HR)||validationType.equals(VT_TIMESTAMP_MIN)||validationType.equals(VT_TIMESTAMP_SEC))
+ javaScript.append("checkDate(");
+ else if (validationType.equals(VT_INT))
+ javaScript.append("checkInteger(");
+ else if (validationType.equals(VT_INT_POSITIVE))
+ javaScript.append("checkPositiveInteger(");
+ else if (validationType.equals(VT_INT_NON_NEGATIVE))
+ javaScript.append("checkNonNegativeInteger(");
+ else if (validationType.equals(VT_FLOAT))
+ javaScript.append("checkFloat(");
+ else if (validationType.equals(VT_FLOAT_POSITIVE))
+ javaScript.append("checkPositiveFloat(");
+ else if (validationType.equals(VT_FLOAT_NON_NEGATIVE))
+ javaScript.append("checkNonNegativeFloat(");
+ javaScript.append("document.");
+ javaScript.append(HTML_FORM);
+ javaScript.append(".");
+ javaScript.append(fieldName);
+ javaScript.append(".value");
+ if (validationType.equals(VT_DATE)||validationType.equals(VT_TIMESTAMP_HR)||validationType.equals(VT_TIMESTAMP_MIN)||validationType.equals(VT_TIMESTAMP_SEC))
+ javaScript.append(", true");
+ javaScript.append(")) {\n\t\talert(\"");
+ javaScript.append(fieldDisplayName);
+ javaScript.append(" is not a valid ");
+ if (validationType.equals(VT_DATE)||validationType.equals(VT_TIMESTAMP_HR)||validationType.equals(VT_TIMESTAMP_MIN)||validationType.equals(VT_TIMESTAMP_SEC))
+ javaScript.append("date formatted "+ Globals.getCalendarOutputDateFormat());
+ else if (validationType.equals(VT_INT))
+ javaScript.append("integer");
+ else if (validationType.equals(VT_INT_POSITIVE))
+ javaScript.append("integer greater than zero");
+ else if (validationType.equals(VT_INT_NON_NEGATIVE))
+ javaScript.append("integer greater than or equal to zero");
+ else if (validationType.equals(VT_FLOAT))
+ javaScript.append("number");
+ else if (validationType.equals(VT_FLOAT_POSITIVE))
+ javaScript.append("number greater than zero");
+ else if (validationType.equals(VT_FLOAT_NON_NEGATIVE))
+ javaScript.append("number greater than or equal to zero");
+ javaScript.append(".\\nPlease enter a valid value.\");\n\t\tdocument.");
+ javaScript.append(HTML_FORM);
+ javaScript.append(".");
+ javaScript.append(fieldName);
+ javaScript.append(".focus();\n\t\tdocument.");
+ javaScript.append(HTML_FORM);
+ javaScript.append(".");
+ javaScript.append(fieldName);
+ javaScript.append(".select();\n\t\treturn false;\n\t}\n");
+ } // if
+ } // if
+ else if (fieldType.equals(FFT_CHECK_BOX)) {
+ if (required) {
+ javaScript.append("\n\tvar isChecked = false;");
+ javaScript.append("\n\tfor (var i=0; i < document.");
+ javaScript.append(HTML_FORM);
+ javaScript.append(".");
+ javaScript.append(fieldName);
+ javaScript.append(".length; i++) { ");
+ javaScript.append("\n\t\tif(document.");
+ javaScript.append(HTML_FORM);
+ javaScript.append(".");
+ javaScript.append(fieldName);
+ javaScript.append("[i].checked) {");
+ javaScript.append("\n\t\t\tisChecked = true;");
+ javaScript.append("\n\t\t\tbreak;");
+ javaScript.append("\n\t\t}");
+ javaScript.append("\n\t}");
+ javaScript.append("\n\tif(!isChecked) {");
+ javaScript.append("\n\t\talert(\"Please select at least one ");
+ javaScript.append(fieldDisplayName);
+ javaScript.append("\");\n\t\treturn false;");
+ javaScript.append("\n\t}");
+ } // if
+ } // else if FFT_CHECK_BOX
+ else if (fieldType.equals(FFT_LIST_MULTI)) {
+ if (required) {
+ javaScript.append("\n\tif(document.");
+ javaScript.append(HTML_FORM);
+ javaScript.append(".");
+ javaScript.append(fieldName);
+ javaScript.append(".selectedIndex == -1) {");
+ javaScript.append("\n\t\talert(\"Please select at least one ");
+ javaScript.append(fieldDisplayName);
+ javaScript.append("\");\n\t\treturn false;");
+ javaScript.append("\n\t}");
+ } // if
+ } // else if
+
+ return javaScript.toString();
+ } // getValidateJavaScript
+
+ public void setDbInfo(String dbInfo) {
+ this.dbInfo = dbInfo;
+ }
+
+ public String getDbInfo() {
+ return dbInfo;
+ }
+
+ public void setUserId(String userId) {
+ this.userId = userId;
+ }
+
+ public String getUserId() {
+ return userId;
+ }
+
+
+ public String getFieldDefaultSQL() {
+
+ return fieldDefaultSQL;
+ }
+
+
+ public void setFieldDefaultSQL(String fieldDefaultSQL) {
+
+ this.fieldDefaultSQL = fieldDefaultSQL;
+ }
+
+
+ public boolean isVisible() {
+
+ return visible;
+ }
+
+
+ public void setVisible(boolean visible) {
+
+ this.visible = visible;
+ }
+
+ public String getDependsOn() {
+ return dependsOn;
+ }
+
+ public void setDependsOn(String dependsOn) {
+ this.dependsOn = dependsOn;
+ }
+
+ public Calendar getRangeEndDate() {
+ if(rangeEndDate != null)
+ rangeEndDate.add(Calendar.DATE, 1);
+ return rangeEndDate;
+ }
+
+ public void setRangeEndDate(Calendar rangeEndDate) {
+ this.rangeEndDate = rangeEndDate;
+ }
+
+ public Calendar getRangeStartDate() {
+ if(rangeStartDate != null)
+ rangeStartDate.add(Calendar.DATE, -1);
+ return rangeStartDate;
+ }
+
+ public void setRangeStartDate(Calendar rangeStartDate) {
+ this.rangeStartDate = rangeStartDate;
+ }
+
+ public String getRangeEndDateSQL() {
+ return rangeEndDateSQL;
+ }
+
+ public void setRangeEndDateSQL(String rangeEndDateSQL) {
+ this.rangeEndDateSQL = rangeEndDateSQL;
+ }
+
+ public void setMultiSelectListSize(String multiSelectListSize) {
+ this.multiSelectListSize = multiSelectListSize;
+ }
+
+ public String getRangeStartDateSQL() {
+ return rangeStartDateSQL;
+ }
+
+ public void setRangeStartDateSQL(String rangeStartDateSQL) {
+ this.rangeStartDateSQL = rangeStartDateSQL;
+ }
+
+ public boolean isHasPredefinedList() {
+ return hasPredefinedList;
+ }
+
+ public void setHasPredefinedList(boolean hasPredefinedList) {
+ this.hasPredefinedList = hasPredefinedList;
+ }
+
+ public boolean isTriggerOtherFormFields() {
+ return triggerOtherFormFields;
+ }
+
+ public void setTriggerOtherFormFields(boolean triggerOtherFormFields) {
+ this.triggerOtherFormFields = triggerOtherFormFields;
+ }
+
+ public boolean isTriggerThisFormfield() {
+ return triggerThisFormfield;
+ }
+
+ public void setTriggerThisFormfield(boolean triggerThisFormfield) {
+ this.triggerThisFormfield = triggerThisFormfield;
+ }
+
+
+} // FormField
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+import org.onap.portalsdk.analytics.view.*;
+import org.onap.portalsdk.analytics.xmlobj.*;
+
+public class FormatProcessor extends RaptorObject {
+
+
+ private SemaphoreType semaphore = null;
+
+ private String colType = null;
+
+ private String dateFormat = null;
+
+ private HtmlFormatter defaultFormatter = null;
+
+ private HashMap formatters = null;
+
+ private HashMap convertedValues = null;
+
+ private boolean attemptNumericConversion = false;
+
+ public FormatProcessor(SemaphoreType sem, String colType, String dateFormat,
+ boolean attemptNumericConversion) {
+
+ super();
+
+ if (sem == null)
+ return;
+
+ this.semaphore = sem;
+ this.colType = colType;
+ this.dateFormat = dateFormat;
+
+ this.attemptNumericConversion = attemptNumericConversion;
+ if (attemptNumericConversion)
+ for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter
+ .hasNext();) {
+ FormatType fmt = (FormatType) iter.next();
+ if (!isNumber(fmt.getLessThanValue())) {
+ this.attemptNumericConversion = false;
+ break;
+ } // if
+ } // for
+
+ formatters = new HashMap(semaphore.getFormatList().getFormat().size() * 4 / 3);
+ convertedValues = new HashMap(semaphore.getFormatList().getFormat().size() * 4 / 3);
+
+ for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter.hasNext();) {
+ FormatType fmt = (FormatType) iter.next();
+ if ((fmt.getFormatId() == null) || (fmt.getFormatId().length() <= 0)) {
+ defaultFormatter = new HtmlFormatter(fmt.isBold(), fmt.isItalic(), fmt
+ .isUnderline(), fmt.getBgColor(), fmt.getFontColor(), fmt
+ .getFontFace(), fmt.getFontSize(), fmt.getAlignment());
+ } else {
+ formatters.put(fmt.getFormatId(), new HtmlFormatter(fmt.isBold(), fmt
+ .isItalic(), fmt.isUnderline(), fmt.getBgColor(), fmt.getFontColor(),
+ fmt.getFontFace(), fmt.getFontSize(), fmt.getAlignment()));
+ convertedValues.put(fmt.getFormatId(), convertValue(fmt.getLessThanValue()));
+ }
+ } // for
+ } // FormatProcessor
+
+ private String convertValue(String origValue) {
+
+ if (colType.equals(AppConstants.CT_DATE))
+ return convertDateValue(origValue);
+ else if (colType.equals(AppConstants.CT_NUMBER))
+ return convertNumericValue(origValue);
+ else if (attemptNumericConversion)
+ return convertUnknownValue(origValue);
+ else
+ return origValue;
+ } // convertValue
+
+ private String convertDateValue(String origValue) {
+
+ // Converts to YYYY-MM-DD if possible
+ if (nvl(dateFormat).length() == 0 || nvl(origValue).length() == 0)
+ return origValue;
+
+ if (dateFormat.equals("MM/DD/YYYY") && origValue.length() == 10)
+ // Special processing for the default date format - for saving DB
+ // calls
+ return origValue.substring(6, 10) + "-" + origValue.substring(0, 2) + "-"
+ + origValue.substring(3, 5);
+
+ try {
+ // DataSet ds = DbUtils.executeQuery("SELECT TO_CHAR(TO_DATE('" + origValue + "', '"
+ // + dateFormat + "'), 'YYYY-MM-DD') val FROM DUAL");
+
+ String sql = Globals.getGenerateSqlVisualDual();
+ DataSet ds = DbUtils.executeQuery("SELECT TO_CHAR(TO_DATE('" + origValue + "', '"
+ + dateFormat + "'), 'YYYY-MM-DD') val"+sql);
+
+ if (ds.getRowCount() > 0)
+ return ds.getString(0, 0);
+ } catch (Exception e) {
+ }
+
+ return origValue;
+ } // convertDateValue
+
+ private String convertNumericValue(String origValue) {
+
+ // Converts to [20 pos.5 pos] if possible
+ if (nvl(origValue).length() == 0)
+ return origValue;
+ boolean isNegative = false;
+
+ StringBuffer integerValue = new StringBuffer();
+ StringBuffer fractionValue = new StringBuffer();
+
+ boolean beforeDecimalPoint = true;
+ for (int i = 0; i < origValue.length(); i++) {
+ char c = origValue.charAt(i);
+ if (c == '.')
+ beforeDecimalPoint = false;
+ else if (c == '-' && integerValue.length() == 0)
+ isNegative = true;
+ // else
+ // if(c=='0'||c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9')
+ else if (Character.isDigit(c))
+ if (beforeDecimalPoint)
+ integerValue.append(c);
+ else
+ fractionValue.append(c);
+ } // for
+
+ while (integerValue.length() < 20)
+ integerValue.insert(0, '0');
+
+ while (fractionValue.length() < 5)
+ fractionValue.append('0');
+
+ integerValue.append('.');
+ integerValue.append(fractionValue);
+ integerValue.insert(0, (isNegative ? '-' : '+'));
+
+ return integerValue.toString();
+ } // convertNumericValue
+
+ private boolean isNumber(String value) { // As per Raptor def, like
+
+ // -$3,270.56
+ value = value.trim();
+ for (int i = 0; i < value.length(); i++) {
+ char c = value.charAt(i);
+ if (!(Character.isDigit(c) || c == '.' || c == '-' || c == '+' || c == ','
+ || c == '$' || c == '%'))
+ return false;
+ } // for
+
+ return true;
+ } // isNumber
+
+ private String convertUnknownValue(String origValue) {
+
+ return isNumber(origValue) ? convertNumericValue(origValue) : origValue;
+ } // convertUnknownValue
+
+ private boolean isEqual(String value1, String value2) {
+
+ return value1.trim().equals(value2.trim());
+ } // isEqual
+
+ private boolean isLessThan(String value1, String value2) {
+
+ boolean compareAsNumbers = colType.equals(AppConstants.CT_NUMBER);
+ if ((!compareAsNumbers) && attemptNumericConversion)
+ compareAsNumbers = isNumber(value1) && isNumber(value2);
+ if (compareAsNumbers && value1.length()>0 && value2.length()>0) {
+ boolean value1IsNegative = (value1.charAt(0) == '-');
+ boolean value2IsNegative = (value2.charAt(0) == '-');
+ if (value1IsNegative && (!value2IsNegative)) {
+ return true;
+ }
+ else if ((!value1IsNegative) && value2IsNegative) {
+ return false;
+ }
+ return Double.parseDouble(value1)<Double.parseDouble(value2);
+ } // if
+
+ return (value1.compareTo(value2) < 0);
+ } // isEqual
+
+ public void setHtmlFormatters(DataValue dv, DataRow dr, boolean formatModified) {
+
+ if (semaphore == null)
+ return;
+
+ HtmlFormatter formatter = defaultFormatter;
+ HtmlFormatter anyFormatter = null;
+ String sValue = convertValue(dv.getDisplayValue());
+
+ String compareColId = semaphore.getComment(); // When Column Id compare is different from formatting.
+
+ String targetColId = null;
+ if(semaphore.getTarget()!=null)
+ targetColId = semaphore.getTarget();
+
+ DataValue targetDataValue = null;
+ /* compare the column id which is in comment and assign to sValue */
+ if(nvl(compareColId).length()>0) {
+ for (dr.resetNext(); dr.hasNext();) {
+ DataValue dv1 = dr.getNext();
+ //add null check
+ if(dv1.getColId()!=null) {
+ if(dv1.getColId().equals(compareColId))
+ sValue = convertValue(dv1.getDisplayValue());
+ if(targetColId!=null) {
+ if(dv1.getColId().equals(targetColId))
+ targetDataValue = dv1;
+ }
+ }
+ }
+ }
+
+ for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter
+ .hasNext();) {
+ FormatType fmt = (FormatType) iter.next();
+ if(fmt.getLessThanValue().length() <= 0) {
+ anyFormatter = (HtmlFormatter) formatters.get(fmt.getFormatId());
+ anyFormatter.setFormatId(fmt.getFormatId());
+ break;
+ }
+ }
+
+ if( anyFormatter == null ) anyFormatter = formatter;
+ // String sValue = convertValue(dv.getDisplayValue());
+ //if (sValue.length() > 0) {
+ for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter
+ .hasNext();) {
+ FormatType fmt = (FormatType) iter.next();
+ // For Excel Download
+
+ if ((fmt.getFormatId() == null) || (fmt.getFormatId().length() <= 0)) {
+ // Default formatter
+ continue;
+ }
+
+ String formatterValue = nvl((String) convertedValues.get(fmt.getFormatId()));
+ boolean valueMatched = false;
+ if (fmt.getExpression().equals("=")) {
+ valueMatched = isEqual(sValue, formatterValue);
+ }
+
+ else if (fmt.getExpression().equals("<>"))
+ valueMatched = (!isEqual(sValue, formatterValue));
+ else if (fmt.getExpression().equals(">")) {
+ valueMatched = (!(isEqual(sValue, formatterValue) || isLessThan(sValue,
+ formatterValue)));
+ }
+ else if (fmt.getExpression().equals(">=")) {
+ valueMatched = /* isEqual(sValue, formatterValue)|| */(!isLessThan(
+ sValue, formatterValue));
+ }
+ else if (fmt.getExpression().equals("<")) {
+ valueMatched = isLessThan(sValue, formatterValue);
+ }
+ else if (fmt.getExpression().equals("<=")) {
+ valueMatched = isEqual(sValue, formatterValue)
+ || isLessThan(sValue, formatterValue);
+ }
+ //s_logger.debug("SYSOUT " + " " +sValue +" " +fmt.getBgColor() + " " + fmt.getLessThanValue()+ " " +valueMatched);
+ if (fmt.getLessThanValue().length() > 0 && valueMatched) {
+ formatter = (HtmlFormatter) formatters.get(fmt.getFormatId());
+ formatter.setFormatId(fmt.getFormatId());
+ formatModified = true;
+ //dv.setFormatId(fmt.getFormatId());
+ //dr.setFormatId(fmt.getFormatId());
+ //break;
+ } else { // if
+ if(!formatModified) formatter = anyFormatter;
+ //if(!((formatter!=null && formatter!=anyFormatter) || (defaultFormatter!=null && formatter!=defaultFormatter)))
+ // formatter = anyFormatter;
+ //formatter.setFormatId(anyFormatter.getFormatId());
+ }
+ /*else if ((fmt.getLessThanValue().length() <= 0)
+ && (fmt.getFormatId().length() > 0)) {
+ formatter = (HtmlFormatter) formatters.get(fmt.getFormatId());
+ System.out.println("---------------lesser "+ fmt.getFormatId()+ " " + fmt.getBgColor());
+ dv.setFormatId(fmt.getFormatId());
+ dr.setFormatId(fmt.getFormatId());
+ // break;
+ } // else if*/
+ } // for
+ /*} else {
+ for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter
+ .hasNext();) {
+ FormatType fmt = (FormatType) iter.next();
+ if(fmt.getLessThanValue().length()<=0 && fmt.getExpression().length()<=0 && !fmt.isBold() && !fmt.isItalic() && !fmt.isUnderline() && fmt.getFontSize().equals("11")) {
+ formatter = defaultFormatter;
+ } else
+ formatter = anyFormatter;
+ }
+
+ //formatter.setFormatId(anyFormatter.getFormatId());
+ } */
+ if(formatter != null) {
+ if (semaphore.getSemaphoreType().equals(AppConstants.ST_ROW)) {
+
+ if (dr.getRowFormatter() == null || formatter != defaultFormatter) {
+ // Making sure the default formatter doesn't overwrite
+ // valid row formatter set from another column
+ dr.setRowFormatter(formatter);
+ dr.setFormatId(formatter.getFormatId());
+ // This is added for excel download
+ //if (!formatter.equals(defaultFormatter)) {
+ dr.setRowFormat(true);
+ //}
+
+ }
+ } else {
+ if(nvl(targetColId).length()>0) {
+ if(targetDataValue!=null) {
+ targetDataValue.setCellFormatter(formatter);
+ targetDataValue.setFormatId(formatter.getFormatId());
+ //if (!formatter.equals(defaultFormatter)) {
+ targetDataValue.setCellFormat(true);
+ int count = 0;
+ for (dr.resetNext(); dr.hasNext();) {
+ DataValue dv1 = dr.getNext();
+ //add null check
+ if(targetColId!=null) {
+ if(dv1.getColId().equals(targetColId))
+ dr.setDataValue(count, targetDataValue);
+ }
+ count++;
+ }
+ }
+ //}
+
+ } else {
+ dv.setCellFormatter(formatter);
+ dv.setFormatId(formatter.getFormatId());
+ //if (!formatter.equals(defaultFormatter)) {
+ dv.setCellFormat(true);
+ //}
+ }
+ }// else
+ }
+ } // setHtmlFormatters
+
+} // FormatProcessor
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+public class Item {
+ private String _id;
+ private String _name;
+
+ public Item() {
+ }
+
+ public Item(String id, String name) {
+ this._id = id;
+ this._name = 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;
+ }
+
+ public String toString() {
+ return _name;
+ }
+}
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+import org.onap.portalsdk.analytics.RaptorObject;
+
+public class LookupDBInfo extends RaptorObject {
+ private String tableName = null;
+
+ private String fieldName = null;
+
+ private String lookupTable = null;
+
+ private String lookupIdField = null;
+
+ private String lookupNameField = null;
+
+ public LookupDBInfo() {
+ }
+
+ public LookupDBInfo(String tableName, String fieldName, String lookupTable,
+ String lookupIdField, String lookupNameField) {
+ this();
+
+ setTableName(tableName);
+ setFieldName(fieldName);
+ setLookupTable(lookupTable);
+ setLookupIdField(lookupIdField);
+ setLookupNameField(lookupNameField);
+ } // LookupDBInfo
+
+ public String getTableName() {
+ return tableName;
+ }
+
+ public String getFieldName() {
+ return fieldName;
+ }
+
+ public String getLookupTable() {
+ return lookupTable;
+ }
+
+ public String getLookupIdField() {
+ return lookupIdField;
+ }
+
+ public String getLookupNameField() {
+ return lookupNameField;
+ }
+
+ public void setTableName(String tableName) {
+ this.tableName = tableName;
+ }
+
+ public void setFieldName(String fieldName) {
+ this.fieldName = fieldName;
+ }
+
+ public void setLookupTable(String lookupTable) {
+ this.lookupTable = lookupTable;
+ }
+
+ public void setLookupIdField(String lookupIdField) {
+ this.lookupIdField = lookupIdField;
+ }
+
+ public void setLookupNameField(String lookupNameField) {
+ this.lookupNameField = lookupNameField;
+ }
+
+} // LookupDBInfo
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+class RangeColorJSON extends IndexValueJSON {}
+class RangeAxisLabelJSON extends IndexValueJSON {}
+class RangeLineTypeJSON extends IndexValueJSON {}
+
+public class RangeAxisJSON {
+
+ private RangeAxisLabelJSON rangeAxisLabelJSON;
+ private RangeColorJSON rangeColorJSON;
+ private RangeLineTypeJSON rangeLineTypeJSON;
+ private String rangeChartGroup;
+ private String rangeYAxis;
+ private boolean showAsArea;
+
+ public RangeAxisLabelJSON getRangeAxisLabelJSON() {
+ return rangeAxisLabelJSON;
+ }
+ public void setRangeAxisLabelJSON(RangeAxisLabelJSON rangeAxisLabelJSON) {
+ this.rangeAxisLabelJSON = rangeAxisLabelJSON;
+ }
+ public RangeColorJSON getRangeColorJSON() {
+ return rangeColorJSON;
+ }
+ public void setRangeColorJSON(RangeColorJSON rangeColorJSON) {
+ this.rangeColorJSON = rangeColorJSON;
+ }
+ public RangeLineTypeJSON getRangeLineTypeJSON() {
+ return rangeLineTypeJSON;
+ }
+ public void setRangeLineTypeJSON(RangeLineTypeJSON rangeLineTypeJSON) {
+ this.rangeLineTypeJSON = rangeLineTypeJSON;
+ }
+ public String getRangeChartGroup() {
+ return rangeChartGroup;
+ }
+ public void setRangeChartGroup(String rangeChartGroup) {
+ this.rangeChartGroup = rangeChartGroup;
+ }
+ public String getRangeYAxis() {
+ return rangeYAxis;
+ }
+ public void setRangeYAxis(String rangeYAxis) {
+ this.rangeYAxis = rangeYAxis;
+ }
+ public boolean isShowAsArea() {
+ return showAsArea;
+ }
+ public void setShowAsArea(boolean showAsArea) {
+ this.showAsArea = showAsArea;
+ }
+
+ public String getRangeAxis() {
+ if(getRangeAxisLabelJSON()!=null)
+ return getRangeAxisLabelJSON().getValue();
+ else
+ return "";
+ }
+
+ public String getRangeColor(){
+ if(getRangeColorJSON()!=null)
+ return getRangeColorJSON().getValue();
+ else
+ return "";
+ }
+
+ public String getRangeLineType(){
+ if(getRangeLineTypeJSON()!=null)
+ return getRangeLineTypeJSON().getValue();
+ else
+ return "";
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+import java.util.*;
+import javax.servlet.http.*;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.model.*;
+import org.onap.portalsdk.analytics.model.base.*;
+import org.onap.portalsdk.analytics.model.definition.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+import org.onap.portalsdk.analytics.xmlobj.*;
+
+public class ReportFormFields extends Vector {
+ private int nextElemIdx = 0;
+
+ public ReportFormFields(ReportWrapper rw, HttpServletRequest request) throws RaptorException {
+ super();
+
+ if (rw.getFormFieldList() != null)
+ for (Iterator iter = rw.getFormFieldList().getFormField().iterator(); iter
+ .hasNext();) {
+ FormFieldType fft = (FormFieldType) iter.next();
+
+ String fieldName = fft.getFieldId();
+ String fieldDisplayName = fft.getFieldName();
+ String fieldType = fft.getFieldType();
+ String validationType = fft.getValidationType();
+ String mandatory = nvl(fft.getMandatory(), "N");
+ String defaultValue = fft.getDefaultValue();
+ String fieldSQL = fft.getFieldSQL();
+ String fieldDefaultSQL = fft.getFieldDefaultSQL();
+ String[] reqParameters = Globals.getRequestParams().split(",");
+ String[] sessionParameters = Globals.getSessionParams().split(",");
+ String[] scheduleSessionParameters = Globals.getSessionParamsForScheduling().split(",");
+ javax.servlet.http.HttpSession session = request.getSession();
+ String visible = nvl(fft.getVisible(),"Y");
+ String dependsOn = nvl(fft.getDependsOn(), "");
+ Calendar rangeStartDate = (fft.getRangeStartDate()==null)?null:fft.getRangeStartDate().toGregorianCalendar();
+ Calendar rangeEndDate = (fft.getRangeEndDate()==null)?null:fft.getRangeEndDate().toGregorianCalendar();
+ //Calendar rangeEndDate = fft.getRangeEndDate().toGregorianCalendar();
+ String rangeStartDateSQL = fft.getRangeStartDateSQL();
+ String rangeEndDateSQL = fft.getRangeEndDateSQL();
+ String user_id = AppUtils.getUserID(request);
+ String multiSelectListSize = fft.getMultiSelectListSize();
+
+ //s_logger.debug("ranges are : " + fft.getRangeStartDate() + fft.getRangeEndDate());
+ //s_logger.debug("fieldSQL B4" + fieldSQL);
+ if(fieldSQL!=null) {
+ for (int i = 0; i < reqParameters.length; i++) {
+ if(!reqParameters[i].startsWith("ff") && (request.getParameter(reqParameters[i].toUpperCase())!=null && request.getParameter(reqParameters[i].toUpperCase()).length() > 0))
+ fieldSQL = Utils.replaceInString(fieldSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
+ else if (request.getParameter(reqParameters[i])!=null && request.getParameter(reqParameters[i]).length() > 0)
+ fieldSQL = Utils.replaceInString(fieldSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
+ }
+
+ for (int i = 0; i < scheduleSessionParameters.length; i++) {
+ //s_logger.debug(" Session " + " scheduleSessionParameters[i] " + scheduleSessionParameters[i].toUpperCase() + " " + request.getParameter(scheduleSessionParameters[i]));
+ if(request.getParameter(scheduleSessionParameters[i])!=null && request.getParameter(scheduleSessionParameters[i]).trim().length()>0 )
+ fieldSQL = Utils.replaceInString(fieldSQL, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) );
+ if(request.getAttribute(scheduleSessionParameters[i])!=null && ((String)request.getAttribute(scheduleSessionParameters[i])).trim().length()>0 )
+ fieldSQL = Utils.replaceInString(fieldSQL, "[" + scheduleSessionParameters[i].toUpperCase()+"]", (String) request.getAttribute(scheduleSessionParameters[i]) );
+
+ }
+
+ for (int i = 0; i < sessionParameters.length; i++) {
+ //if(!sessionParameters[i].startsWith("ff"))
+ //fieldSQL = Utils.replaceInString(fieldSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) );
+ //else {
+ if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0) {
+ //s_logger.debug(" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i]));
+ fieldSQL = Utils.replaceInString(fieldSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
+ }
+ // }
+ }
+ fieldSQL = Utils.replaceInString(fieldSQL, "[USERID]", user_id);
+ fieldSQL = Utils.replaceInString(fieldSQL, "[USER_ID]", user_id);
+ fieldSQL = Utils.replaceInString(fieldSQL, "[LOGGED_USERID]", user_id);
+
+ }
+
+ if(fieldDefaultSQL!=null) {
+ for (int i = 0; i < reqParameters.length; i++) {
+ if(!reqParameters[i].startsWith("ff") && (request.getParameter(reqParameters[i].toUpperCase())!=null && request.getParameter(reqParameters[i].toUpperCase()).length() > 0))
+ fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
+ else if (request.getParameter(reqParameters[i])!=null && request.getParameter(reqParameters[i]).length() > 0)
+ fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
+ }
+ for (int i = 0; i < scheduleSessionParameters.length; i++) {
+ //s_logger.debug(" Session " + " scheduleSessionParameters[i] " + scheduleSessionParameters[i].toUpperCase() + " " + request.getParameter(scheduleSessionParameters[i]));
+ if(request.getParameter(scheduleSessionParameters[i])!=null && request.getParameter(scheduleSessionParameters[i]).trim().length()>0 )
+ fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) );
+ if(request.getAttribute(scheduleSessionParameters[i])!=null && ((String)request.getAttribute(scheduleSessionParameters[i])).trim().length()>0 )
+ fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + scheduleSessionParameters[i].toUpperCase()+"]", (String) request.getAttribute(scheduleSessionParameters[i]) );
+
+ }
+
+ for (int i = 0; i < sessionParameters.length; i++) {
+ //if(!sessionParameters[i].startsWith("ff"))
+ //fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) );
+ //else
+ if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0)
+ fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
+ }
+
+ fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[USERID]", user_id);
+ fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[USER_ID]", user_id);
+ fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[LOGGED_USERID]", user_id);
+ }
+ //s_logger.debug("fieldSQL After" + fieldSQL);
+ if(rangeStartDateSQL!=null) {
+ for (int i = 0; i < reqParameters.length; i++) {
+ if(!reqParameters[i].startsWith("ff") && (request.getParameter(reqParameters[i].toUpperCase())!=null && request.getParameter(reqParameters[i].toUpperCase()).length() > 0))
+ rangeStartDateSQL = Utils.replaceInString(rangeStartDateSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
+ else if (request.getParameter(reqParameters[i])!=null && request.getParameter(reqParameters[i]).length() > 0)
+ rangeStartDateSQL = Utils.replaceInString(rangeStartDateSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
+ }
+ for (int i = 0; i < sessionParameters.length; i++) {
+ if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0)
+ rangeStartDateSQL = Utils.replaceInString(rangeStartDateSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
+ }
+ }
+ if(rangeEndDateSQL!=null) {
+ for (int i = 0; i < reqParameters.length; i++) {
+ if(!reqParameters[i].startsWith("ff")&& (request.getParameter(reqParameters[i].toUpperCase())!=null && request.getParameter(reqParameters[i].toUpperCase()).length() > 0))
+ rangeEndDateSQL = Utils.replaceInString(rangeEndDateSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
+ else if (request.getParameter(reqParameters[i])!=null && request.getParameter(reqParameters[i]).length() > 0)
+ rangeEndDateSQL = Utils.replaceInString(rangeEndDateSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
+ }
+ for (int i = 0; i < sessionParameters.length; i++) {
+ if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0)
+ rangeEndDateSQL = Utils.replaceInString(rangeEndDateSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
+ }
+ }
+ String helpText = fft.getComment();
+
+ List predefinedValues = null;
+ if (fft.getPredefinedValueList() != null) {
+ predefinedValues = fft.getPredefinedValueList().getPredefinedValue();
+ if (predefinedValues.size() == 0)
+ predefinedValues = null;
+ } // if
+
+ DataColumnType dct = rw.getColumnById(nvl(fft.getColId()));
+
+ boolean basedOnColumn = false;
+ if (rw.getReportDefType().equals(AppConstants.RD_SQL_BASED))
+ basedOnColumn = (nvl(fft.getColId()).indexOf('.') > 0);
+ else
+ basedOnColumn = (dct != null);
+
+ if (((!basedOnColumn) && (nvl(fieldSQL).length() == 0))
+ || predefinedValues != null) {
+ if (predefinedValues != null)
+ if (nvl(defaultValue).equals(AppConstants.FILTER_MAX_VALUE))
+ defaultValue = (String) Collections.max(predefinedValues);
+ else if (nvl(defaultValue).equals(AppConstants.FILTER_MIN_VALUE))
+ defaultValue = (String) Collections.min(predefinedValues);
+ add(new FormField(fieldName, fieldDisplayName, fieldType, validationType,
+ mandatory.equals("Y"), defaultValue, helpText, predefinedValues,visible.equals("Y"), dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize));
+ } else if (nvl(fieldSQL).length() > 0) {
+ add(new FormField(fieldName, fieldDisplayName, fieldType, validationType,
+ mandatory.equals("Y"), fieldDefaultSQL, helpText, fieldSQL,visible.equals("Y"), dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize));
+ } else {
+ String lTableName = null;
+ String lColumnName = null;
+ String lColumnType = null;
+ String lColFormat = null;
+ if (rw.getReportDefType().equals(AppConstants.RD_SQL_BASED)) {
+ String colId = nvl(fft.getColId());
+ lTableName = ReportWrapper.getSQLBasedFFTColTableName(colId); // colId.substring(0,
+ // colId.indexOf('.'));
+ lColumnName = ReportWrapper.getSQLBasedFFTColColumnName(colId); // colId.substring(colId.lastIndexOf('.')+1);
+ lColumnType = AppConstants.CT_CHAR;
+ try {
+ lColumnType = nvl(DataCache.getReportTableDbColumnType(lTableName,
+ lColumnName, rw.getDBInfo()), AppConstants.CT_CHAR);
+ } catch (Exception e) {
+ }
+ lColFormat = lColumnType.equals(AppConstants.CT_DATE) ? nvl(
+ ReportWrapper.getSQLBasedFFTColDisplayFormat(colId),
+ AppConstants.DEFAULT_DATE_FORMAT) : "";
+ } else {
+ lTableName = rw.getColumnTableById(dct.getColId()).getTableName(); // should
+ // be
+ // same
+ // as
+ // rw.getTableById(dct.getTableId()).getTableName()
+ lColumnName = dct.getColName();
+ lColumnType = dct.getColType();
+ lColFormat = nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT);
+ } // else
+
+ if (nvl(defaultValue).equals(AppConstants.FILTER_MAX_VALUE)
+ || nvl(defaultValue).equals(AppConstants.FILTER_MIN_VALUE))
+ try {
+ String selectVal = (defaultValue
+ .equals(AppConstants.FILTER_MAX_VALUE) ? "MAX" : "MIN")
+ + "(" + lColumnName + ")";
+ if (lColumnType.equals(AppConstants.CT_DATE))
+ selectVal = "TO_CHAR(" + selectVal + ", '"
+ + AppConstants.DEFAULT_DATE_FORMAT + "')";
+ // DataSet ds = DbUtils.executeQuery("SELECT
+ // "+selectVal+" FROM "+lTableName);
+ DataSet ds = ConnectionUtils.getDataSet("SELECT " + selectVal
+ + " FROM " + lTableName, rw.getDBInfo());
+ if (ds.getRowCount() > 0)
+ defaultValue = ds.getString(0, 0);
+ } catch (Exception e) {
+ }
+
+ LookupDBInfo lookupDBInfo = DataCache.getLookupTable(lTableName,
+ lColumnName);
+ String lookupTable = lookupDBInfo.getLookupTable();
+ String lookupIdField = lookupDBInfo.getLookupIdField();
+ String lookupNameField = lookupDBInfo.getLookupNameField();
+ String lookupSortByField = lookupDBInfo.getLookupNameField();
+ if (lColumnType.equals(AppConstants.CT_DATE)) {
+ // Expects lookup on DATE fields will have both Id and
+ // Name fields with DATE format; if not the case will
+ // generate an error
+ lookupIdField = "TO_CHAR(" + lookupIdField + ", '"
+ + AppConstants.DEFAULT_DATE_FORMAT + "')";
+ lookupSortByField = " TO_DATE(TO_CHAR("+ lookupNameField +", '" + AppConstants.DEFAULT_DATE_FORMAT+ "'),'" + AppConstants.DEFAULT_DATE_FORMAT+ "') ";
+ lookupNameField = "TO_CHAR(" + lookupNameField + ", '" + lColFormat
+ + "')";
+ lookupSortByField += " DESC";
+ } // if
+ if (fieldDefaultSQL!=null && fieldDefaultSQL.length()>0 && (fieldDefaultSQL.trim().length()>10) && fieldDefaultSQL.substring(0,10).toLowerCase().startsWith("select")) {
+ add(new FormField(fieldName, fieldDisplayName, fieldType, validationType,
+ mandatory.equals("Y"), fieldDefaultSQL, helpText, lookupTable,
+ lookupIdField, lookupNameField, lookupSortByField,visible.equals("Y"),dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize));
+
+ } else {
+ add(new FormField(fieldName, fieldDisplayName, fieldType, validationType,
+ mandatory.equals("Y"), defaultValue, helpText, lookupTable,
+ lookupIdField, lookupNameField, lookupSortByField,visible.equals("Y"), dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize));
+ }
+ } // else
+ } // for
+
+ List reportCols = rw.getAllColumns();
+ for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
+ DataColumnType dct = (DataColumnType) iter.next();
+
+ if (dct.getColFilterList() != null) {
+ int fNo = 0;
+ List fList = dct.getColFilterList().getColFilter();
+ for (Iterator iterF = fList.iterator(); iterF.hasNext(); fNo++) {
+ ColFilterType cft = (ColFilterType) iterF.next();
+
+ if (nvl(cft.getArgType()).equals(AppConstants.AT_FORM)
+ && rw.getFormFieldByDisplayValue(cft.getArgValue()) == null) {
+ String fieldName = rw.getFormFieldName(cft);
+ String fieldDisplayName = rw.getFormFieldDisplayName(dct, cft);
+
+ LookupDBInfo lookupDBInfo = DataCache.getLookupTable(rw
+ .getColumnTableById(dct.getColId()).getTableName(), dct
+ .getColName());
+ String lookupTable = lookupDBInfo.getLookupTable();
+ String lookupIdField = lookupDBInfo.getLookupIdField();
+ String lookupNameField = lookupDBInfo.getLookupNameField();
+ String lookupSortByField = lookupDBInfo.getLookupNameField();
+ Calendar lookupRangeStartDate = rw.getFormFieldRangeStart(cft);
+ Calendar lookupRangeEndDate = rw.getFormFieldRangeEnd(cft);
+ String lookupRangeStartDateSQL = rw.getFormFieldRangeStartSQL(cft);
+ String lookupRangeEndDateSQL = rw.getFormFieldRangeEndSQL(cft);
+ if (dct.getColType().equals(AppConstants.CT_DATE)) {
+ // Expects lookup on DATE fields will have both Id
+ // and Name fields with DATE format; if not the case
+ // will generate an error
+ lookupIdField = "TO_CHAR("
+ + lookupIdField
+ + ", '"
+ + nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT)
+ + "')";
+ lookupNameField = "TO_CHAR("
+ + lookupNameField
+ + ", '"
+ + nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT)
+ + "')";
+ lookupSortByField += " DESC";
+ } // if
+ add(new FormField(fieldName, fieldDisplayName,
+ FormField.FFT_TEXT_W_POPUP, null, false, null, null,
+ lookupTable, lookupIdField, lookupNameField, lookupSortByField,null, lookupRangeStartDate, lookupRangeEndDate, lookupRangeStartDateSQL, lookupRangeEndDateSQL, "0"));
+ } // if
+ } // for
+ } // if
+ } // for
+ } // ReportFormFields
+
+ public int getFieldCount() {
+ return size();
+ } // getFieldCount
+
+ public FormField getFormField(int fieldIdx) {
+ return (FormField) get(fieldIdx);
+ } // getFormField
+
+ public FormField getFormField(String fieldName) {
+ for (int i = 0; i < getFieldCount(); i++) {
+ FormField ff = (FormField) get(i);
+ if (ff.getFieldName().equals(fieldName))
+ return ff;
+ } // for
+
+ return null;
+ } // getFormField
+
+ public void resetNext() {
+ resetNext(0);
+ } // resetNext
+
+ public void resetNext(int toPos) {
+ nextElemIdx = toPos;
+ } // resetNext
+
+ public boolean hasNext() {
+ return (nextElemIdx < size());
+ } // hasNext
+
+ public FormField getNext() {
+ return hasNext() ? getFormField(nextElemIdx++) : null;
+ } // getNext
+
+ /** ************************************************************************************************* */
+
+ private String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ private String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+} // ReportFormFields
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.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.onap.portalsdk.analytics.model.base.IdNameValue;
+import org.onap.portalsdk.analytics.view.ColumnHeader;
+import org.onap.portalsdk.analytics.view.DataValue;
+import org.onap.portalsdk.analytics.xmlobj.ColFilterList;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnList;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
+
+/*class MetaColumn {
+ private String tableId;
+ private String dbColName;
+ private String crossTabValue;
+ private String colName;
+ private String displayName;
+ private Integer displayWidth;
+ private String displayWidthInPxls;
+ private String pdfDisplayWidthInPxls;
+ private String displayAlignment;
+ private String displayHeaderAlignment;
+ private int orderSeq;
+ private boolean visible;
+ private boolean calculated;
+ private String colType;
+ private String hyperlinkURL;
+ private String hyperlinkType;
+ private String actionImg;
+ private Integer groupByPos;
+ private String subTotalCustomText;
+ private Boolean hideRepeatedKey;
+ private String colFormat;
+ private boolean groupBreak;
+ private Integer orderBySeq;
+ private String orderByAscDesc;
+ private String displayTotal;
+ private String colOnChart;
+ private Integer chartSeq;
+ private String chartColor;
+ private String chartLineType;
+ private Boolean chartSeries;
+ private Boolean isRangeAxisFilled;
+ private Boolean createInNewChart;
+ private String drillDownType;
+ private Boolean drillinPoPUp;
+ private String drillDownURL;
+ private String drillDownParams;
+ private String comment;
+ private ColFilterList colFilterList;
+ private String semaphoreId;
+ private String dbColType;
+ private String chartGroup;
+ private String yAxis;
+ private String dependsOnFormField;
+ private String nowrap;
+ private Integer indentation;
+ private Boolean enhancedPagination;
+ private Integer level;
+ private Integer start;
+ private Integer colspan;
+ private String dataMiningCol;
+ private String colId;
+
+ public String getTableId() {
+ return tableId;
+ }
+ public void setTableId(String tableId) {
+ this.tableId = tableId;
+ }
+ public String getDbColName() {
+ return dbColName;
+ }
+ public void setDbColName(String dbColName) {
+ this.dbColName = dbColName;
+ }
+ public String getCrossTabValue() {
+ return crossTabValue;
+ }
+ public void setCrossTabValue(String crossTabValue) {
+ this.crossTabValue = crossTabValue;
+ }
+ public String getColName() {
+ return colName;
+ }
+ public void setColName(String colName) {
+ this.colName = colName;
+ }
+ public String getDisplayName() {
+ return displayName;
+ }
+ public void setDisplayName(String displayName) {
+ this.displayName = displayName;
+ }
+ public Integer getDisplayWidth() {
+ return displayWidth;
+ }
+ public void setDisplayWidth(Integer displayWidth) {
+ this.displayWidth = displayWidth;
+ }
+ public String getDisplayWidthInPxls() {
+ return displayWidthInPxls;
+ }
+ public void setDisplayWidthInPxls(String displayWidthInPxls) {
+ this.displayWidthInPxls = displayWidthInPxls;
+ }
+ public String getPdfDisplayWidthInPxls() {
+ return pdfDisplayWidthInPxls;
+ }
+ public void setPdfDisplayWidthInPxls(String pdfDisplayWidthInPxls) {
+ this.pdfDisplayWidthInPxls = pdfDisplayWidthInPxls;
+ }
+ 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 int getOrderSeq() {
+ return orderSeq;
+ }
+ public void setOrderSeq(int orderSeq) {
+ this.orderSeq = orderSeq;
+ }
+ public boolean isVisible() {
+ return visible;
+ }
+ public void setVisible(boolean visible) {
+ this.visible = visible;
+ }
+ public boolean isCalculated() {
+ return calculated;
+ }
+ public void setCalculated(boolean calculated) {
+ this.calculated = calculated;
+ }
+ public String getColType() {
+ return colType;
+ }
+ public void setColType(String colType) {
+ this.colType = colType;
+ }
+ public String getHyperlinkURL() {
+ return hyperlinkURL;
+ }
+ public void setHyperlinkURL(String hyperlinkURL) {
+ this.hyperlinkURL = hyperlinkURL;
+ }
+ public String getHyperlinkType() {
+ return hyperlinkType;
+ }
+ public void setHyperlinkType(String hyperlinkType) {
+ this.hyperlinkType = hyperlinkType;
+ }
+ public String getActionImg() {
+ return actionImg;
+ }
+ public void setActionImg(String actionImg) {
+ this.actionImg = actionImg;
+ }
+ public Integer getGroupByPos() {
+ return groupByPos;
+ }
+ public void setGroupByPos(Integer groupByPos) {
+ this.groupByPos = groupByPos;
+ }
+ public String getSubTotalCustomText() {
+ return subTotalCustomText;
+ }
+ public void setSubTotalCustomText(String subTotalCustomText) {
+ this.subTotalCustomText = subTotalCustomText;
+ }
+ public Boolean getHideRepeatedKey() {
+ return hideRepeatedKey;
+ }
+ public void setHideRepeatedKey(Boolean hideRepeatedKey) {
+ this.hideRepeatedKey = hideRepeatedKey;
+ }
+ public String getColFormat() {
+ return colFormat;
+ }
+ public void setColFormat(String colFormat) {
+ this.colFormat = colFormat;
+ }
+ public boolean isGroupBreak() {
+ return groupBreak;
+ }
+ public void setGroupBreak(boolean groupBreak) {
+ this.groupBreak = groupBreak;
+ }
+ public Integer getOrderBySeq() {
+ return orderBySeq;
+ }
+ public void setOrderBySeq(Integer orderBySeq) {
+ this.orderBySeq = orderBySeq;
+ }
+ public String getOrderByAscDesc() {
+ return orderByAscDesc;
+ }
+ public void setOrderByAscDesc(String orderByAscDesc) {
+ this.orderByAscDesc = orderByAscDesc;
+ }
+ public String getDisplayTotal() {
+ return displayTotal;
+ }
+ public void setDisplayTotal(String displayTotal) {
+ this.displayTotal = displayTotal;
+ }
+ public String getColOnChart() {
+ return colOnChart;
+ }
+ public void setColOnChart(String colOnChart) {
+ this.colOnChart = colOnChart;
+ }
+ public Integer getChartSeq() {
+ return chartSeq;
+ }
+ public void setChartSeq(Integer chartSeq) {
+ this.chartSeq = chartSeq;
+ }
+ public String getChartColor() {
+ return chartColor;
+ }
+ public void setChartColor(String chartColor) {
+ this.chartColor = chartColor;
+ }
+ public String getChartLineType() {
+ return chartLineType;
+ }
+ public void setChartLineType(String chartLineType) {
+ this.chartLineType = chartLineType;
+ }
+ public Boolean getChartSeries() {
+ return chartSeries;
+ }
+ public void setChartSeries(Boolean chartSeries) {
+ this.chartSeries = chartSeries;
+ }
+ public Boolean getIsRangeAxisFilled() {
+ return isRangeAxisFilled;
+ }
+ public void setIsRangeAxisFilled(Boolean isRangeAxisFilled) {
+ this.isRangeAxisFilled = isRangeAxisFilled;
+ }
+ public Boolean getCreateInNewChart() {
+ return createInNewChart;
+ }
+ public void setCreateInNewChart(Boolean createInNewChart) {
+ this.createInNewChart = createInNewChart;
+ }
+ public String getDrillDownType() {
+ return drillDownType;
+ }
+ public void setDrillDownType(String drillDownType) {
+ this.drillDownType = drillDownType;
+ }
+ public Boolean getDrillinPoPUp() {
+ return drillinPoPUp;
+ }
+ public void setDrillinPoPUp(Boolean drillinPoPUp) {
+ this.drillinPoPUp = drillinPoPUp;
+ }
+ 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 getComment() {
+ return comment;
+ }
+ public void setComment(String comment) {
+ this.comment = comment;
+ }
+ public ColFilterList getColFilterList() {
+ return colFilterList;
+ }
+ public void setColFilterList(ColFilterList colFilterList) {
+ this.colFilterList = colFilterList;
+ }
+ public String getSemaphoreId() {
+ return semaphoreId;
+ }
+ public void setSemaphoreId(String semaphoreId) {
+ this.semaphoreId = semaphoreId;
+ }
+ public String getDbColType() {
+ return dbColType;
+ }
+ public void setDbColType(String dbColType) {
+ this.dbColType = dbColType;
+ }
+ public String getChartGroup() {
+ return chartGroup;
+ }
+ public void setChartGroup(String chartGroup) {
+ this.chartGroup = chartGroup;
+ }
+ public String getyAxis() {
+ return yAxis;
+ }
+ public void setyAxis(String yAxis) {
+ this.yAxis = yAxis;
+ }
+ public String getDependsOnFormField() {
+ return dependsOnFormField;
+ }
+ public void setDependsOnFormField(String dependsOnFormField) {
+ this.dependsOnFormField = dependsOnFormField;
+ }
+ public String getNowrap() {
+ return nowrap;
+ }
+ public void setNowrap(String nowrap) {
+ this.nowrap = nowrap;
+ }
+ public Integer getIndentation() {
+ return indentation;
+ }
+ public void setIndentation(Integer indentation) {
+ this.indentation = indentation;
+ }
+ public Boolean getEnhancedPagination() {
+ return enhancedPagination;
+ }
+ public void setEnhancedPagination(Boolean enhancedPagination) {
+ this.enhancedPagination = enhancedPagination;
+ }
+ public Integer getLevel() {
+ return level;
+ }
+ public void setLevel(Integer level) {
+ this.level = level;
+ }
+ public Integer getStart() {
+ return start;
+ }
+ public void setStart(Integer start) {
+ this.start = start;
+ }
+ public Integer getColspan() {
+ return colspan;
+ }
+ public void setColspan(Integer colspan) {
+ this.colspan = colspan;
+ }
+ public String getDataMiningCol() {
+ return dataMiningCol;
+ }
+ public void setDataMiningCol(String dataMiningCol) {
+ this.dataMiningCol = dataMiningCol;
+ }
+ public String getColId() {
+ return colId;
+ }
+ public void setColId(String colId) {
+ this.colId = colId;
+ }
+
+}*/
+
+/*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 FormFieldJSON {
+ private String fieldId;
+ private String fieldDisplayName;
+ private String fieldType;
+ private String validationType;
+ private boolean required;
+ //private String defaultValue;
+
+ private Calendar rangeStartDate;
+ private Calendar rangeEndDate;
+ private String multiSelectListSize;
+ private String helpText;
+ private boolean visible;
+ private boolean triggerOtherFormFields;
+ private ArrayList<IdNameValue> formFieldValues;
+
+ public String getFieldId() {
+ return fieldId;
+ }
+ public void setFieldId(String fieldId) {
+ this.fieldId = fieldId;
+ }
+ public String getFieldDisplayName() {
+ return fieldDisplayName;
+ }
+ public void setFieldDisplayName(String fieldDisplayName) {
+ this.fieldDisplayName = fieldDisplayName;
+ }
+ public String getFieldType() {
+ return fieldType;
+ }
+ public void setFieldType(String fieldType) {
+ this.fieldType = fieldType;
+ }
+ public String getValidationType() {
+ return validationType;
+ }
+ public void setValidationType(String validationType) {
+ this.validationType = validationType;
+ }
+ public boolean isRequired() {
+ return required;
+ }
+ public void setRequired(boolean required) {
+ this.required = required;
+ }
+ public Calendar getRangeStartDate() {
+ return rangeStartDate;
+ }
+ public void setRangeStartDate(Calendar rangeStartDate) {
+ this.rangeStartDate = rangeStartDate;
+ }
+ public Calendar getRangeEndDate() {
+ return rangeEndDate;
+ }
+ public void setRangeEndDate(Calendar rangeEndDate) {
+ this.rangeEndDate = rangeEndDate;
+ }
+ public String getMultiSelectListSize() {
+ return multiSelectListSize;
+ }
+ public void setMultiSelectListSize(String multiSelectListSize) {
+ this.multiSelectListSize = multiSelectListSize;
+ }
+ public String getHelpText() {
+ return helpText;
+ }
+ public void setHelpText(String helpText) {
+ this.helpText = helpText;
+ }
+ public boolean isVisible() {
+ return visible;
+ }
+ public void setVisible(boolean visible) {
+ this.visible = visible;
+ }
+ public boolean isTriggerOtherFormFields() {
+ return triggerOtherFormFields;
+ }
+ public void setTriggerOtherFormFields(boolean triggerOtherFormFields) {
+ this.triggerOtherFormFields = triggerOtherFormFields;
+ }
+ public ArrayList<IdNameValue> getFormFieldValues() {
+ return formFieldValues;
+ }
+ public void setFormFieldValues(ArrayList<IdNameValue> formFieldValues) {
+ this.formFieldValues = formFieldValues;
+ }
+
+
+}
+public class ReportJSONRuntime {
+
+ private String reportID;
+ private String reportName;
+ private String reportDescr;
+ private String reportTitle;
+ private String reportSubTitle;
+ private boolean allowSchedule;
+ private boolean allowEdit;
+ private ArrayList <FormFieldJSON> formFieldList;
+ private String formfield_comments;
+ private ArrayList<ColumnHeader> reportDataColumns;
+ private ArrayList<Map<String,Object>> reportDataRows;
+ private int totalRows;
+ private int pageSize;
+ private String sqlWhole;
+ private boolean chartAvailable;
+ private boolean chartWizardAvailable;
+ private boolean displayData;
+ private boolean displayForm;
+ private boolean displayExcel;
+ private boolean displayPDF;
+ private String backBtnURL;
+ private String colIdxTobeFreezed;
+ private int numFormCols;
+ private String message;
+ private boolean hideFormFieldsAfterRun;
+
+
+ public boolean isChartAvailable() {
+ return chartAvailable;
+ }
+ public void setChartAvailable(boolean chartAvailable) {
+ this.chartAvailable = chartAvailable;
+ }
+ public ArrayList<Map<String,Object>> getReportDataRows() {
+ return reportDataRows;
+ }
+ public void setReportDataRows(ArrayList<Map<String,Object>> reportDataRows) {
+ this.reportDataRows = reportDataRows;
+ }
+ 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 boolean isAllowSchedule() {
+ return allowSchedule;
+ }
+ public void setAllowSchedule(boolean allowSchedule) {
+ this.allowSchedule = allowSchedule;
+ }
+ 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 ArrayList<ColumnHeader> getReportDataColumns() {
+ return reportDataColumns;
+ }
+ public void setReportDataColumns(ArrayList<ColumnHeader> reportDataColumns) {
+ this.reportDataColumns = reportDataColumns;
+ }
+
+ public int getTotalRows() {
+ return totalRows;
+ }
+ public void setTotalRows(int totalRows) {
+ this.totalRows = totalRows;
+ }
+ public int getPageSize() {
+ return pageSize;
+ }
+ public void setPageSize(int pageSize) {
+ this.pageSize = pageSize;
+ }
+ public String getSqlWhole() {
+ return sqlWhole;
+ }
+ public void setSqlWhole(String sqlWhole) {
+ this.sqlWhole = sqlWhole;
+ }
+
+ public boolean isAllowEdit() {
+ return allowEdit;
+ }
+ public void setAllowEdit(boolean allowEdit) {
+ this.allowEdit = allowEdit;
+ }
+ public String getBackBtnURL() {
+ return backBtnURL;
+ }
+ public void setBackBtnURL(String backBtnURL) {
+ this.backBtnURL = backBtnURL;
+ }
+ public String getColIdxTobeFreezed() {
+ return colIdxTobeFreezed;
+ }
+ public void setColIdxTobeFreezed(String colIdxTobeFreezed) {
+ this.colIdxTobeFreezed = colIdxTobeFreezed;
+ }
+ public int getNumFormCols() {
+ return numFormCols;
+ }
+ public void setNumFormCols(int numFormCols) {
+ this.numFormCols = numFormCols;
+ }
+ public boolean isDisplayData() {
+ return displayData;
+ }
+ public void setDisplayData(boolean displayData) {
+ this.displayData = displayData;
+ }
+ public boolean isDisplayForm() {
+ return displayForm;
+ }
+ public void setDisplayForm(boolean displayForm) {
+ this.displayForm = displayForm;
+ }
+ public boolean isDisplayExcel() {
+ return displayExcel;
+ }
+ public void setDisplayExcel(boolean displayExcel) {
+ this.displayExcel = displayExcel;
+ }
+ public boolean isDisplayPDF() {
+ return displayPDF;
+ }
+ public void setDisplayPDF(boolean displayPDF) {
+ this.displayPDF = displayPDF;
+ }
+ public String getMessage() {
+ return message;
+ }
+ public void setMessage(String message) {
+ this.message = message;
+ }
+ public boolean isChartWizardAvailable() {
+ return chartWizardAvailable;
+ }
+ public void setChartWizardAvailable(boolean chartWizardAvilable) {
+ this.chartWizardAvailable = chartWizardAvilable;
+ }
+ public boolean isHideFormFieldsAfterRun() {
+ return hideFormFieldsAfterRun;
+ }
+ public void setHideFormFieldsAfterRun(boolean hideFormFieldsAfterRun) {
+ this.hideFormFieldsAfterRun = hideFormFieldsAfterRun;
+ }
+
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.*;
+import javax.servlet.http.*;
+
+import org.onap.portalsdk.analytics.model.base.*;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.*;
+import org.onap.portalsdk.analytics.xmlobj.*;
+
+public class ReportParamDateValueParser {
+
+ /*public static final SimpleDateFormat[] dateFormats;
+
+ static {
+ dateFormats = new SimpleDateFormat[5];
+ (dateFormats[0] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MONTHYYYY))
+ .setLenient(true);
+ (dateFormats[1] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MONTHDDYYYY))
+ .setLenient(true);
+ (dateFormats[2] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMDDYYYY))
+ .setLenient(true);
+ (dateFormats[3] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMYYYY))
+ .setLenient(true);
+ (dateFormats[4] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_DDMONYYYY))
+ .setLenient(true);
+ }*/
+
+ public static boolean isDateHrParam(String param) {
+ SimpleDateFormat[] dateFormats = new SimpleDateFormat[2];
+ (dateFormats[0] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMDDYYYY_HR))
+ .setLenient(true);
+ (dateFormats[1] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_DDMONYYYY_HR))
+ .setLenient(true);
+ for (int i = 0; i < dateFormats.length; i++) {
+ try {
+ if (dateFormats[i].parse(param) != null) {
+ return true;
+ }
+ } catch (ParseException pe) {
+ // do nothing, continue to check param against other dates
+ }
+ catch (NumberFormatException pe) {
+ // do nothing, continue to check param against other dates
+ }
+ }
+ return false;
+ }
+ public static boolean isDateParam(String param) {
+ SimpleDateFormat[] dateFormats = new SimpleDateFormat[5];
+ (dateFormats[0] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MONTHYYYY))
+ .setLenient(true);
+ (dateFormats[1] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MONTHDDYYYY))
+ .setLenient(true);
+ (dateFormats[2] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMDDYYYY))
+ .setLenient(true);
+ (dateFormats[3] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMYYYY))
+ .setLenient(true);
+ (dateFormats[4] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_DDMONYYYY))
+ .setLenient(true);
+
+ for (int i = 0; i < dateFormats.length; i++) {
+ try {
+ if (dateFormats[i].parse(param) != null) {
+ return true;
+ }
+ } catch (ParseException pe) {
+ // do nothing, continue to check param against other dates
+ }
+ catch (NumberFormatException pe) {
+ // do nothing, continue to check param against other dates
+ }
+ }
+ return false;
+ }
+
+ public static String formatDateParamValue(String param) {
+ return ReportParamDateValueParser.formatDateParamValue(param, null);
+ }
+
+ public static String formatDateHrParamValue(String param) {
+ return ReportParamDateValueParser.formatDateHrParamValue(param, null);
+ }
+
+ public static String formatDateHrParamValue(String param, String dateHrFormatPattern) {
+ String formattedDate = null;
+ Date parsedDate = null;
+
+ dateHrFormatPattern = (dateHrFormatPattern != null) ? dateHrFormatPattern
+ : "HH";
+
+ SimpleDateFormat[] dateFormats = new SimpleDateFormat[2];
+ (dateFormats[0] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMDDYYYY_HR))
+ .setLenient(true);
+ (dateFormats[1] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_DDMONYYYY_HR))
+ .setLenient(true);
+
+ for (int i = 0; i < dateFormats.length; i++) {
+ try {
+ if (dateFormats[i].parse(param) != null) {
+ SimpleDateFormat newDateFormat = new SimpleDateFormat(dateHrFormatPattern);
+ parsedDate = dateFormats[i].parse(param);
+ formattedDate = newDateFormat.format(parsedDate);
+
+
+ return formattedDate;
+ }
+ } catch (ParseException pe) {
+ // do nothing, continue to check param against other dates and
+ // format accordingly
+ }
+ catch (NumberFormatException pe) {
+ // do nothing, continue to check param against other dates
+ }
+ }
+ return param;
+ }
+
+
+ public static String formatDateParamValue(String param, String dateFormatPattern) {
+ String formattedDate = null;
+ Date parsedDate = null;
+
+ dateFormatPattern = (dateFormatPattern != null) ? dateFormatPattern
+ : AppConstants.JAVA_DATE_FORMAT_MMDDYYYY;
+
+ SimpleDateFormat[] dateFormats = new SimpleDateFormat[5];
+ (dateFormats[0] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MONTHYYYY))
+ .setLenient(true);
+ (dateFormats[1] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MONTHDDYYYY))
+ .setLenient(true);
+ (dateFormats[2] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMDDYYYY))
+ .setLenient(true);
+ (dateFormats[3] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMYYYY))
+ .setLenient(true);
+ (dateFormats[4] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_DDMONYYYY))
+ .setLenient(true);
+
+ for (int i = 0; i < dateFormats.length; i++) {
+ try {
+ if (dateFormats[i].parse(param) != null) {
+ SimpleDateFormat newDateFormat = new SimpleDateFormat(dateFormatPattern);
+ parsedDate = dateFormats[i].parse(param);
+ formattedDate = newDateFormat.format(parsedDate);
+
+ if (Globals.getMonthFormatUseLastDay()
+ && (dateFormats[i].toPattern().equals(
+ AppConstants.JAVA_DATE_FORMAT_MMYYYY) || dateFormats[i]
+ .toPattern().equals(
+ AppConstants.JAVA_DATE_FORMAT_MONTHYYYY))) {
+
+ GregorianCalendar gc = new GregorianCalendar();
+ gc.setTime(parsedDate);
+ int day = gc.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
+ formattedDate = Utils.replaceInString(formattedDate, "/01/", "/"
+ + String.valueOf(day) + "/");
+
+ }
+
+ return formattedDate;
+ }
+ } catch (ParseException pe) {
+ // do nothing, continue to check param against other dates and
+ // format accordingly
+ }
+ catch (NumberFormatException pe) {
+ // do nothing, continue to check param against other dates
+ }
+ }
+ return param;
+ }
+
+} // ReportParamValues
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Iterator;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.system.ConnectionUtils;
+import org.onap.portalsdk.analytics.system.DbUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.analytics.util.XSSFilter;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class ReportParamValues extends Hashtable {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportParamValues.class);
+
+ private Hashtable paramIsMultiValue = null;
+ private Hashtable paramIsTextAreaValue = null;
+ private Hashtable paramIsTextAreaDrilldownValue = null;
+ private Hashtable paramIsTextAreaValueModified = null;
+ private ReportFormFields rff = null;
+
+ private Hashtable multiValueBaseSQL = null;
+ private Hashtable textAreaValueBaseSQL = null;
+
+ public ReportParamValues() {
+ super();
+ paramIsMultiValue = new Hashtable();
+ multiValueBaseSQL = new Hashtable();
+ paramIsTextAreaValue = new Hashtable();
+ paramIsTextAreaDrilldownValue = new Hashtable();
+ paramIsTextAreaValueModified = new Hashtable();
+ } // ReportParamValues
+
+ public ReportParamValues(ReportFormFields rff, String reportDefType) {
+ this();
+ this.rff = rff;
+ for (Iterator iter = rff.iterator(); iter.hasNext();) {
+ FormField ff = (FormField) iter.next();
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
+ put(ff.getFieldName(), nvl(ff.getDefaultValue()));
+ put(ff.getFieldName()+"_Hr", nvl(ff.getDefaultValue()));
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
+ put(ff.getFieldName()+"_Min", nvl(ff.getDefaultValue()));
+ }
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
+ put(ff.getFieldName()+"_Sec", nvl(ff.getDefaultValue()));
+ }
+ } else
+ put(ff.getFieldName(), nvl(ff.getDefaultValue()));
+
+ boolean isMultiValue = ff.getFieldType().equals(FormField.FFT_CHECK_BOX)
+ || ff.getFieldType().equals(FormField.FFT_LIST_MULTI);
+ boolean isTextAreaValue = ff.getFieldType().equals(FormField.FFT_TEXTAREA) && reportDefType
+ .equals(AppConstants.RD_SQL_BASED);
+
+ paramIsMultiValue.put(ff.getFieldName(), new Boolean(isMultiValue));
+ paramIsTextAreaValue.put(ff.getFieldName(), new Boolean(isTextAreaValue));
+
+ if ((isMultiValue || isTextAreaValue) && ff.getBaseSQL() != null)
+ multiValueBaseSQL.put(ff.getFieldName(), ff.getBaseSQL());
+
+
+ } // for
+ } // ReportParamValues
+
+ /*
+ * public ReportParamValues(ReportFormFields rff, HttpServletRequest
+ * request) { this(rff);
+ *
+ * setParamValues(request); } // ReportParamValues
+ */
+ public boolean isParameterMultiValue(String fieldName) {
+ Boolean b = (Boolean) paramIsMultiValue.get(fieldName);
+ return (b != null) ? b.booleanValue() : false;
+ } // isParameterMultiValue
+
+ public boolean isParameterTextAreaValue(String fieldName) {
+ Boolean b = (Boolean) paramIsTextAreaValue.get(fieldName);
+ return (b != null) ? b.booleanValue() : false;
+ } // isParameterMultiValue
+
+ public boolean isParameterTextAreaValueAndModified(String fieldName) {
+ Boolean b = (Boolean) paramIsTextAreaValueModified.get(fieldName);
+ return (b != null) ? b.booleanValue() : false;
+ } // isParameterMultiValue
+
+ public boolean setParamValues(HttpServletRequest request, boolean refresh) {
+ long currentTime = System.currentTimeMillis();
+ //System.out.println("ReportParamValues setParamValues called " + refresh);
+ boolean paramUpdated = false;
+ if(refresh) clearValues();
+ for (Enumeration enKeys = keys(); enKeys.hasMoreElements();) {
+ String key = (String) enKeys.nextElement();
+ String oldValue = XSSFilter.filterRequestOnlyScript(getParamValue(key));
+ String newValue = null;
+ if (isParameterMultiValue(key)) {
+ String[] values = request.getParameterValues(key);
+
+ if (values != null) {
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < values.length; i++) {
+ if (sb.length() > 0)
+ sb.append('|');
+ sb.append(values[i]);
+ } // for
+
+ newValue = XSSFilter.filterRequestOnlyScript(sb.toString());
+ } // if
+ } else if (isParameterTextAreaValue(key)) {
+/* String[] values = request.getParameterValues(key);
+
+ if (values != null) {
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < values.length; i++) {
+ if (sb.length() > 0)
+ sb.append('|');
+ sb.append(values[i]);
+ } // for
+*/
+ String value = "";
+ value = request.getParameter(key);
+ value = Utils.oracleSafe(nvl(value));
+ paramIsTextAreaDrilldownValue.put(key, value);
+ value = value.replaceAll(",", "|");
+ value = "('" + Utils.replaceInString(value, "|", "','") + "')";
+ //value = Utils.replaceInString(value, "|", ",");
+ newValue = XSSFilter.filterRequestOnlyScript(value);
+ paramIsTextAreaValueModified.put(key, new Boolean(true));
+ //} // if
+
+ } else
+ // newValue = nvl(request.getParameter(key));
+ newValue = XSSFilter.filterRequestOnlyScript(request.getParameter(key));
+ //debugLogger.debug("IN REPORTPARAM ^NEW VALUE " + newValue + " OLD VALUE " + oldValue + " KEY " + key + " isParameterMultiValue(key) " + isParameterMultiValue(key));
+ if(!isParameterMultiValue(key) && !isParameterTextAreaValue(key)) {
+ if(refresh && nvl(newValue).length()<=0) {
+ put(key, oldValue);
+ } else if ( ((newValue != null && newValue.trim().length()>0) && (oldValue!=null && oldValue.trim().length()>0) && !newValue.equals(oldValue)) ||
+ ((newValue != null && newValue.trim().length()>0) && (oldValue == null || oldValue.trim().length() <= 0)) ) {
+ paramUpdated = true;
+ //System.out.println("paramupdated1 " +paramUpdated+ " " + newValue + " " + oldValue);
+ // if(newValue.startsWith("[") && newValue.endsWith("]")) {
+ // newValue = getDateAsString(newValue);
+ // }
+ put(key, newValue);
+ } else if (((newValue == null || newValue.trim().length()<=0)) && (oldValue!=null && oldValue.trim().length()>0)) {
+ paramUpdated = true;
+ put(key, newValue);
+ } else if (nvl(newValue).equals(nvl(oldValue)) ) {
+ put(key, newValue);
+ } else {
+ put(key, "");
+ }
+ } else {
+ if (((newValue != null && newValue.trim().length()>0) && (oldValue!=null && oldValue.trim().length()>0) && !newValue.equals(oldValue)) ||
+ ((newValue != null && newValue.trim().length()>0) && (oldValue == null || oldValue.trim().length() <= 0)) && (isParameterMultiValue(key)||isParameterTextAreaValue(key))) {
+ if(isParameterTextAreaValue(key)) {
+ newValue = getParamValueforTextAreaDrilldown(key);
+ if(newValue.length() > 0 && !newValue.equals(oldValue)) {
+ paramUpdated = true;
+ put (key, newValue);
+ }
+ } else {
+ paramUpdated = true;
+ put (key, newValue);
+ }
+
+ } else if (((newValue == null || newValue.trim().length()<=0)) && (oldValue!=null && oldValue.trim().length()>0) && (isParameterMultiValue(key)||isParameterTextAreaValue(key))) {
+ paramUpdated = true;
+ //System.out.println("paramupdated3 " +paramUpdated+ " N" + newValue + " O" + oldValue);
+ put(key, "");
+ }
+ }
+ } // for
+ //printValues();
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] ------->Time Taken for Adding/Clearing Param Values for Search Field Display " + (System.currentTimeMillis() - currentTime)));
+ return paramUpdated;
+ } // setParamValues
+
+ public String getParamValueforTextAreaDrilldown(String key) {
+ return (String) paramIsTextAreaDrilldownValue.get(key);
+ }
+
+ public String getParamValue(String key) {
+ //This logic below is added to avoid BLANK formfield to pass through logic - Sundar
+ if (key!=null) {
+ if(isParameterTextAreaValueAndModified(key)) {
+ String value = "";
+ value = (String) get(key);
+ value = Utils.oracleSafe(nvl(value));
+ value = value.replaceAll(",","|");
+ if(nvl(value).length()>0) {
+ if(value.indexOf("|")!= -1) { // Need option to support "|"
+ value = Utils.replaceInString(value,"\r\n","~");
+ }
+ value = Utils.replaceInString(value, "~", "' , '");
+ value = "('" + Utils.replaceInString(value, "|", "','") + "')"; // changed from "|"
+ //value = Utils.replaceInString(value, "|", ",");
+ value = XSSFilter.filterRequestOnlyScript(value);
+ return value;
+ } else return "";
+
+// if(nvl(value).length()>0) {
+// value = Utils.replaceInString(value, ",", "|");
+// value = value.indexOf("('")!=-1? value.substring(2, value.length()-2):value;
+// value = Utils.replaceInString(value, "'|'", ",");
+// }
+// return value;
+
+ } else
+ return (String) get(key);
+ }
+ else
+ return "";
+ } // getParamValue
+
+ public String getParamDisplayValue(String key) {
+ String value = getParamValue(key);
+ if (isParameterMultiValue(key))
+ value = "(" + Utils.replaceInString(value, "|", ",") + ")";
+ return value;
+ } // getParamValue
+
+ public String getParamBaseSQL(String key) {
+ return (String) multiValueBaseSQL.get(key);
+ } // getParamBaseSQL
+
+ /** ************************************************************************************************* */
+
+ private String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ private String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+ private boolean isNull(String a) {
+ if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null"))
+ return true;
+ else
+ return false;
+ }
+
+ private void clearValues() {
+ FormField ff = null;
+ String defaultValue = "";
+ String defaultSQL = "";
+ String defaultQuery = "";
+ DataSet dsDefault = null;
+ if (rff!= null) {
+ for (Enumeration enKeys = keys(); enKeys.hasMoreElements();) {
+ String key = (String) enKeys.nextElement();
+ for(rff.resetNext(); rff.hasNext(); ) {
+ ff = rff.getNext();
+ if(ff.getFieldName().equals(key)) {
+ // Add default Value
+ defaultValue = ff.getDefaultValue();
+ defaultSQL = ff.getFieldDefaultSQL();
+ if(nvl(defaultValue).length()>0) {
+ put(key,ff.getDefaultValue());
+ } else if(nvl(defaultSQL).length() > 0) {
+ //defaultSQL = Utils.replaceInString(defaultSQL, "[LOGGED_USERID]", userId);
+ if(!(isParameterMultiValue(key) || isParameterTextAreaValue(key))) {
+ defaultQuery = "SELECT id, name FROM (SELECT rownum r, id, name FROM (" + defaultSQL
+ + ") x "
+ + ") xx ";
+ try {
+ dsDefault = ConnectionUtils.getDataSet(defaultQuery, ff.getDbInfo());
+ if(dsDefault!=null && dsDefault.getRowCount()>0) {
+ for (int i = 0; i < dsDefault.getRowCount(); i++) {
+ put(key, dsDefault.getString(i, 0));
+ }
+ }
+ } catch (RaptorException ex) {}
+ } else put(key, "");
+
+ } else put(key,"");
+ break;
+ }
+ }
+ }
+ }
+
+/* for (Enumeration enKeys = keys(); enKeys.hasMoreElements();) {
+ String key = (String) enKeys.nextElement();
+ put(key,"");
+ }
+*/
+ }
+
+
+ public void printValues() {
+ for (Enumeration enKeys = keys(); enKeys.hasMoreElements();) {
+ String key = (String) enKeys.nextElement();
+ String value = (String) get(key);
+ System.out.println("ReportParamValues " + key + " "+ value);
+ }
+ }
+
+ private String getDateAsString (String keyword) {
+ String sql = "";
+ if (keyword.equals("[PROCESSING_DATE]")) {
+ //sql = "select to_char(trunc(sysdate,'dd'), 'mm/dd/yyyy') as dateStr from dual";
+ sql = "select to_char(trunc(sysdate,'dd'), 'mm/dd/yyyy') as dateStr" + Globals.getGenerateSqlVisualDual();
+ } else if (keyword.equals("[PROCESSING_NEXT_DATE]")) {
+ //sql = "select to_char(trunc(sysdate+1,'dd'), 'mm/dd/yyyy') as dateStr from dual";
+ sql = "select to_char(trunc(sysdate+1,'dd'), 'mm/dd/yyyy') as dateStr" + Globals.getGenerateSqlVisualDual();
+ } else if (keyword.equals("[PROCESSING_DAY_BEFORE_DATE]")) {
+ //sql = "select to_char(trunc(sysdate-1,'dd'), 'mm/dd/yyyy') as dateStr from dual";
+ sql = "select to_char(trunc(sysdate-1,'dd'), 'mm/dd/yyyy') as dateStr"+ Globals.getGenerateSqlVisualDual();
+ } else if (keyword.equals("[PROCESSING_MONTH_START_DATE]")) {
+ //sql = "select to_char(trunc(sysdate,'MM'), 'mm/dd/yyyy') as dateStr from dual";
+ sql = "select to_char(trunc(sysdate,'MM'), 'mm/dd/yyyy') as dateStr"+ Globals.getGenerateSqlVisualDual();
+ } else if (keyword.equals("[PROCESSING_MONTH_END_DATE]")) {
+ //sql = "select to_char(last_day(sysdate), 'mm/dd/yyyy') as dateStr from dual";
+ sql = "select to_char(last_day(sysdate), 'mm/dd/yyyy') as dateStr" + Globals.getGenerateSqlVisualDual();
+ } else if (keyword.equals("[CURRENT_HOUR]")) {
+ //sql = "select to_char(trunc(sysdate,'HH24'),'mm/dd/yyyy HH24') as dateStr from dual";
+ sql = "select to_char(trunc(sysdate,'HH24'),'mm/dd/yyyy HH24') as dateStr"+ Globals.getGenerateSqlVisualDual();
+ } else if (keyword.equals("[PREVIOUS_HOUR]")) {
+ //sql = "select to_char(trunc(sysdate-1/24, 'HH24'),'mm/dd/yyyy HH24') as dateStr from dual";
+ sql = "select to_char(trunc(sysdate-1/24, 'HH24'),'mm/dd/yyyy HH24') as dateStr" + Globals.getGenerateSqlVisualDual();
+ } else if (keyword.equals("[NEXT_HOUR]")) {
+ //sql = "select to_char(trunc(sysdate+1/24, 'HH24'),'mm/dd/yyyy HH24') as dateStr from dual";
+ sql = "select to_char(trunc(sysdate+1/24, 'HH24'),'mm/dd/yyyy HH24') as dateStr" + Globals.getGenerateSqlVisualDual();
+ }
+ DataSet ds = null;
+
+ try {
+ if(sql.length()>0) {
+ ds = DbUtils.executeQuery(sql);
+ return ds.getString(0,0);
+ }
+ else
+ return "";
+ } catch (RaptorException ex) {
+ ex.printStackTrace();
+ //throw ex;
+ }
+ return "";
+ }
+} // ReportParamValues
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Iterator;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.ConnectionUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class ReportParamValuesForPDFExcel extends Hashtable {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportParamValuesForPDFExcel.class);
+
+ private Hashtable paramIsMultiValue = null;
+ private Hashtable paramIsTextAreaValue = null;
+ private ReportFormFields rff = null;
+
+ private Hashtable multiValueBaseSQL = null;
+
+ public ReportParamValuesForPDFExcel() {
+ super();
+ paramIsMultiValue = new Hashtable();
+ paramIsTextAreaValue = new Hashtable();
+ multiValueBaseSQL = new Hashtable();
+ } // ReportParamValues
+
+ public ReportParamValuesForPDFExcel(ReportFormFields rff, String reportDefType) {
+ this();
+ this.rff = rff;
+ for (Iterator iter = rff.iterator(); iter.hasNext();) {
+ FormField ff = (FormField) iter.next();
+
+ put(ff.getFieldName(), nvl(ff.getDefaultValue()));
+
+ boolean isMultiValue = ff.getFieldType().equals(FormField.FFT_CHECK_BOX)
+ || ff.getFieldType().equals(FormField.FFT_LIST_MULTI);
+ boolean isTextAreaValue = ff.getFieldType().equals(FormField.FFT_TEXTAREA) && reportDefType
+ .equals(AppConstants.RD_SQL_BASED);
+ paramIsMultiValue.put(ff.getFieldName(), new Boolean(isMultiValue));
+ paramIsTextAreaValue.put(ff.getFieldName(), new Boolean(isTextAreaValue));
+ if (isMultiValue && ff.getBaseSQL() != null)
+ multiValueBaseSQL.put(ff.getFieldName(), ff.getBaseSQL());
+ } // for
+ } // ReportParamValues
+
+ /*
+ * public ReportParamValues(ReportFormFields rff, HttpServletRequest
+ * request) { this(rff);
+ *
+ * setParamValues(request); } // ReportParamValues
+ */
+ public boolean isParameterMultiValue(String fieldName) {
+ Boolean b = (Boolean) paramIsMultiValue.get(fieldName);
+ return (b != null) ? b.booleanValue() : false;
+ } // isParameterMultiValue
+
+ public boolean isParameterTextAreaValue(String fieldName) {
+ Boolean b = (Boolean) paramIsTextAreaValue.get(fieldName);
+ return (b != null) ? b.booleanValue() : false;
+ } // isParameterMultiValue
+
+ public boolean setParamValues(HttpServletRequest request, boolean refresh) {
+ //debugLogger.debug("ReportParamValues for PDF Excel setParamValues called " + refresh);
+ long currentTime = System.currentTimeMillis();
+ boolean paramUpdated = false;
+ if(refresh) clearValues();
+ String name = null;
+ String value = null;
+ String value1 = "";
+ String sql = "";
+ FormField ff = null;
+ String dbInfo = null;
+ ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
+ if(rr!=null && rr.getReportType().equals(AppConstants.RT_DASHBOARD)) {
+ rr = (ReportRuntime) request.getSession().getAttribute("FirstDashReport");
+ if(rr!=null)
+ rff = rr.getReportFormFields();
+ } else if (rr == null) {
+ rr = (ReportRuntime) request.getSession().getAttribute("FirstDashReport");
+ if(rr!=null)
+ rff = rr.getReportFormFields();
+ } else {
+ rff = rr.getReportFormFields();
+ }
+
+ if(rr!=null) {
+ dbInfo = rr.getDBInfo();
+ if (Utils.isNull(dbInfo)) {
+ dbInfo = (String) request.getSession().getAttribute("remoteDB");
+ }
+ if(!Utils.isNull(dbInfo)){
+ for (Iterator iter = rff.iterator(); iter.hasNext();) {
+ name=""; //just added
+ ff = (FormField) iter.next();
+ //debugLogger.debug("ff.getFieldName " + ff.getFieldName() + " " + ff.getFieldDisplayName() + " " + ff.getFieldType()+ " " +ff.getBaseSQLForPDFExcel()+ " "+ rr.getParamValue(ff.getFieldName()));
+ if(!ff.getFieldType().equals(FormField.FFT_BLANK)) {
+ sql = ff.getBaseSQLForPDFExcel();
+ if(sql!=null && sql.trim().length()>0)
+ sql = Utils.replaceInString(sql, "[LOGGED_USERID]", AppUtils.getUserID(request));
+ if(ff.getFieldType().equals(FormField.FFT_COMBO_BOX) || ff.getFieldType().equals(FormField.FFT_LIST_BOX) || ff.getFieldType().equals(FormField.FFT_TEXT_W_POPUP) || ff.getFieldType().equals(FormField.FFT_HIDDEN)) {
+ for (Enumeration enum1 = rr.getParamKeys(); enum1.hasMoreElements();) {
+ name = (String) enum1.nextElement();
+ value = rr.getParamValue(name);
+ value = getParamValueForSQL(name, value);
+ if(name.startsWith("ff")) {
+ for (Iterator iter1 = rff.iterator(); iter1.hasNext();) {
+ FormField ff1 = (FormField) iter1.next();
+
+ if(sql!=null && sql.trim().length()>0){
+ if(name.equals(ff.getFieldName())){
+ sql = Utils.replaceInString(sql, "[VALUE]", value);
+ }
+ if(name.equals(ff1.getFieldName())){
+ sql = Utils.replaceInString(sql, "["+ff1.getFieldDisplayName()+"]", value);
+
+ } else continue;
+ }
+ }
+ }
+ }
+ } else if (ff.getFieldType().equals(ff.FFT_LIST_MULTI)||ff.getFieldType().equals(ff.FFT_CHECK_BOX)) {
+ for (Enumeration enum1 = rr.getParamKeys(); enum1.hasMoreElements();) {
+ name = (String) enum1.nextElement();
+ value = rr.getParamValue(name);
+ value = getParamValueForSQL(name, value);
+ if(name.startsWith("ff")) {
+ for (Iterator iter1 = rff.iterator(); iter1.hasNext();) {
+ FormField ff1 = (FormField) iter1.next();
+
+ if(sql!=null && sql.trim().length()>0){
+ if(name.equals(ff.getFieldName())){
+ sql = Utils.replaceInString(sql, "[VALUE]", value);
+ }
+ if(name.equals(ff1.getFieldName())){
+ sql = Utils.replaceInString(sql, "["+ff1.getFieldDisplayName()+"]", value);
+
+ } else continue;
+ }
+ }
+ }
+ }
+ } else {
+ if(nvl(ff.getFieldDefaultSQL()).length()<=0)
+ sql = "";
+ }
+ if(sql!=null && sql.trim().length()>0){
+ name = "";
+ if(name.length()<=0) name = ff.getFieldName();
+ value = rr.getParamValue(name);
+ //debugLogger.debug("Name "+ name+ " value:" + value);
+ String paramValue = getParamValueForSQL(name, value);
+ //debugLogger.debug("PDFEXCEL " + name+ " " + ff.getFieldName()+ " " + value + " " + sql +" "+ paramValue);
+ if(name!=null && name.equals(ff.getFieldName()))
+ sql = Utils.replaceInString(sql, "[VALUE]", paramValue);
+ if(paramValue == null) {
+ if(sql.lastIndexOf("where id = ''")>0)
+ sql = sql.substring(0, sql.lastIndexOf("where id = ''"));
+ }
+ //debugLogger.debug("SQL Modified " + sql);
+ FormField ff2 = null;
+ for (Iterator iter1 = rff.iterator(); iter1.hasNext();) {
+ ff2 = (FormField)iter1.next();
+ sql = Utils.replaceInString(sql, "[" + ff2.getFieldDisplayName() +"]", getParamValue(ff2.getFieldName()));
+ }
+ //debugLogger.debug("SQL Modified after replacing formfield" + sql);
+ try {
+ String[] reqParameters = Globals.getRequestParams().split(",");
+ String[] sessionParameters = Globals.getSessionParams().split(",");
+ String[] scheduleSessionParameters = Globals.getSessionParamsForScheduling().split(",");
+ javax.servlet.http.HttpSession session = request.getSession();
+ //debugLogger.debug("B4 Session " + sql);
+ if(session != null ) {
+ for (int i = 0; i < sessionParameters.length; i++) {
+ sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
+ }
+ }
+ //debugLogger.debug("B4 request " + sql);
+ if(request != null ) {
+ for (int i = 0; i < scheduleSessionParameters.length; i++) {
+ sql = Utils.replaceInString(sql, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) );
+ }
+ for (int i = 0; i < reqParameters.length; i++) {
+ if(!reqParameters[i].startsWith("ff")) {
+ if (request.getParameter(reqParameters[i])!=null) {
+ sql = Utils.replaceInString(sql, "[" + reqParameters[i]+"]", request.getParameter(reqParameters[i]) );
+ sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
+ }
+ else {
+ sql = Utils.replaceInString(sql, "[" + reqParameters[i]+"]", request.getParameter(reqParameters[i].toUpperCase()) );
+ sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
+ }
+ }
+ else
+ sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
+ }
+ }
+ //debugLogger.debug("After request " + sql);
+ DataSet ds = null;
+ try {
+ ds = ConnectionUtils.getDataSet(sql, dbInfo);
+ } catch (ReportSQLException ex) {
+ logger.debug(EELFLoggerDelegate.debugLogger, ("sql not complete" + sql));
+ }
+ if(ff.getFieldType().equals(FormField.FFT_LIST_MULTI) || ff.getFieldType().equals(FormField.FFT_CHECK_BOX)) {
+ StringBuffer multiValue = new StringBuffer("");
+ if(ds!=null) {
+ for(int i = 0; i < ds.getRowCount(); i++) {
+ //if(i==0) multiValue.append("(");
+ multiValue.append(ds.getString(i,1));
+ if(i<ds.getRowCount()-1)
+ multiValue.append("|");
+ //else multiValue.append(")");
+
+ }
+ }
+ put(ff.getFieldName(), nvl(multiValue.toString()));
+ } else {
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ) {
+ value1 = nvl(rr.getParamValue(ff.getFieldName())) + " "+addZero(Utils.oracleSafe(nvl(rr
+ .getParamValue(ff.getFieldName()+"_Hr"))));
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ) {
+ value1 = value1 + (nvl(rr
+ .getParamValue(ff.getFieldName()+"_Min")).length() > 0 ? ":" + addZero(Utils.oracleSafe(nvl(rr
+ .getParamValue(ff.getFieldName()+"_Min")))) : "");
+ }
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ) {
+ value1 = value1 + (nvl(rr
+ .getParamValue(ff.getFieldName()+"_Sec")).length() > 0 ? ":"+ addZero(Utils.oracleSafe(nvl(rr
+ .getParamValue(ff.getFieldName()+"_Sec")))) : "");
+ }
+ //debugLogger.debug("77777777777777 " + value1);
+ put(ff.getFieldName(), nvl(value1));
+ } else {
+
+ if(ds!=null && ds.getRowCount()>0) put(ff.getFieldName(), nvl(ds.getString(0,1)));
+ else put(ff.getFieldName(), nvl(value));
+ }
+ }
+
+ paramUpdated = true;
+ } catch (ReportSQLException ex) {
+ logger.debug(EELFLoggerDelegate.debugLogger, ("sql not complete" + sql));
+ }
+ catch (Exception ex) {}
+
+ //debugLogger.debug("66666666666666666 " + ff.getValidationType());
+
+ //Added for TimeStamp validation
+
+ } else {
+ if(!ff.getFieldType().equals(FormField.FFT_BLANK)) {
+ //Added for TimeStamp validation
+ //debugLogger.debug("666666666666 " + ff.getValidationType());
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ) {
+ value1 = nvl(rr.getParamValue(ff.getFieldName())) + " "+addZero(Utils.oracleSafe(nvl(rr
+ .getParamValue(ff.getFieldName()+"_Hr"))));
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ) {
+ value1 = value1 + (nvl(rr
+ .getParamValue(ff.getFieldName()+"_Min")).length() > 0 ? ":" + addZero(Utils.oracleSafe(nvl(rr
+ .getParamValue(ff.getFieldName()+"_Min")))) : "");
+ }
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ) {
+ value1 = value1 + (nvl(rr
+ .getParamValue(ff.getFieldName()+"_Sec")).length() > 0 ? ":"+ addZero(Utils.oracleSafe(nvl(rr
+ .getParamValue(ff.getFieldName()+"_Sec")))) : "");
+ }
+ //debugLogger.debug("77777777777777 " + value1);
+ } else
+ value1 = nvl(rr.getParamValue(ff.getFieldName()));
+ if(value1.length()<=0) value1 = nvl(ff.getDefaultValue());
+ put(ff.getFieldName(), nvl(value1));
+
+ }
+ paramUpdated = true;
+ }
+
+ } // BLANK
+ } // for
+ } // dbInfo
+ } // !=null
+
+ //printValues();
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] ------->Time Taken for Adding/Clearing Param Values for FormField Info Bar " + (System.currentTimeMillis() - currentTime)));
+ return paramUpdated;
+ } // setParamValues
+
+ public String getParamValue(String key) {
+ if (key!=null)
+ return (String) get(key);
+ else
+ return "NULL";
+ } // getParamValue
+
+ public String getParamValueForSQL(String key, String value) {
+ value = Utils.oracleSafe(value);
+ if (isParameterMultiValue(key))
+ value = "('" + Utils.replaceInString(value, "|", "','") + "')";
+ return value;
+ } // getParamValue
+
+ public String getParamDisplayValue(String key) {
+ //debugLogger.debug("Key is " + key +" Value is " + getParamValue(key));
+ String value = getParamValue(key);
+ if (isParameterMultiValue(key))
+ value = "(" + Utils.replaceInString(value, "|", ",") + ")";
+ return value;
+ } // getParamValue
+
+ public String getParamBaseSQL(String key) {
+ return (String) multiValueBaseSQL.get(key);
+ } // getParamBaseSQL
+
+ /** ************************************************************************************************* */
+
+ private String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ private String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+ private boolean isNull(String a) {
+ if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null"))
+ return true;
+ else
+ return false;
+ }
+
+ private void clearValues() {
+ FormField ff = null;
+ String defaultValue = "";
+ String defaultSQL = "";
+ String defaultQuery = "";
+ DataSet dsDefault = null;
+ if (rff!= null) {
+ for (Enumeration enKeys = keys(); enKeys.hasMoreElements();) {
+ String key = (String) enKeys.nextElement();
+ for(rff.resetNext(); rff.hasNext(); ) {
+ ff = rff.getNext();
+ if(ff.getFieldName().equals(key)) {
+ // Add default Value
+ defaultValue = ff.getDefaultValue();
+ defaultSQL = ff.getFieldDefaultSQL();
+ if(nvl(defaultValue).length()>0) {
+ put(key,ff.getDefaultValue());
+ } else if(nvl(defaultSQL).length() > 0) {
+ //defaultSQL = Utils.replaceInString(defaultSQL, "[LOGGED_USERID]", userId);
+ if(!(isParameterMultiValue(key) || isParameterTextAreaValue(key))) {
+ defaultQuery = "SELECT id, name FROM (SELECT rownum r, id, name FROM (" + defaultSQL
+ + ") x "
+ + ") xx ";
+ try {
+ dsDefault = ConnectionUtils.getDataSet(defaultQuery, ff.getDbInfo());
+ if(dsDefault!=null && dsDefault.getRowCount()>0) {
+ for (int i = 0; i < dsDefault.getRowCount(); i++) {
+ put(key, dsDefault.getString(i, 1));
+ }
+ }
+ } catch (RaptorException ex) {}
+ } else put(key, "");
+
+ } else put(key,"");
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
+ public void printValues() {
+ for (Enumeration enKeys = keys(); enKeys.hasMoreElements();) {
+ String key = (String) enKeys.nextElement();
+ String value = (String) get(key);
+ logger.debug(EELFLoggerDelegate.debugLogger, ("ReportParamValuesForPDFEXCEL " + key + " "+ value));
+ }
+ }
+ 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;
+ }
+
+} // ReportParamValues
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+import java.io.Serializable;
+import java.sql.Connection;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+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.StringTokenizer;
+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.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.model.DataCache;
+import org.onap.portalsdk.analytics.model.ReportHandler;
+import org.onap.portalsdk.analytics.model.ReportLoader;
+import org.onap.portalsdk.analytics.model.base.IdNameList;
+import org.onap.portalsdk.analytics.model.base.IdNameSql;
+import org.onap.portalsdk.analytics.model.base.IdNameValue;
+import org.onap.portalsdk.analytics.model.base.ReportWrapper;
+import org.onap.portalsdk.analytics.model.definition.Marker;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.ConnectionUtils;
+import org.onap.portalsdk.analytics.system.DbUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.analytics.view.ColumnHeader;
+import org.onap.portalsdk.analytics.view.ColumnHeaderRow;
+import org.onap.portalsdk.analytics.view.CrossTabOrderManager;
+import org.onap.portalsdk.analytics.view.CrossTabTotalValue;
+import org.onap.portalsdk.analytics.view.DataRow;
+import org.onap.portalsdk.analytics.view.DataValue;
+import org.onap.portalsdk.analytics.view.ReportData;
+import org.onap.portalsdk.analytics.view.RowHeaderCol;
+import org.onap.portalsdk.analytics.xmlobj.CustomReportType;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
+import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
+import org.onap.portalsdk.analytics.xmlobj.ObjectFactory;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+
+/**<HR/>
+ * This class is part of <B><I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I></B><BR/>
+ * <HR/>
+ *
+ * --------------------------------------------------------------------------------------------------<BR/>
+ * <B>ReportRuntime.java</B> - This class involves in running, downloading RAPTOR reports.
+ * --------------------------------------------------------------------------------------------------<BR/>
+ *
+ *
+ * <U>Change Log</U><BR/><BR/>
+ *
+ * 27-Aug-2009 : Version 8.5 (Sundar); <UL><LI>Order by logic is restored for DAYTONA.</LI></UL>
+ * 13-Aug-2009 : Version 8.5 (Sundar); <UL><LI>Removing order by logic is rollbacked.</LI></UL>
+ * 22-Jun-2009 : Version 8.4 (Sundar); <UL><LI>Bug while parsing SQL for text download is fixed.</LI></UL>
+ *
+ */
+
+public class ReportRuntime extends ReportWrapper implements Cloneable, Serializable {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportRuntime.class);
+
+ //TODO DELETE IF PARSE SQL is not working
+ private int curSQLParsePos = 0;
+
+ private String xmlFileURL = null;
+
+ private String xmlFileName = null;
+
+ private String flatFileName = null;
+
+ private String excelPageFileName = null;
+
+ private int reportDataSize = -1;
+
+ private boolean displayChart = true;
+
+ private boolean displayForm = true;
+
+ private boolean displayContent = true;
+
+ private boolean reportRunLogged = false; // Used to avoid multiple
+ // entries in the report log
+ // when executing with different
+ // params or going to next page
+
+ private DataSet chartDataCache = null;
+
+ private ReportData pageDataCache = null;
+
+ private int cachedPageNo = -1;
+
+ private String cachedSQL = null; // For display purposes only
+
+ private String wholeSQL = null; // For display purposes only
+
+ private String totalSql = null; // For display purposes only
+
+ private ReportParamValues reportParamValues = null;
+
+ private ReportParamValuesForPDFExcel reportParamValuesFPE = null;
+
+ private ReportFormFields reportFormFields = null;
+
+ private VisualManager visualManager = null;
+
+ private CrossTabOrderManager crossTabOrderManager = null;
+
+ private boolean displayColTotals = false;
+
+ private boolean displayRowTotals = false;
+
+ private DataRow colDataTotalsLinear = null;
+
+ private Vector colDataTotalsCrosstab = null;
+
+ private Vector rowDataTotalsCrosstab = null;
+
+ private String grandTotalCrosstab = null;
+
+ public static int DISPLAY_DATA_ONLY = 1;
+ public static int DISPLAY_CHART_ONLY = 2;
+ public static int DISPLAY_CHART_AND_DATA = 3;
+
+ public static final int DATE_OPTION_MONTHLY = 1;
+ public static final int DATE_OPTION_YEARLY = 2;
+ public static final int DATE_OPTION_DAILY = 3;
+
+
+ private int DISPLAY_MODE = 0;
+
+ private int DATE_OPTION = -1;
+
+ /*
+ * private ReportRuntime(CustomReport cr, String reportID,
+ * HttpServletRequest request) { super(cr, reportID);
+ *
+ * reportParamValues = new ReportParamValues(this); reportFormFields = new
+ * ReportFormFields(this);
+ *
+ * if(request!=null) setParamValues(request); } // ReportRuntime
+ */
+ private ReportRuntime(CustomReportType crType, String reportID, HttpServletRequest request,
+ String ownerID, String createID, String createDate, String updateID,
+ String updateDate, String menuID, boolean menuApproved) throws RaptorException {
+ super(crType, reportID, ownerID, createID, createDate, updateID, updateDate, menuID,
+ menuApproved);
+ initializeReportRuntime(request);
+ } // ReportRuntime
+
+ public ReportRuntime(ReportWrapper rw) throws RaptorException {
+ this(rw, null);
+ } // ReportRuntime
+
+ public ReportRuntime(ReportWrapper rw, HttpServletRequest request)throws RaptorException {
+ super(rw);
+ initializeReportRuntime(request);
+ } // ReportRuntime
+
+ private void initializeReportRuntime(HttpServletRequest request) throws RaptorException {
+ reportFormFields = new ReportFormFields(this, request);
+ setParamValues(request, true, true);
+
+ visualManager = new VisualManager();
+ } // initializeReportRuntime
+
+// public void setReportFormFields(HttpServletRequest request) {
+// reportFormFields = new ReportFormFields(this, request);
+// setParamValues(request, true, true);
+// }
+
+ public static ReportRuntime unmarshal(String reportXML, String reportID)
+ throws RaptorException {
+ return unmarshal(reportXML, reportID, null);
+ } // unmarshal
+
+ public static ReportRuntime unmarshal(String reportXML, String reportID,
+ HttpServletRequest request) throws RaptorException {
+ CustomReportType crType = ReportWrapper.unmarshalCR(reportXML);
+ ObjectFactory objFactory = new ObjectFactory();
+
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report [" + reportID + "]: XML unmarshalled"));
+
+ return new ReportRuntime(crType, reportID, request, null, null, null, null, null, null,
+ false);
+
+ } // unmarshal
+
+ public String getXmlFileURL() {
+ return xmlFileURL;
+ }
+
+ public String getXmlFileName() {
+ return xmlFileName;
+ }
+
+ public String getFlatFileName() {
+ return flatFileName;
+ }
+
+ public String getExcelPageFileName() {
+ return excelPageFileName;
+ }
+
+ public int getReportDataSize() {
+ return reportDataSize;
+ }
+
+ public boolean getDisplayChart() {
+ return displayChart;
+ }
+
+ public boolean getDisplayForm() {
+ return displayForm;
+ }
+
+ public boolean getDisplayContent() {
+ return displayContent;
+ }
+
+ public int getCachedPageNo() {
+ return cachedPageNo;
+ }
+
+ public String getCachedSQL() {
+ return cachedSQL;
+ }
+
+ public boolean isDashboardType() throws RaptorException {
+ return ReportLoader.isDashboardType(getReportID());
+ }
+
+
+ public void setXmlFileURL(String xmlFileURL) {
+ this.xmlFileURL = xmlFileURL;
+ }
+
+ public void setXmlFileName(String xmlFileName) {
+ this.xmlFileName = xmlFileName;
+ }
+
+ public void setFlatFileName(String flatFileName) {
+ this.flatFileName = flatFileName;
+ }
+
+ public void setExcelPageFileName(String excelPageFileName) {
+ this.excelPageFileName = excelPageFileName;
+ }
+
+ /*private*/ public void setReportDataSize(int reportDataSize) {
+ this.reportDataSize = reportDataSize;
+ }
+
+ private void setDisplayForm(boolean displayForm) {
+ this.displayForm = displayForm;
+ }
+
+ private void setDisplayContent(boolean displayContent) {
+ this.displayContent = displayContent;
+ }
+
+ public void setDisplayFlags(boolean isFirstAccess, boolean forceDisplayContent) {
+ if (isFirstAccess) {
+ setDisplayForm(true);
+
+ if (forceDisplayContent)
+ setDisplayContent(true);
+ else if (Globals.getDisplayFormBeforeRun())
+ if (needFormInput())
+ setDisplayContent(false);
+ else
+ setDisplayContent(true);
+ else
+ setDisplayContent(true);
+ } else {
+ setDisplayContent(true);
+
+ if (Globals.getIncludeFormWithData())
+ setDisplayForm(true);
+ else if (Globals.getDisplayFormBeforeRun())
+ setDisplayForm(false);
+ else
+ setDisplayForm(true);
+ } // else
+ } // setDisplayFlags
+
+ public void logReportRun(String userID, String executionTime, String formFields) throws RaptorException {
+ if (reportRunLogged)
+ return;
+
+ ReportLoader.createReportLogEntry(null, reportID, userID, AppConstants.RLA_RUN,executionTime,formFields );
+ reportRunLogged = true;
+ } // logReportRun
+
+ public void logReportExecutionTime(String userId, String executionTime, String action, String formFields) throws RaptorException {
+ ReportLoader.createReportLogEntryForExecutionTime(null, reportID, userId,executionTime , action, formFields);
+ }
+
+ public void logReportExecutionTimeFromLogList (String userId, String executionTime, String formFields) throws RaptorException {
+ ReportLoader.createReportLogEntryForExecutionTime(null, reportID, userId,executionTime , AppConstants.RLA_FROM_LOG, formFields);
+ }
+
+ public void resetVisualSettings() {
+ boolean haveToResetCachedData = (visualManager.getSortByColId().length() > 0);
+ visualManager = new VisualManager();
+
+ if (haveToResetCachedData)
+ pageDataCache = null;
+
+ if (pageDataCache != null)
+ pageDataCache.resetVisualSettings();
+ } // resetVisualSettings
+
+ /** ************** ReportParamValues processing *************** */
+
+ public boolean setParamValues(HttpServletRequest request, boolean resetParams, boolean refresh) throws RaptorException {
+ boolean paramsUpdated = false;
+ if (resetParams) {
+ reportFormFields = new ReportFormFields(this, request);
+ reportParamValues = new ReportParamValues(reportFormFields, getReportDefType());
+ // This is called even in the wizard page. Hence this condition.
+ if((ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null)
+ reportParamValuesFPE = new ReportParamValuesForPDFExcel(reportFormFields, getReportDefType());
+ paramsUpdated = true;
+
+ reportRunLogged = false;
+ } else if (request != null) {
+ paramsUpdated = reportParamValues.setParamValues(request,refresh);
+ }
+ // This is called even in the wizard page. Hence this condition.
+ if((ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null) {
+ if(reportParamValuesFPE!=null) reportParamValuesFPE.setParamValues(request,refresh);
+ else {
+ reportParamValuesFPE = new ReportParamValuesForPDFExcel(reportFormFields, getReportDefType());
+ reportParamValuesFPE.setParamValues(request,refresh);
+ }
+ } else {
+ reportFormFields = new ReportFormFields(this, request);
+ //added below two lines for dashboard default value
+ reportParamValues = new ReportParamValues(reportFormFields, getReportDefType());
+ reportParamValues.setParamValues(request,refresh);
+ //End
+ reportParamValuesFPE = new ReportParamValuesForPDFExcel(reportFormFields, getReportDefType());
+ reportParamValuesFPE.setParamValues(request,refresh);
+
+ }
+// }
+ if (paramsUpdated) {
+ setReportDataSize(-1);
+ chartDataCache = null;
+ pageDataCache = null;
+ cachedPageNo = -1;
+
+ crossTabOrderManager = null;
+
+ colDataTotalsLinear = null;
+ colDataTotalsCrosstab = null;
+ rowDataTotalsCrosstab = null;
+ grandTotalCrosstab = null;
+ if(!refresh)
+ resetVisualSettings();
+ } // if
+
+ displayChart = (request.getParameter(AppConstants.RI_DISPLAY_CHART) == null) ? !isDisplayOptionHideChart() : request.getParameter("display_chart")
+ .equals("Y");
+
+ return paramsUpdated;
+ } // setParamValues
+
+ public String getParamValue(String key) {
+ //reportParamValues.printValues();
+ return reportParamValues.getParamValue(key);
+ } // getParamValue
+
+ public String getParamDisplayValue(String key) {
+ //reportParamValues.printValues();
+ return reportParamValues.getParamDisplayValue(key);
+ } // getParamValue
+
+ public Enumeration getParamKeys() {
+ return reportParamValues.keys();
+ } // getParamKeys
+
+ public Enumeration getParamKeysForPDFExcel() {
+ return reportParamValuesFPE.keys();
+ } // getParamKeys
+
+ public String getParamValueForPDFExcel(String key) {
+ return reportParamValuesFPE.getParamValue(key);
+ } // getParamValue
+
+ public ArrayList getParamNameValuePairs() {
+ ArrayList paramList = new ArrayList(getReportFormFields().size());
+ for (Iterator iter = getReportFormFields().iterator(); iter.hasNext();) {
+ FormField ff = (FormField) iter.next();
+ paramList.add(new IdNameValue(ff.getFieldDisplayName(), reportParamValues
+ .getParamDisplayValue(ff.getFieldName())));
+ } // for
+ return paramList;
+ } // getParamNameValuePairs
+
+ public ArrayList getParamNameValuePairsforPDFExcel(HttpServletRequest request, int type /*excel =1; pdf=2*/) {
+ javax.servlet.http.HttpSession session = request.getSession();
+ ArrayList paramList = new ArrayList(getReportFormFields().size());
+ if(session.getAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO)!=null) {
+ paramList = (ArrayList) session.getAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO);
+ if(paramList!=null && paramList.size()>0)
+ return paramList;
+ }
+ //System.out.println(" getParamNamePairs type " + type + " " + Globals.customizeFormFieldInfo());
+ if ( reportParamValuesFPE == null) {
+ reportParamValuesFPE = new ReportParamValuesForPDFExcel(reportFormFields, getReportDefType());
+ reportParamValuesFPE.setParamValues(request,true);
+ }
+
+ String valueString = "";
+ for (Iterator iter = getReportFormFields().iterator(); iter.hasNext();) {
+ FormField ff = (FormField) iter.next();
+ if(ff.isVisible() && /*!ff.getFieldType().equals(FormField.FFT_HIDDEN) &&*/ type == 1){
+ valueString = reportParamValuesFPE.getParamDisplayValue(ff.getFieldName());
+ } else if(ff.isVisible() && type != 1) {
+ valueString = reportParamValuesFPE.getParamDisplayValue(ff.getFieldName());
+ }
+ if(valueString.equalsIgnoreCase("NULL"))
+ valueString="";
+ paramList.add(new IdNameValue(ff.getFieldDisplayName(), valueString));
+// }
+ } // for
+
+ String pdfAttachmentKey = AppUtils.getRequestValue(request, "pdfAttachmentKey");
+ boolean isSchedule = false;
+ if(pdfAttachmentKey != null)
+ isSchedule = true;
+ if(Globals.customizeFormFieldInfo() && type == 2) {
+ String[] sessionParameters = Globals.getSessionParams().split(",");
+
+ if(session != null && !isSchedule ) {
+ session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
+ for (int i = 0; i < sessionParameters.length; i++) {
+ if(session.getAttribute(sessionParameters[i])!=null)
+ paramList.add(new IdNameValue(sessionParameters[i].toUpperCase(), (String)session.getAttribute(sessionParameters[i])));
+ }
+ }
+
+ if(isSchedule) {
+ //debugLogger.debug("Globals " + Globals.getSessionParamsForScheduling());
+ String[] scheduleSessionParam = Globals.getSessionParamsForScheduling().split(",");
+ for (int i = 0; i < scheduleSessionParam.length; i++) {
+ //debugLogger.debug(" scheduleSessionParam[i] " + scheduleSessionParam[i] + " " + request.getParameter(scheduleSessionParam[i]) );
+ if(request.getParameter(scheduleSessionParam[i])!=null)
+ paramList.add(new IdNameValue(scheduleSessionParam[i].toUpperCase(), request.getParameter(scheduleSessionParam[i])));
+ }
+ }
+
+ try {
+ SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss");
+ Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime());
+ SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern());
+ paramList.add(new IdNameValue("DATE", dtimestamp.format(sysdate)+" "+Globals.getTimeZone()));
+ } catch(Exception ex) {}
+
+ } else {
+ //System.out.println(" In Else getParamNamePairs type " + type);
+ String[] sessionDisplayParameters = Globals.getDisplaySessionParamInPDFEXCEL().split(",");
+ if(session != null && !isSchedule ) {
+ session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
+ for (int i = 0; i < sessionDisplayParameters.length; i++) {
+ String sessionDispParam = sessionDisplayParameters[i];
+ if(nvl(sessionDispParam).length()>0) {
+ String sessionDispParamArr[] = sessionDispParam.split(";");
+ //System.out.println("Session " + sessionDispParamArr[1] + " " + (String)session.getAttribute(sessionDispParamArr[0]));
+ paramList.add(new IdNameValue(sessionDispParamArr[1], nvl((String)session.getAttribute(sessionDispParamArr[0]),"")));
+ }
+ }
+ }
+ if(isSchedule) {
+ String[] scheduleSessionParam = Globals.getDisplayScheduleSessionParamInPDFEXCEL().split(",");
+ for (int i = 0; i < scheduleSessionParam.length; i++) {
+ String scheduleSessionDispParam = scheduleSessionParam[i];
+ if(nvl(scheduleSessionDispParam).length()>0) {
+ String scheduleSessionDispParamArr[] = scheduleSessionDispParam.split(";");
+ paramList.add(new IdNameValue(scheduleSessionDispParamArr[1], nvl(request.getParameter(scheduleSessionDispParamArr[0]),"")));
+ }
+ }
+ }
+ try {
+ SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss");
+ Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime());
+ SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern());
+ paramList.add(new IdNameValue("Report Date/Time", dtimestamp.format(sysdate)+" "+Globals.getTimeZone()));
+ } catch(Exception ex) {}
+
+ }
+
+ for (int i = 0; i < paramList.size(); i++) {
+ IdNameValue value = (IdNameValue) paramList.get(i);
+ String name = value.getName().replaceAll(",","~");
+ value.setName(name);
+ }
+ //request.getSession().setAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO, paramList);
+ return paramList;
+ } // getParamNameValuePairs
+
+ /** ************** ReportFormFields processing *************** */
+
+ public String getFormFieldComments(HttpServletRequest request) {
+ String comment = "";
+ StringBuffer st = new StringBuffer("");
+ if(getFormFieldList()!=null){
+ comment = nvl(getFormFieldList().getComment());
+ ArrayList al = null;
+ if(comment.length()>0) {
+ al = getParamNameValuePairsforPDFExcel(request, 2);
+ if(al!=null) {
+ //st = new StringBuffer(comment);
+ for (int i=0; i < al.size(); i++) {
+ IdNameValue idNameValue = (IdNameValue)al.get(i);
+ if(nvl(idNameValue.getId()).equals("DATE"))
+ st.append("<b>Date/Time Report Run:</b>"+ idNameValue.getName() +"<br></br>");
+ }
+
+ for (int i=0; i < al.size(); i++) {
+ IdNameValue idNameValue = (IdNameValue)al.get(i);
+ comment = Utils.replaceInString(comment, "["+ idNameValue.getId()+"]", idNameValue.getName());
+ }
+ st.append(comment);
+
+ }
+ }
+ }
+ return st.toString();
+ }
+
+ public boolean needFormInput() {
+ return reportFormFields.getFieldCount() > 0;
+ } // needFormInput
+
+ public FormField getFormField(String fieldName) {
+ return reportFormFields.getFormField(fieldName);
+ } // getFormField
+
+ public ReportFormFields getReportFormFields() {
+ return reportFormFields;
+ } // getReportFormFields
+
+ /** ************** Report Data processing *************** */
+ public DataSet loadChartData(String userId, HttpServletRequest request) throws RaptorException {
+ if (nvl(getChartType()).length() == 0)
+ return null;
+ if (!getDisplayChart())
+ return null;
+
+ DataSet ds = chartDataCache;
+ String sql = null;
+ if (ds == null) {
+ sql = generateChartSQL(reportParamValues, userId, request);
+ String dbInfo = getDBInfo();
+ ds = ConnectionUtils.getDataSet(sql, dbInfo);
+ if (Globals.getCacheChartData())
+ chartDataCache = ds;
+ } // if
+
+ return ds;
+ } // loadChartData
+
+ public String getReportDataSQL(String userId, int downloadLimit, HttpServletRequest request) throws RaptorException {
+ String reportSQL = "";
+ if(doesReportContainsGroupFormField()) {
+ reportSQL = generateSubsetSQL(0, downloadLimit,userId, request, true, reportParamValues);
+ } else
+ reportSQL = generateSubsetSQL(0, downloadLimit,userId, request, false, reportParamValues);
+ return reportSQL;
+ }
+
+ public ReportData loadReportData(int pageNo, String userId, int downloadLimit, HttpServletRequest request, boolean download) throws RaptorException {
+ ReportData rd = null;
+ boolean isGoBackAction = AppUtils.getRequestFlag(request, AppConstants.RI_GO_BACK);
+ if (pageNo >= 0)
+ if (pageNo == cachedPageNo && pageDataCache != null)
+ rd = pageDataCache;
+
+ if(isGoBackAction && rd!=null) return rd;
+ if (rd == null) { // Commented So that Data is refreshed from DB again
+ if (getReportDataSize() < 0)
+ if (getReportType().equals(AppConstants.RT_CROSSTAB))
+ rd = loadCrossTabReportData(pageNo, userId, downloadLimit, request, download);
+ else if (getReportType().equals(AppConstants.RT_LINEAR))
+ rd = loadLinearReportData(pageNo, userId, downloadLimit, request, download);
+ else
+ throw new RuntimeException(
+ "[ReportRuntime.loadReportData] Invalid report type");
+
+ if (pageNo >= 0)
+ if (Globals.getCacheCurPageData()) {
+ pageDataCache = rd;
+ cachedPageNo = pageNo;
+ }
+ } // if // Commented So that Data is refreshed from DB again
+
+ return rd;
+ } // loadReportData
+
+ private ReportData loadCrossTabReportData(int pageNo, String userId, int downloadLimit, HttpServletRequest request, boolean download) throws RaptorException {
+ String reportSQL = generateSQL(reportParamValues, userId, request);
+ setWholeSQL(reportSQL);
+ cachedSQL = reportSQL;
+ wholeSQL = reportSQL;
+ List reportCols = getAllColumns();
+ // replace the request parameter specified in the drill down
+ DataColumnType dataColumnRequest = getCrossTabValueColumn();
+ reportSQL = parseReportSQLForDrillDownParams(reportSQL, dataColumnRequest, request);
+
+
+ DataSet ds = null;
+ // try {
+ String dbInfo = getDBInfo();
+ StringBuffer colNames = new StringBuffer();
+ StringBuffer colExtraIdNames = new StringBuffer();
+ StringBuffer colExtraDateNames = new StringBuffer();
+
+
+ for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
+ DataColumnType dc = (DataColumnType) iter.next();
+ //TODO: commented if (dc.isVisible()) {
+ if (colNames.length() > 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) {
+ System.out.println("Drilldown URL " + dc.getDrillDownURL());
+
+ }
+ } // for
+
+ if (reportSQL.toUpperCase().indexOf("GROUP BY ") < 0)
+ colNames.append(colExtraIdNames.toString());
+ colNames.append(colExtraDateNames.toString());
+ //reportSQL = " SELECT ROWNUM rnum, "
+ // + colNames.toString() + " FROM (" + reportSQL + ") ";
+
+ String rSQL = Globals.getLoadCrosstabReportData();
+ rSQL = rSQL.replace("[colNames.toString()]", colNames.toString());
+ rSQL = rSQL.replace("[reportSQL]", reportSQL);
+ reportSQL = rSQL;
+ setWholeSQL(reportSQL);
+ if (crossTabOrderManager == null)
+ crossTabOrderManager = new CrossTabOrderManager(this, userId,request);
+ ds = ConnectionUtils.getDataSet(reportSQL, dbInfo);
+
+ ReportData rd = new ReportData(pageNo, false);
+ ReportFormFields childReportFormFields = null;
+ if(doesReportContainsGroupFormField()) {
+ List reportCols1 = getAllColumns();
+ reportCols = new Vector();
+ outer:
+ for (Iterator iter = reportCols1.iterator(); iter.hasNext();) {
+ DataColumnType dct = (DataColumnType) iter.next();
+ for (int k=0; k<ds.getColumnCount(); k++) {
+ if(dct.getColId().toUpperCase().trim().equals(ds.getColumnName(k).trim())) {
+ reportCols.add(dct);
+ continue outer;
+ }
+ }
+ }
+
+ if (getFormFieldList() != null) {
+ String paramValue = "";
+ for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
+ FormFieldType fft = (FormFieldType) iter.next();
+ if(fft.isGroupFormField()!=null && fft.isGroupFormField().booleanValue()) {
+ paramValue = Utils.oracleSafe(nvl(reportParamValues
+ .getParamValue(fft.getFieldId())));
+ outer:
+ for (Iterator iter1 = reportCols1.iterator(); iter1.hasNext();) {
+ DataColumnType dct = (DataColumnType) iter1.next();
+ if(("["+fft.getFieldName()+ "]").equals(dct.getColName().trim())) {
+ dct.setDisplayName(paramValue);
+ continue outer;
+ }
+ }
+
+
+ }
+ }
+ }
+ }
+
+ int dataColumnIdx = (rd.reportRowHeaderCols.size() + rd.reportColumnHeaderRows.size())-1;
+ DataColumnType dataColumn = getCrossTabValueColumn();
+
+ String columnValue = "";
+
+
+ for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
+ DataColumnType dct = (DataColumnType) iter.next();
+
+ if (nvl(dct.getDrillDownURL()).length() > 0) {
+ childReportFormFields = getChildReportFormFields(request,dct.getDrillDownURL());
+ }
+
+ if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_ROW)) {
+ RowHeaderCol rhc = new RowHeaderCol();
+ rhc.setColumnTitle(dct.getDisplayName());
+ // rhc.setColumnWidth("10%");
+ //rhc.setColumnWidth(dct.getDisplayWidth() + "%");
+ if(nvl(dct.getDisplayWidthInPxls()).length()<=0) {
+ dct.setDisplayWidthInPxls("100px");
+ }
+ if(dct.getDisplayWidthInPxls().endsWith("px"))
+ rhc.setColumnWidth(dct.getDisplayWidthInPxls());
+ else
+ rhc.setColumnWidth(dct.getDisplayWidthInPxls()+"px");
+
+ rhc.setAlignment(dct.getDisplayAlignment());
+ rhc.setDisplayHeaderAlignment(dct.getDisplayHeaderAlignment());
+ rhc.setNowrap(nvl(dataColumn.getNowrap(),"null").equals("false")?"null":nvl(dataColumn.getNowrap(),"null"));
+ rd.reportRowHeaderCols.addRowHeaderCol(rhc);
+ } else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_COLUMN)) {
+ ColumnHeaderRow chr = new ColumnHeaderRow();
+ chr.setAlignment(dct.getDisplayHeaderAlignment());
+ chr.setRowHeight("15");
+ if(nvl(dct.getDisplayWidthInPxls()).length()<=0) {
+ dct.setDisplayWidthInPxls("80px");
+ }
+ if(dct.getDisplayWidthInPxls().endsWith("px"))
+ chr.setDisplayWidth(dct.getDisplayWidthInPxls());
+ else
+ chr.setDisplayWidth(dct.getDisplayWidthInPxls()+"px");
+
+ rd.reportColumnHeaderRows.addColumnHeaderRow(chr);
+ } else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_VALUE)) {
+ columnValue = dct.getColId();
+ } else {
+ if(!dct.getColId().toLowerCase().endsWith("_sort")) {
+ RowHeaderCol rhc = new RowHeaderCol();
+ rhc.setVisible(false);
+ rd.reportRowHeaderCols.addRowHeaderCol(rhc);
+ }
+ }
+ } // for
+
+ //int dataColumnIdx = getCrossTabValueColumnIndex();
+ FormatProcessor formatProcessor = new FormatProcessor(getSemaphoreById(dataColumn
+ .getSemaphoreId()),
+ getReportDefType().equals(AppConstants.RD_SQL_BASED) ? AppConstants.CT_NUMBER
+ : dataColumn.getColType(), dataColumn.getColFormat(), false);
+ List dataList = new ArrayList();
+ /* //fillup all rows based on rowheaders
+ Vector rowHeaders = crossTabOrderManager.getRowHeaderValues();
+ CrossTabColumnValues crossTabRowValues;
+ int size = 0;
+ for (int i = 0; i < rowHeaders.size(); i++) {
+ if((i+1)==rowHeaders.size()) {
+ crossTabRowValues = (CrossTabColumnValues) rowHeaders.get(i);
+ size = crossTabRowValues.getValuesCount();
+ }
+ }
+
+ for (int i = 0; i < size; i++) {
+ dataList.add(new DataRow());
+ }*/
+
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ Vector rValues = new Vector();
+ Vector cValues = new Vector();
+ Vector cValuesSort = new Vector();
+
+ int colIdx = 0;
+ for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
+ try {
+ DataColumnType dct = (DataColumnType) iter.next();
+ if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_ROW))
+ rValues.add(addDataValue(dct, ds.getString(i, dct.getColId())));
+ if (nvl(dct.getCrossTabValue()).trim().length()<=0 && !dct.getColId().toLowerCase().endsWith("_sort"))
+ rValues.add(addDataValue(dct, ds.getString(i, dct.getColId())));
+ if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_COLUMN)) {
+ cValues.add(addDataValue(dct, ds.getString(i, dct.getColId())));
+ if(getColumnById(dct.getColId().toLowerCase()+"_sort")!=null)
+ cValuesSort.add(addDataValue(dct, new Integer(ds.getString(i, dct.getColId()+"_sort")).toString()));
+ }
+ if (dct.isVisible())
+ colIdx++;
+ } catch (ArrayIndexOutOfBoundsException ex ) {continue;}
+ catch (NumberFormatException ex1) {
+ ex1.printStackTrace();
+ continue;
+ }
+ } // for
+
+ DataValue dv = new DataValue();
+ dv.setDisplayValue(ds.getString(i, columnValue));
+ if (nvl(dataColumn.getCrossTabValue()).trim().length()<=0)
+ dv.setVisible(false);
+ dv.setAlignment(dataColumn.getDisplayAlignment());
+ dv.setDisplayTotal(dataColumn.getDisplayTotal());
+ dv.setColName(dataColumn.getColName());
+ dv.setDisplayName(dataColumn.getDisplayName());
+ dv.setColId(dataColumn.getColId());
+ dv.setNowrap(nvl(dataColumn.getNowrap(),"null").equals("false")?"null":nvl(dataColumn.getNowrap(),"null"));
+ /*StringBuffer indentation = new StringBuffer("");
+ if(dataColumn.getIndentation()!=null && dataColumn.getIndentation().intValue()>0) {
+ for (int indent=0; indent < dataColumn.getIndentation(); indent++) {
+ indentation.append("\t");
+ }
+ dv.setNowrap("true");
+ }
+ dv.setIndentation(indentation.toString());*/
+
+ if (nvl(dataColumn.getDrillDownURL()).length() > 0) {
+ if(dv.getDisplayValue().length() > 0) {
+ dv.setDrillDownURL(parseDrillDownURL(i, /* dataColumnIdx, */ds, dataColumn,request, childReportFormFields));
+ dv.setDrillDowninPoPUp(dataColumn.isDrillinPoPUp()!=null?dataColumn.isDrillinPoPUp():false);
+ }
+ if (dv.getDisplayValue().length() == 0) {
+ //dv.setDisplayValue("[NULL]");
+ dv.setDisplayValue("");
+ }
+ } // if
+
+ rd.setDataValue(rValues, cValues, cValuesSort.size()==0?null:cValuesSort, dv, formatProcessor, crossTabOrderManager, dataList);
+ } // for
+ rd.setReportDataList(dataList);
+ /*if (getReportDataSize() < 0)
+ setReportDataSize(rd.getDataRowCount());*/
+
+ /*if (pageNo >= 0)
+ rd.truncateData(pageNo * getPageSize(), (pageNo + 1) * getPageSize() - 1);
+ else {
+ if( downloadLimit != -1)
+ rd.truncateData(0, downloadLimit - 1);
+ else
+ rd.truncateData(0, -1);
+ }*/
+
+ if (colDataTotalsCrosstab == null)
+ colDataTotalsCrosstab = generateDataTotalsCrossTab(AppConstants.CV_COLUMN, userId,request);
+ if (displayColTotals && colDataTotalsCrosstab != null)
+ rd.setColumnDataTotalsCrossTab(colDataTotalsCrosstab, dataColumn
+ .getDisplayAlignment(), getCrossTabDisplayTotal(AppConstants.CV_COLUMN),
+ crossTabOrderManager, dataList);
+
+ if (rowDataTotalsCrosstab == null)
+ rowDataTotalsCrosstab = generateDataTotalsCrossTab(AppConstants.CV_ROW, userId, request);
+ if (displayRowTotals && rowDataTotalsCrosstab != null)
+ rd.setRowDataTotalsCrossTab(rowDataTotalsCrosstab, dataColumn
+ .getDisplayAlignment(), getCrossTabDisplayTotal(AppConstants.CV_ROW),
+ crossTabOrderManager, dataList);
+
+ if (displayColTotals
+ && displayRowTotals
+ && getCrossTabDisplayTotal(AppConstants.CV_COLUMN).equals(
+ getCrossTabDisplayTotal(AppConstants.CV_ROW))) {
+ // Display grand total
+ if (grandTotalCrosstab == null)
+ grandTotalCrosstab = ((CrossTabTotalValue) generateDataTotalsCrossTab("",
+ userId,request).get(0)).getTotalValue();
+ if (grandTotalCrosstab != null)
+ rd.setGrandTotalCrossTab(Utils.truncateTotalDecimals(grandTotalCrosstab),
+ dataColumn.getDisplayAlignment(),
+ getCrossTabDisplayTotal(AppConstants.CV_COLUMN), dataList);
+ } // if
+
+ rd.consolidateColumnHeaders(visualManager);
+ //if (Globals.getMergeCrosstabRowHeadings())
+ // rd.consolidateRowHeaders();
+ //rd.addRowNumbers(pageNo, dataList);
+
+ if (displayColTotals && colDataTotalsCrosstab != null) {
+ String totalLabel = "Total";
+ String colDisplayTotal = getCrossTabDisplayTotal(AppConstants.CV_COLUMN);
+ if (colDisplayTotal.length() > 0
+ && (!colDisplayTotal.equals(AppConstants.TOTAL_SUM_ID)))
+ totalLabel = nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(colDisplayTotal));
+ if (getReportDataSize() > getPageSize())
+ totalLabel += "_nl_(for all pages)";
+
+ //rd.setCrossTabColumnTotalLabel(totalLabel);
+ } // if
+
+ //rd.applyVisibility();
+ //Collections.sort((List)dataList, new DataRowComparable());
+ DataRow drInFor1 = null;
+ Vector<DataValue> v1= null, v2 = null;
+ ArrayList<String> temp = new ArrayList<String>();
+ if (Globals.getMergeCrosstabRowHeadings()) {
+ for (int i = 0; i < dataList.size(); i++) {
+ drInFor1 = (DataRow)dataList.get(i);
+ drInFor1.setRowNum(i+1);
+ v1 = drInFor1.getRowValues();
+ if(i<dataList.size()-1) {
+ v2 = ((DataRow)dataList.get(i+1)).getRowValues();
+ } /*else {
+ v2 = ((DataRow)dataList.get(i-1)).getRowValues();
+ }*/
+ for (int j = 0; j < v1.size(); j++) {
+ if(j==0) {
+ if(v1.get(j).getDisplayValue().length()>0) { // another ArrayList
+ temp = new ArrayList();
+ temp.add(v1.get(j).getDisplayValue());
+ }
+ if(v2!=null && temp.get(j).equals(v2.get(j).getDisplayValue())) {
+ v2.get(j).setDisplayValue("");
+ }
+ }
+ }
+ }
+ }
+ rd.setReportDataList(dataList);
+ if (getReportDataSize() < 0) {
+ //setReportDataSize(rd.getDataRowCount());
+ setReportDataSize(rd.getReportDataList().size());
+ }
+
+ return rd;
+ } // loadCrossTabReportData
+
+
+ public DataValue addDataValue(DataColumnType dataColumn, String columnValue) {
+ DataValue dv = new DataValue();
+ dv.setDisplayValue(columnValue);
+ if (nvl(dataColumn.getCrossTabValue()).trim().length()<=0)
+ dv.setVisible(false);
+ dv.setAlignment(dataColumn.getDisplayAlignment());
+ dv.setDisplayTotal(dataColumn.getDisplayTotal());
+ dv.setColName(dataColumn.getColName());
+ dv.setDisplayName(dataColumn.getDisplayName());
+ dv.setColId(dataColumn.getColId());
+ dv.setNowrap(nvl(dataColumn.getNowrap(),"null").equals("false")?"null":nvl(dataColumn.getNowrap(),"null"));
+ return dv;
+
+ }
+
+ /*private*/ public boolean doesReportContainsGroupFormField() {
+ int flag = 0;
+ if(getFormFieldList()!=null) {
+ for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
+ FormFieldType fft = (FormFieldType) iter.next();
+ if(fft.isGroupFormField()!=null && fft.isGroupFormField().booleanValue()) {
+ flag = 1;
+ break;
+ }
+ }
+ }
+ return (flag ==1);
+ }
+
+ private ReportData loadLinearReportData(int pageNo, String userId, int downloadLimit, HttpServletRequest request, boolean download) throws RaptorException {
+ String action = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action"));;
+
+ String reportSQL = "";
+
+ if(action.endsWith("session")) {
+ reportSQL = getWholeSQL();
+ wholeSQL = reportSQL;
+ } else {
+ reportSQL = generateSQL(reportParamValues, visualManager.getSortByColId(),
+ visualManager.getSortByAscDesc(), userId, request);
+ wholeSQL = reportSQL;
+ setWholeSQL(wholeSQL);
+ }
+ DataSet ds = null;
+ String dbInfo = getDBInfo();
+ ds = ConnectionUtils.getDataSet(wholeSQL, dbInfo);
+ setReportDataSize(ds.getRowCount());
+ //wholeSQL = reportSQL;
+ HttpSession session = request.getSession();
+ //debugLogger.debug(" ******** Download Limit ********* " + downloadLimit + " %%%%%%%%%%PAGE " + pageNo );
+ List reportCols = null;
+ StringBuffer colNames = new StringBuffer();
+
+ if(download && action.endsWith("session")) {
+ reportCols = getAllColumns();
+ 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());
+ }
+
+ }
+ else {
+ String pagedSQL = null; // reportSQL;
+ if (pageNo >= 0)
+ pagedSQL = generatePagedSQL(pageNo, userId, request, false, null);
+ else
+ pagedSQL = generateSubsetSQL(0, downloadLimit, userId, request, false, null);
+ // replace the request parameter specified in the drill down
+ reportCols = getAllColumns();
+ 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());
+ if (dc.isVisible()) {
+ reportSQL = parseReportSQLForDrillDownParams(reportSQL, dc, request);
+ pagedSQL = parseReportSQLForDrillDownParams(pagedSQL, dc, request);
+ }
+ }
+
+ cachedSQL = pagedSQL;
+
+
+ // try {
+ if(doesReportContainsGroupFormField()) {
+ if (pageNo >= 0)
+ pagedSQL = generatePagedSQL(pageNo, userId, request, true, reportParamValues);
+ else
+ pagedSQL = generateSubsetSQL(0, downloadLimit, userId, request, true, reportParamValues);
+ }
+ //check for Group formfield
+ //if groupformfield get columns from sql
+
+ ds = ConnectionUtils.getDataSet(pagedSQL, dbInfo);
+
+ if(doesReportContainsGroupFormField()) {
+ List reportCols1 = getAllColumns();
+ reportCols = new Vector();
+ outer:
+ for (Iterator iter = reportCols1.iterator(); iter.hasNext();) {
+ DataColumnType dct = (DataColumnType) iter.next();
+ for (int k=0; k<ds.getColumnCount(); k++) {
+ if(dct.getColId().toUpperCase().trim().equals(ds.getColumnName(k).trim())) {
+ reportCols.add(dct);
+ continue outer;
+ }
+ }
+ }
+
+ if (getFormFieldList() != null) {
+ String paramValue = "";
+ for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
+ FormFieldType fft = (FormFieldType) iter.next();
+ if(fft.isGroupFormField()!=null && fft.isGroupFormField().booleanValue()) {
+ paramValue = Utils.oracleSafe(nvl(reportParamValues
+ .getParamValue(fft.getFieldId())));
+ outer:
+ for (Iterator iter1 = reportCols1.iterator(); iter1.hasNext();) {
+ DataColumnType dct = (DataColumnType) iter1.next();
+ if(("["+fft.getFieldName()+ "]").equals(dct.getColName().trim())) {
+ dct.setDisplayName(paramValue);
+ continue outer;
+ }
+ }
+
+
+ }
+ }
+ }
+ }
+
+
+ // if ( (remDbInfo!=null) && (!remDbInfo.equals(AppConstants.DB_LOCAL)))
+ // {
+ // Globals.getRDbUtils().setDBPrefix(remDbInfo);
+ // ds = RemDbUtils.executeQuery(pagedSQL);
+ // }
+ // else
+ // ds = DbUtils.executeQuery(pagedSQL);
+ /*
+ * } catch(SQLException e) { throw new
+ * ReportSQLException("[ReportRuntime.loadLinearReportData]
+ * "+e.getMessage(), pagedSQL); }
+ */
+
+ if (getReportDataSize() < 0)
+ if (pageNo < 0)
+ setReportDataSize(ds.getRowCount());
+ else if (ds.getRowCount() <= getPageSize())
+ setReportDataSize(ds.getRowCount());
+ else {
+
+ /*Pattern re1 = Pattern.compile("[Oo][Rr][Dd][Ee][Rr](.*?[^\r\n]*)[Bb][Yy]", Pattern.DOTALL);
+ Pattern re2 = Pattern.compile("[Oo][Rr][Dd][Ee][Rr](.*?[^\r\n]*)[Bb][Yy]((.*?[^\r\n]*)|[\\s]|[^0-9a-zA-Z])\\)", Pattern.DOTALL);
+ Matcher matcher = re1.matcher(reportSQL);
+ Matcher matcher2 = null;
+ int startPoint = reportSQL.length()-30;
+ String startReportSQL = "";
+ String endReportSQL = "";
+ while(reportSQL.indexOf("xid", startPoint)!=-1)startPoint++;
+ if (matcher.find(startPoint)) {
+ startReportSQL = reportSQL.substring(0, reportSQL.indexOf(matcher.group()));
+ endReportSQL = reportSQL.substring(reportSQL.indexOf(matcher.group()));
+ matcher2 = re2.matcher(endReportSQL);
+ if(matcher2.find())
+ endReportSQL = endReportSQL.substring(matcher.group().length()-1);
+ else
+ endReportSQL = "";
+ reportSQL = startReportSQL + endReportSQL;
+ }*/
+ String countSQL = "SELECT count(*) FROM (" + reportSQL + ")"+ (Globals.isPostgreSQL() || Globals.isMySQL()?" AS ":"") +" x ";
+ String dbType = "";
+
+ if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) {
+ try {
+ org.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.portalsdk.analytics.util.RemDbInfo();
+ dbType = remDbInfo.getDBType(dbInfo);
+ if (dbType.equals("DAYTONA") && reportSQL.trim().toUpperCase().startsWith("SELECT")) {
+ Pattern re1 = Pattern.compile("order(.*?[^\r\n]*)by", Pattern.DOTALL);
+ Matcher matcher = re1.matcher(reportSQL);
+ int startPoint = reportSQL.length()-30;
+ while(reportSQL.indexOf("xid", startPoint)!=-1)startPoint++;
+ if (matcher.find(startPoint)) {
+ reportSQL = reportSQL.substring(0, reportSQL.indexOf(matcher.group()));
+ }
+ countSQL = "SELECT count(*) FROM (" + reportSQL + ")"+ (Globals.isPostgreSQL() || Globals.isMySQL()?" AS ":"") +" x";
+ countSQL = countSQL + " ("+ colNames+ ")";
+ } else if (dbType.equals("DAYTONA")) {
+ setReportDataSize(50);
+ }
+ } catch (Exception ex) {
+ throw new RaptorException(ex);
+ }
+ }
+
+ DataSet ds2 = null;
+ // try {
+ if(reportSQL.trim().toUpperCase().startsWith("SELECT")) {
+ ds2 = ConnectionUtils.getDataSet(countSQL, dbInfo);
+ if (ds2.getRowCount() > 0)
+ setReportDataSize(ds2.getInt(0, 0));
+ else
+ throw new RuntimeException(
+ "[ReportRuntime.loadLinearReportData] Unable to load report data size");
+ } else
+ setReportDataSize(50);
+ // if ( (remDbInfo!=null) &&
+ // (!remDbInfo.equals(AppConstants.DB_LOCAL))){
+ // Globals.getRDbUtils().setDBPrefix(remDbInfo);
+ // ds2 = RemDbUtils.executeQuery(countSQL);
+ // }
+ // else
+ // ds2 = DbUtils.executeQuery(countSQL);
+ /*
+ * } catch(SQLException e) { throw new
+ * ReportSQLException("[ReportRuntime.loadLinearReportData size]
+ * "+e.getMessage(), countSQL); }
+ */
+
+
+ } // else
+ }
+ ReportData rd = new ReportData(pageNo, true);
+
+ // 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 = 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(
+ getSemaphoreById(dc.getSemaphoreId()), dc.getColType(), dc
+ .getColFormat(), getReportDefType().equals(
+ AppConstants.RD_SQL_BASED)));
+
+ if (nvl(dc.getDrillDownURL()).length() > 0) {
+ childReportFormFields = getChildReportFormFields(request,AppUtils.getDrillActionURL()+""+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);
+ }
+ }
+ }
+ //}
+
+ String widthInPxls = dc.getDisplayWidthInPxls();
+
+ if(nvl(widthInPxls).endsWith("px"))
+ dc.setDisplayWidthInPxls(widthInPxls);
+ else {
+ widthInPxls = widthInPxls+"px";
+ dc.setDisplayWidthInPxls(widthInPxls+"px");
+ }
+
+ rd.createColumn(dc.getColId(), dc.getDisplayName(), dc.getDisplayWidthInPxls(), dc.getDisplayHeaderAlignment(),
+ visualManager.isColumnVisible(dc.getColId()), visualManager
+ .getSortByColId().equals(dc.getColId()) ? visualManager
+ .getSortByAscDesc() : null, isRuntimeColSortDisabled(), 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(),
+ true, 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
+
+ if(getReportDefType().equals(AppConstants.RD_SQL_BASED_DATAMIN) && pageNo ==0) {
+ /*Vector v = null;
+ try {
+ v = addForecastData(reportSQL);
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ throw new RaptorException (ex);
+ }
+ session.setAttribute("FORECASTED_DATA", v);
+ DataSet dsWhole = ConnectionUtils.getDataSet(wholeSQL, dbInfo);
+ dsWhole.addAll(v);
+ session.setAttribute(AppConstants.RI_CHART_FORECAST_DATA, dsWhole);
+ }
+
+ if(getReportDefType().equals(AppConstants.RD_SQL_BASED_DATAMIN) && session.getAttribute("FORECASTED_DATA")!=null) {
+ Vector vForecastedData = (Vector)session.getAttribute("FORECASTED_DATA");
+ if(vForecastedData.size() > 0)
+ ds.addAll(vForecastedData);*/
+ }
+
+
+ // 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
+ for (int r = 0; r < Math.min(ds.getRowCount(), ((pageNo < 0) ? (downloadLimit == -1?Globals.getFlatFileUpperLimit():Globals.getDownloadLimit() ) : getPageSize())); 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);
+ DataValue dv = new DataValue();
+ dr.addDataValue(dv);
+ dv.setDisplayValue(ds.getString(r, c));
+ dv.setColName(dct.getColName());
+ dv.setColId(dct.getColId());
+ dv.setNowrap(nvl(dct.getNowrap(),"null").equals("false")?"null":nvl(dct.getNowrap(),"null"));
+ 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) {
+ dv.setDrillDownURL(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
+
+ } 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
+ } // for
+
+ //Only if rownumber options is needed
+ //rd.addRowNumbers(pageNo, getPageSize());
+
+ if (colDataTotalsLinear == null) {
+ if(!download && !action.endsWith("session"))
+ colDataTotalsLinear = generateColumnDataTotalsLinear(new ArrayList(reportCols), userId,
+ getDbInfo(),request);
+ if(download && action.endsWith("session"))
+ colDataTotalsLinear = generateColumnDataTotalsLinear(new ArrayList(reportCols), userId,
+ getDbInfo(), getTotalSql());
+ }
+ if (displayColTotals && colDataTotalsLinear != null) {
+ String totalLabel = "Total";
+ if (getReportDataSize() > getPageSize())
+ totalLabel += "<br><font size=1>(for all pages)</font>";
+
+ rd.setColumnDataTotalsLinear(colDataTotalsLinear, totalLabel);
+ } // if
+ // 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 DataRow generateColumnDataTotalsLinear(ArrayList reportCols, String userId,
+ String dbInfo, String reportSQL) throws RaptorException {
+ DataRow dr = null;
+
+ boolean displayColTotals = false;
+ for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
+
+ DataColumnType dct = (DataColumnType) iter.next();
+ if( dct != null ) {
+ if (nvl(dct.getDisplayTotal()).length() > 0) {
+ displayColTotals = true;
+ break;
+ } // if
+ } // if checking dct
+ } // for
+
+ DataSet ds = null;
+ if (displayColTotals) {
+ dr = new DataRow();
+ // ds =
+ // DbUtils.executeQuery(generateTotalSQLLinear(reportParamValues,
+ // userId));
+ ds = ConnectionUtils.getDataSet(reportSQL,
+ dbInfo);
+
+ for (int c = 0; c < reportCols.size(); c++) {
+ DataColumnType dct = (DataColumnType) reportCols.get(c);
+ if ( dct != null ) {
+ DataValue dv = new DataValue();
+
+ String totalValue = "";
+ if (ds != null)
+ totalValue = ds.getString(0, c);
+ if (nvl(dct.getDisplayTotal()).length() > 0
+ && (!dct.getDisplayTotal().equals(AppConstants.TOTAL_SUM_ID)))
+ totalValue = nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(dct
+ .getDisplayTotal()))
+ + ": " + totalValue;
+ dv.setDisplayValue(Utils.truncateTotalDecimals(totalValue));
+
+ dv.setAlignment(dct.getDisplayAlignment());
+ dv.setColName(dct.getColName());
+ dv.setDisplayName(dct.getDisplayName());
+ dv.setColId(dct.getColId());
+ dv.setNowrap(nvl(dct.getNowrap(),"null").equals("false")?"null":nvl(dct.getNowrap(),"null"));
+ 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());
+ dv.setDisplayTotal(dct.getDisplayTotal());
+ dv.setBold(true);
+ dv.setVisible(dct.isVisible());
+ if(dv.isVisible())
+ dr.addDataValue(dv);
+ } // dct check
+ } // for
+ }
+
+ return dr;
+ } // generateColumnDataTotalsLinear
+
+
+ public ReportData loadHiveLinearReportData(String reportSQL, String userId, int downloadLimit, HttpServletRequest request) throws RaptorException {
+ wholeSQL = reportSQL;
+ int countRows = getHiveReportCount(wholeSQL);
+ setReportDataSize(countRows);
+ if(countRows < 1001)
+ wholeSQL += " limit "+ countRows;
+ else
+ wholeSQL += " limit "+ downloadLimit;
+ HttpSession session = request.getSession();
+
+ DataSet ds = null;
+ // try {
+ String dbInfo = getDBInfo();
+
+ List reportCols = getAllColumns();
+ 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());
+ }
+
+ ds = ConnectionUtils.getDataSet(wholeSQL, dbInfo);
+
+ ReportData rd = new ReportData(0, true);
+
+ // 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 = 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(
+ getSemaphoreById(dc.getSemaphoreId()), dc.getColType(), dc
+ .getColFormat(), getReportDefType().equals(
+ AppConstants.RD_SQL_BASED)));
+
+ if (nvl(dc.getDrillDownURL()).length() > 0) {
+ childReportFormFields = 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);
+ }
+ }
+ }
+ //}
+
+ String widthInPxls = dc.getDisplayWidthInPxls();
+
+ if(nvl(widthInPxls).endsWith("px"))
+ dc.setDisplayWidthInPxls(widthInPxls);
+ else {
+ widthInPxls = widthInPxls+"px";
+ dc.setDisplayWidthInPxls(widthInPxls+"px");
+ }
+
+ rd.createColumn(dc.getColId(), dc.getDisplayName(), dc.getDisplayWidthInPxls(), dc.getDisplayHeaderAlignment(),
+ visualManager.isColumnVisible(dc.getColId()), visualManager
+ .getSortByColId().equals(dc.getColId()) ? visualManager
+ .getSortByAscDesc() : null, isRuntimeColSortDisabled(), 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(), "", dc.getDisplayWidthInPxls(), dc.getDisplayHeaderAlignment(),
+ true, 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
+
+ ArrayList reportDataList = new ArrayList();
+ for (int r = 0; r < ds.getRowCount(); 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);
+ DataValue dv = new DataValue();
+ dr.addDataValue(dv);
+ dv.setDisplayValue(ds.getString(r, c));
+ dv.setColName(dct.getColName());
+ dv.setColId(dct.getColId());
+ dv.setNowrap(nvl(dct.getNowrap(),"null").equals("false")?"null":nvl(dct.getNowrap(),"null"));
+ 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) {
+ dv.setDrillDownURL(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
+
+ } 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());
+
+ if (colDataTotalsLinear == null)
+ colDataTotalsLinear = generateColumnDataTotalsLinear(new ArrayList(reportCols), userId,
+ getDbInfo(),request);
+ if (displayColTotals && colDataTotalsLinear != null) {
+ String totalLabel = "Total";
+ if (getReportDataSize() > getPageSize())
+ totalLabel += "<br><font size=1>(for all pages)</font>";
+
+ rd.setColumnDataTotalsLinear(colDataTotalsLinear, totalLabel);
+ } // if
+ // Please note the below function doesn't set the visibility for dv since this is set in this function. - Sundar
+ rd.applyVisibility();
+
+ return rd;
+ } // loadHiveLinearReportData
+
+ //For Hive reports
+ public int getHiveReportCount(String sql) throws RaptorException {
+ //select t from (select count(*) t from (select * from program)x)x1;
+ int count = 0;
+ String countSql = "select t from (select count(*) t from ("+ sql + ")" + (Globals.isPostgreSQL() || Globals.isMySQL() ?" AS ":"") + " x) AS x1";
+
+ DataSet ds = null;
+ // try {
+ String dbInfo = getDBInfo();
+ System.out.println("SQL getReportCount()- " + countSql);
+ try {
+ ds = ConnectionUtils.getDataSet(countSql, dbInfo);
+ int totalRows = 0;
+ String dbType = "";
+ if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) {
+ try {
+ org.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.portalsdk.analytics.util.RemDbInfo();
+ dbType = remDbInfo.getDBType(dbInfo);
+ } catch (Exception ex) {
+ throw new RaptorException(ex);
+ }
+ }
+ if( ds.getRowCount()>0) {
+ count = Integer.parseInt(ds.getString(0,0));
+ }
+ } catch (NumberFormatException ex) {}
+ return count;
+
+ } // getReportCount
+
+
+ /*private*/ public ReportFormFields getChildReportFormFields( HttpServletRequest request, String URL ) throws RaptorException {
+ String childReportID = getReportID(URL);
+
+ ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, childReportID,
+ false, 1);
+
+ ReportFormFields ddReportFormFields = ddRr.getReportFormFields();
+ return ddReportFormFields;
+ }
+
+ private String getReportID(String URL) {
+ URL = nvl(URL);
+ int pos = URL.toLowerCase().indexOf("c_master=")+9;
+ String reportID = "";
+ if(URL.toLowerCase().indexOf("&", pos)!=-1)
+ reportID = URL.substring(pos, URL.toLowerCase().indexOf("&", pos));
+ else
+ reportID = URL.substring(pos);
+ return reportID;
+
+ }
+ /*private*/ public String parseDrillDownURL(int rowIdx, /* int colIdx, */DataSet ds, DataColumnType dct, HttpServletRequest request, ReportFormFields ddReportFormFields)
+ throws RaptorException {
+ Vector viewActions = DataCache.getDataViewActions();
+ javax.servlet.http.HttpSession session = request.getSession();
+
+ StringBuffer dUrl = new StringBuffer();
+
+ //String childReportID = getReportID(dct.getDrillDownURL());
+
+ //ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, childReportID,
+ // false, 1);
+
+ //ReportFormFields ddReportFormFields = ddRr.getReportFormFields();
+
+ boolean isViewAction = false;
+ int flag = 0;
+ String requestParam ="";
+ for (int k = 0; k < viewActions.size(); k++)
+ if (dct.getDrillDownURL().equals(
+ AppUtils.getBaseActionURL() + ((String) viewActions.get(k))))
+ isViewAction = true;
+ if (isViewAction) {
+ // Drill-down to record details
+ String param = nvl(dct.getDrillDownParams()); // i.e.
+ // "c_master=[bo1.RECID$]"
+ param = param.substring(AppUtils.getBaseActionParam().length() + 1,
+ param.length() - 1); // i.e. "bo1.RECID$"
+ param = param.replace('.', '_'); // i.e. "bo1.RECID$"
+
+ dUrl.append(AppUtils.getBaseActionParam());
+ dUrl.append(java.net.URLEncoder.encode(ds.getString(rowIdx, param.toLowerCase())));
+ } else {
+ // Drill-down to another report
+ // Replacing col ids with values
+ String param = nvl(dct.getDrillDownParams());
+ while (param.indexOf('[') >= 0) {
+ int startIdx = param.indexOf('[');
+ int endIdx = param.indexOf(']');
+ StringBuffer sb = new StringBuffer();
+ if(startIdx>endIdx) {
+ if (endIdx < param.length() - 1)
+ sb.append(param.substring(endIdx + 1));
+ param = sb.toString();
+ continue;
+ }
+ if (startIdx > 0)
+ sb.append(param.substring(0, startIdx));
+
+ if (param.charAt(startIdx + 1) == '!') {
+ // Parameter is a form field value
+ String fieldId = param.substring(startIdx + 2, endIdx);
+ String fieldValue = (String) reportParamValues.get(fieldId);
+
+ sb.append(java.net.URLEncoder.encode(nvl(fieldValue)));
+ //TODO Add a else if condition to check whether the param is from request Param
+ //TODO make a unique symbol like #
+ }else if (param.charAt(startIdx + 1) == '#') {
+ flag = 1;
+ String fieldId = param.substring(startIdx + 2, endIdx);
+ String fieldValue = request.getParameter(fieldId);
+ sb.append(java.net.URLEncoder.encode(nvl(fieldValue)));
+
+ }else {
+ // Parameter is a column value
+ String fieldValue = "";
+ String colValue = null;
+ String colId = null;
+ if (param.indexOf('!') < 0 || param.indexOf('!') > endIdx)
+ colId = param.substring(startIdx + 1, endIdx);
+ else {
+ // Need to use NVL(column, form field)
+ colId = param.substring(startIdx + 1, param.indexOf('!'));
+
+ String fieldId = param.substring(param.indexOf('!') + 1, endIdx);
+ FormField ff = getFormField(fieldId);
+ if (ff.getFieldType().equals(FormField.FFT_TEXTAREA)) {
+ fieldValue = reportParamValues.getParamValueforTextAreaDrilldown(fieldId);
+ } else
+ fieldValue = (String) reportParamValues.get(fieldId);
+ } // else
+
+ DataColumnType column = getColumnById(colId);
+ String columnName = "";
+ int groupColumn = 0;
+ int groupMatch = 0;
+ if(column.getColName().startsWith("[")) {
+ groupColumn = 1;
+ columnName = column.getDisplayName();
+ for(ddReportFormFields.resetNext(); ddReportFormFields.hasNext(); ) {
+ FormField ff = ddReportFormFields.getNext();
+ if(ff.getFieldDisplayName().toLowerCase().equals(columnName.toLowerCase())) {
+ groupMatch = 1;
+ sb.delete(sb.lastIndexOf("&")+1, sb.length());
+ sb.append(ff.getFieldName()+"=");
+ }
+ }
+ }
+ if (groupColumn == 0 || (groupColumn == 1 && groupMatch == 1)) {
+ String dependsOn = column.getDependsOnFormField();
+ if(nvl(dependsOn).length()>0)
+ System.out.println("DependsOn " + dependsOn);
+ if (column != null) {
+ // if (column.getColType().equals(AppConstants.CT_DATE))
+ //if (!nvl(column.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT)
+ // .equals(AppConstants.DEFAULT_DATE_FORMAT))
+ // Use extra column instead
+ //commented out below line usually for Visual
+ //colId += AppConstants.DD_COL_EXTENSION;
+ colValue = ds.getString(rowIdx, colId.toLowerCase());
+ // if SQL-Based and drill-down param is a date, decode
+ // it to the expected Oracle format **/
+ if (getReportDefType().equals(AppConstants.RD_SQL_BASED))
+ if (!getColumnNoParseDateFlag(column))
+ if (ReportParamDateValueParser.isDateParam(colValue))
+ colValue = ReportParamDateValueParser
+ .formatDateParamValue(colValue);
+ } // if
+
+ String suppressValues = "|" + nvl(dct.getDrillDownType()) + "|";
+ if (suppressValues.length() > 2
+ && suppressValues.indexOf("|" + colValue + "|") >= 0)
+ // Parameter value is suppressed and not passed to the
+ // drill-down report
+ colValue = null;
+
+ sb.append(java.net.URLEncoder.encode(nvl(colValue, fieldValue)));
+ } else {
+ sb.delete(sb.lastIndexOf("&")+1, sb.length());
+ }
+ } // else
+
+ if (endIdx < param.length() - 1)
+ sb.append(param.substring(endIdx + 1));
+ param = sb.toString();
+ } // while
+ if(Globals.getPassRequestParamInDrilldown()) {
+ if(param.indexOf('#') < 0) {
+ String[] reqParameters = Globals.getRequestParams().split(",");
+ String[] sessionParameters = Globals.getSessionParams().split(",");
+ for (int i = 0; i < reqParameters.length; i++) {
+ if(request.getParameter(reqParameters[i])!=null) {
+ if(!reqParameters[i].toUpperCase().startsWith("FF")){
+ if(param.length()>0) {
+ param += "&" + reqParameters[i]+"="
+ + request.getParameter(reqParameters[i]);
+ } else {
+ param += "&" + reqParameters[i]+"="
+ + request.getParameter(reqParameters[i]);
+
+ }
+ }
+ }
+ }
+ for (int i = 0; i < sessionParameters.length; i++) {
+ if(session.getAttribute(sessionParameters[i].toUpperCase())!=null) {
+ if(!sessionParameters[i].toUpperCase().startsWith("FF")){
+ if(param.length()>0) {
+ param += "&" + sessionParameters[i].toUpperCase()+"="
+ + (String)session.getAttribute(sessionParameters[i].toUpperCase());
+ } else {
+ param += "&" + sessionParameters[i].toUpperCase()+"="
+ + (String)session.getAttribute(sessionParameters[i].toUpperCase());
+
+ }
+ }
+ } else {
+ param += "&" + sessionParameters[i].toUpperCase()+"="
+ + (String)session.getAttribute(sessionParameters[i]);
+
+ }
+ }
+
+ }
+ }
+
+ dUrl.append(param.toString());
+ dUrl.append("&");
+ dUrl.append(AppConstants.RI_DISPLAY_CONTENT);
+ dUrl.append("=Y");
+ dUrl.append("&");
+ if(dct.isDrillinPoPUp()==null || (!dct.isDrillinPoPUp().booleanValue())) {
+ dUrl.append(AppConstants.RI_SHOW_BACK_BTN);
+ dUrl.append("=Y");
+ dUrl.append("&");
+ }
+ dUrl.append(AppConstants.DRILLDOWN_INDEX);
+ int index = Integer.parseInt(nvl(AppUtils.getRequestValue(request, AppConstants.DRILLDOWN_INDEX), "0"));
+ /*
+ int form_index = Integer.parseInt(nvl(AppUtils.getRequestValue(request, AppConstants.FORM_DRILLDOWN_INDEX), "0"));
+ index = index>0 ? --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));*/
+
+ dUrl.append("=" + AppUtils.getRequestNvlValue(request, AppConstants.DRILLDOWN_INDEX));
+
+ //TODO Add a if condition to check whether the param is request Param
+ } // if
+
+ if (dUrl.length() > 0)
+ dUrl.insert(0, ((dct.getDrillDownURL()).indexOf('&') > 0) ? '&' : '&');
+ dUrl.insert(0, AppUtils.getDrillActionURL()+dct.getDrillDownURL());
+
+ //debugLogger.debug(" [[[[[[[[[[[[[[[[ " + dUrl);
+
+ return dUrl.toString();
+ } // parseDrillDownURL
+
+ /** *********************************************************************************** */
+
+ public DataRow generateColumnDataTotalsLinear(ArrayList reportCols, String userId,
+ String dbInfo, HttpServletRequest request) throws RaptorException {
+ DataRow dr = null;
+
+ displayColTotals = false;
+ for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
+
+ DataColumnType dct = (DataColumnType) iter.next();
+ if( dct != null ) {
+ if (nvl(dct.getDisplayTotal()).length() > 0) {
+ displayColTotals = true;
+ break;
+ } // if
+ } // if checking dct
+ } // for
+
+ DataSet ds = null;
+ if (displayColTotals) {
+ dr = new DataRow();
+ // ds =
+ // DbUtils.executeQuery(generateTotalSQLLinear(reportParamValues,
+ // userId));
+ ds = ConnectionUtils.getDataSet(generateTotalSQLLinear(reportParamValues, userId,request),
+ dbInfo);
+
+ for (int c = 0; c < reportCols.size(); c++) {
+ DataColumnType dct = (DataColumnType) reportCols.get(c);
+ if ( dct != null ) {
+ DataValue dv = new DataValue();
+ if(dv.isVisible())
+ dr.addDataValue(dv);
+
+ String totalValue = "";
+ if (ds != null)
+ totalValue = ds.getString(0, c);
+ if (nvl(dct.getDisplayTotal()).length() > 0
+ && (!dct.getDisplayTotal().equals(AppConstants.TOTAL_SUM_ID)))
+ totalValue = nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(dct
+ .getDisplayTotal()))
+ + ": " + totalValue;
+ dv.setDisplayValue(Utils.truncateTotalDecimals(totalValue));
+
+ dv.setAlignment(dct.getDisplayAlignment());
+ dv.setColName(dct.getColName());
+ dv.setDisplayName(dct.getDisplayName());
+ dv.setColId(dct.getColId());
+ dv.setNowrap(nvl(dct.getNowrap(),"null").equals("false")?"null":nvl(dct.getNowrap(),"null"));
+ 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());
+ dv.setDisplayTotal(dct.getDisplayTotal());
+ dv.setBold(true);
+ } // dct check
+ } // for
+ }
+
+ return dr;
+ } // generateColumnDataTotalsLinear
+
+ private Vector generateDataTotalsCrossTab(String rowColPos, String userId, HttpServletRequest request)
+ throws RaptorException {
+ String sql = getWholeSQL();
+ Vector dataTotals = new Vector();
+
+ boolean displayTotals = ((rowColPos.length() == 0) || (getCrossTabDisplayTotal(
+ rowColPos).length() > 0));
+ if (rowColPos.equals(AppConstants.CV_COLUMN))
+ displayColTotals = displayTotals;
+ else if (rowColPos.equals(AppConstants.CV_ROW))
+ displayRowTotals = displayTotals;
+
+ if (displayTotals) {
+ // DataSet ds =
+ // DbUtils.executeQuery(generateTotalSQLCrossTab(reportParamValues,
+ // rowColPos, userId));
+ String executeSql = generateTotalSQLCrossTab(
+ sql, rowColPos, userId, request, reportParamValues);
+ DataSet ds = ConnectionUtils.getDataSet(executeSql, getDbInfo());
+
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ Vector headerValues = new Vector();
+ String totalValue = null;
+
+ int cPos = 0;
+ for (Iterator iter = getAllColumns().iterator(); iter.hasNext();) {
+ DataColumnType dct = (DataColumnType) iter.next();
+
+ if (rowColPos.length() > 0
+ && nvl(dct.getCrossTabValue()).equals(rowColPos)) {
+ DataValue dataValue = new DataValue();
+ dataValue.setBold(true);
+ dataValue.setAlignment("center");
+ dataValue.setDisplayValue(ds.getString(i, cPos++));
+ headerValues.add(dataValue);
+
+ //headerValues.add(ds.getString(i, cPos++));
+ }
+ else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_VALUE))
+ totalValue = ds.getString(i, cPos++);
+ } // for
+
+ dataTotals.add(new CrossTabTotalValue(headerValues, Utils
+ .truncateTotalDecimals(totalValue)));
+ } // for
+ } // if
+
+ return dataTotals;
+ } // generateDataTotalsCrossTab
+
+ /** *********************************************************************************** */
+
+ public void hideColVisual(String colId) {
+ visualManager.hideColumn(colId);
+ if (pageDataCache != null)
+ pageDataCache.columnVisualShowHide(colId, false);
+ } // hideColVisual
+
+ public void showColVisual(String colId) {
+ visualManager.showColumn(colId);
+ if (pageDataCache != null)
+ pageDataCache.columnVisualShowHide(colId, true);
+ } // showColVisual
+
+ public void sortColVisual(String colId) {
+ visualManager.setSortByColumn(colId);
+ resetCache(true);
+
+ pageDataCache = null;
+ cachedPageNo = -1;
+ } // sortColVisual
+
+ /** *********************************************************************************** */
+
+ public String generateDistinctValuesSQL(DataColumnType dct, String userId, HttpServletRequest request) throws RaptorException {
+ return super.generateDistinctValuesSQL(reportParamValues, dct, userId, request);
+ } // generateDistinctValuesSQL
+
+ public String getDbInfo() {
+ return this.cr.getDbInfo();
+ }
+
+ private String fixSQL(StringBuffer sql) {
+ int pos = 0;
+ int pos_f_format = 0;
+ int pos_t_format = 0;
+ int pos_alias = 0;
+ String format = "";
+ String alias = null;
+ if(sql.indexOf("SELECT", 7)!= -1) {
+ pos = sql.indexOf("SELECT", 7);
+ if(sql.indexOf("TO_CHAR", pos)!= -1){
+ pos = sql.indexOf("TO_CHAR", pos);
+ if(sql.indexOf("999",pos)!= -1) {
+ pos = sql.indexOf("999",pos);
+ pos_f_format = sql.lastIndexOf(", '", pos);
+ if(pos_f_format == -1 || (pos - pos_f_format > 10)) {
+ pos_f_format = sql.lastIndexOf(",'", pos);
+ pos_f_format -= 1;
+ }
+ pos = pos_f_format;
+ if(sql.indexOf("')", pos)!= -1) {
+ pos_t_format = sql.indexOf("')", pos);
+ //debugLogger.debug("pos_t - " + pos_t_format + " " + pos);
+ if(pos_t_format == -1 || (pos_t_format - pos > 20)) {
+ pos_t_format = sql.indexOf("' )", pos);
+ pos_t_format += 3;
+ }
+ else if (pos_t_format != -1)
+ pos_t_format += 2;
+ format = sql.substring(pos_f_format+3, pos_t_format);
+ //alias = sql.substring(pos_t_format+3, pos_t_format+6);
+ pos_alias = sql.indexOf(" ", pos_t_format);
+ alias = sql.substring(pos_alias+1, pos_alias+4);
+ }
+ }
+ }
+
+ if(sql.indexOf(alias)!=-1) {
+ pos = sql.indexOf(alias);
+ //debugLogger.debug(pos + " " + alias.length()+1 + "\n" + sql);
+ sql.delete(pos,pos+4);
+ sql.insert(pos, "TO_NUMBER("+alias+", '"+format+"')),'"+ format + "')");
+ pos = sql.lastIndexOf("SUM", pos);
+ if(pos==-1)
+ pos = sql.lastIndexOf("AVG", pos);
+ else if (pos==-1)
+ pos = sql.lastIndexOf("COUNT", pos);
+ else if (pos == -1)
+ pos = sql.lastIndexOf("STDDEV", pos);
+ else if (pos == -1)
+ pos = sql.lastIndexOf("VARIANCE", pos);
+ sql.insert(pos, "TO_CHAR (");
+ }
+
+ }
+
+ //debugLogger.debug("Alias|" + alias + "| Format " + format);
+ //debugLogger.debug(sql.toString());
+ return sql.toString();
+ } // FixSQL
+
+ public String parseReportSQL(String sql) throws RaptorException {
+ StringBuffer parsedSQL = new StringBuffer();
+
+ Vector updatedReportCols = new Vector();
+
+ curSQLParsePos = 0;
+ int lastParsePos = curSQLParsePos;
+ String lastToken = null;
+ logger.debug(EELFLoggerDelegate.debugLogger, ("Flat File parseReportSQL ******* SQL " + sql));
+ sql = sql.replaceAll("([\\s]*\\() (?!FROM)", "(");
+ sql = sql.replaceAll("[\\s]*\\)", ")");
+ //sql = sql.replaceAll("[dD][eE][cC][oO][dD][eE] ", "decode");
+ //sql = sql.replaceAll("[\\s]*\\(", "(");
+ //sql = replaceNewLine(sql, "decode ", "decode");
+ //sql = replaceNewLine(sql, "DECODE ", "decode");
+ //sql = replaceNewLine(sql, "Decode ", "decode");
+
+ String nextToken = getNextSQLParseToken(sql, true);
+ String dbInfo = getDbInfo();
+ boolean isCYMBALScript = false;
+ if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) {
+ try {
+ org.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.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) {
+ //System.out.println("LastToken " + lastToken + " NextToken " + nextToken);
+
+
+ if (parsedSQL.length() == 0) {
+ if (nextToken.toUpperCase().equals("SELECT"))
+ parsedSQL.append("SELECT ");
+ else
+ throw new org.onap.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.onap.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 {
+ //System.out.println("Next Token " + nextToken);
+ 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 {
+ //System.out.println("Next Token " + nextToken + " is Here" + " Last Token " + lastToken);
+ 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);
+ //System.out.println(" ********** " + token + " " + lastToken);
+ if (!token.toUpperCase().equals("FROM"))
+ throw new org.onap.portalsdk.analytics.error.ValidationException(
+ "|FROM keyword or a comma expected after [" + nextToken
+ + "].");
+ //System.out.println("Next Token " + 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
+ nextToken = getNextCYMBALSQLParseToken(sql, true);
+ Pattern re = null;
+ Matcher matcher = null;
+ String extracted = null;
+ while (nextToken.length() > 0) {
+ if (lastToken == null) lastToken = nextToken;
+
+ if( lastToken.toUpperCase().equals("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()-2);
+ StringTokenizer sToken = new StringTokenizer(extracted);
+ while(sToken.hasMoreTokens()) {
+ updatedReportCols.add(getParseSQLDataColumn("", sToken.nextToken(),
+ new StringBuffer(""), updatedReportCols, true));
+ }
+ }
+
+ }
+
+ }
+ lastToken = nextToken;
+ nextToken = getNextCYMBALSQLParseToken(sql, true);
+ }
+ }
+
+ if (updatedReportCols.size() == 0)
+ throw new org.onap.portalsdk.analytics.error.ValidationException(
+ "The SQL statement must have at least one column in the SELECT clause.");
+
+
+ return parsedSQL.toString();
+
+ } // 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);
+ else break;
+ } // for
+
+ return nextToken.toString();
+ } // getNextSQLParseToken
+
+ 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 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.onap.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); // ???
+
+ 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
+ } // 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
+
+ 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*/ public String parseReportSQLForDrillDownParams(String reportSQL, DataColumnType dataColumnRequest, HttpServletRequest request){
+ String param = nvl(dataColumnRequest.getDrillDownParams());
+ String sql = reportSQL;
+ int pos = 0;
+ while (param.indexOf('[', pos) >= 0) {
+ int startIdx = param.indexOf('[',pos);
+ int endIdx = param.indexOf(']',startIdx+1);
+ pos = startIdx+1;
+ StringBuffer sb = new StringBuffer();
+ if (startIdx > 0)
+ sb.append(param.substring(0, startIdx));
+ else break;
+
+ if (param.charAt(startIdx + 1) == '#') {
+ // Parameter is a form field value
+ String fieldId = param.substring(startIdx + 2, endIdx);
+ String fieldValue = request.getParameter(fieldId);
+ sql = Utils.replaceInString(sql, "[" + fieldId.toUpperCase()+"]", fieldValue );
+ }
+ }
+ return sql;
+ }
+
+public List getMapMarkers(ReportData rd, org.onap.portalsdk.analytics.xmlobj.ReportMap xmlmap){
+
+ ArrayList markers = new ArrayList();
+ int rNum = 0;
+ HashMap colHash = new HashMap();
+
+ for(rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext(); rNum++) {
+ DataRow dr = rd.reportDataRows.getNext();
+ for(dr.resetNext(); dr.hasNext(); ) {
+ DataValue dv = dr.getNext();
+ colHash.put(dv.getColId(), dv.getDisplayValueLinkHtml());
+ }
+
+ for (int i = 0; i < xmlmap.getMarkers().size(); i ++){
+ Marker marker = new Marker("", "", "");
+ org.onap.portalsdk.analytics.xmlobj.Marker m = (org.onap.portalsdk.analytics.xmlobj.Marker) xmlmap.getMarkers().get(i);
+ String address = (String) colHash.get(m.getAddressColumn());
+ String data = (String) colHash.get(m.getDataColumn());
+ marker.setAddress(address);
+ if (xmlmap.getAddAddressInDataYN() != null && xmlmap.getAddAddressInDataYN().equals("Y")){
+ marker.setData(address + "<br/>" + data);
+ }
+ else{
+ marker.setData(data);
+ }
+ marker.setColor(m.getMarkerColor());
+ markers.add(marker);
+ System.out.println("%%%%%%%%%%%% marker is : " + address + data);
+ }
+
+ }
+
+ return markers;
+ }
+
+
+
+ public ReportParamValues getReportParamValues() {
+ return reportParamValues;
+ }
+
+ public String getFormFieldFilled(String title) {
+ if( getFormFieldList()!=null && reportParamValues!=null && nvl(title).length()>0) {
+ 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)));
+ title = Utils.replaceInString(title, fieldDisplay, nvl(
+ paramValue, ""));
+ }
+ }
+ }
+ return title;
+ }
+
+ public synchronized Object clone() {
+ try {
+ return super.clone();
+ } catch (CloneNotSupportedException e) {
+ // this shouldn't happen, since we are Cloneable
+ throw new InternalError("Cloning throws error.");
+ }
+ }
+
+ public VisualManager getVisualManager() {
+ return visualManager;
+ }
+
+ public String getReportSQLWithRowNum(String _orderBy, boolean asc) {
+ String sql = getWholeSQL();
+ int closeBracketPos = 0;
+ // Added reportSQLOnlyFirstPart which has Column information with Rownum
+ return nvl(getReportSQLOnlyFirstPart()) + " " + sql + ") x ";
+
+ }
+
+ public int getDisplayMode() {
+ return DISPLAY_MODE;
+ }
+
+ public void setDisplayMode(int mode) {
+ DISPLAY_MODE = mode;
+ }
+
+ public int getDateOption() {
+ return DATE_OPTION;
+ }
+
+ public void setDateOption(int dateOption) {
+ DATE_OPTION = dateOption;
+ }
+
+ public boolean isDisplayColTotals() {
+ return displayColTotals;
+ }
+
+ public void setDisplayColTotals(boolean displayColTotals) {
+ this.displayColTotals = displayColTotals;
+ }
+
+ public boolean isDisplayRowTotals() {
+ return displayRowTotals;
+ }
+
+ public void setDisplayRowTotals(boolean displayRowTotals) {
+ this.displayRowTotals = displayRowTotals;
+ }
+
+
+ private boolean 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
+
+ return visibleColExist;
+ } // canPersistLinearReport
+
+ public void persistLinearReport(HttpServletRequest request)
+ throws RaptorException {
+ if (!canPersistLinearReport())
+ return;
+
+ Connection connection = null;
+ try {
+ String userID = AppUtils.getUserID(request);
+ String reportXML = marshal();
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report " + reportID
+ + " XML marshalled succesfully"));
+
+ // Update report
+ verifySQLBasedReportAccess(request);
+ reportSecurity.reportUpdate(request);
+ connection = DbUtils.startTransaction();
+ ReportLoader.updateCustomReportRec(connection, this, reportXML);
+ ReportLoader.createReportLogEntry(connection, reportID, userID,
+ AppConstants.RLA_UPDATE, "", "");
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] DB update report "
+ + reportID + " succesfull"));
+ DbUtils.commitTransaction(connection);
+ } catch (RaptorException e) {
+ e.printStackTrace();
+ DbUtils.rollbackTransaction(connection);
+ throw e;
+ } finally {
+ DbUtils.clearConnection(connection);
+ }
+ } // persistLinearReport
+
+ public void persistDashboardReport(HttpServletRequest request)
+ throws RaptorException {
+
+ Connection connection = null;
+ try {
+ String userID = AppUtils.getUserID(request);
+ String reportXML = marshal();
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report " + reportID
+ + " XML marshalled succesfully"));
+
+ // Update report
+ verifySQLBasedReportAccess(request);
+ reportSecurity.reportUpdate(request);
+ connection = DbUtils.startTransaction();
+ ReportLoader.updateCustomReportRec(connection, this, reportXML);
+ ReportLoader.createReportLogEntry(connection, reportID, userID,
+ AppConstants.RLA_UPDATE, "", "");
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] DB update report "
+ + reportID + " succesfull"));
+ DbUtils.commitTransaction(connection);
+ } catch (RaptorException e) {
+ e.printStackTrace();
+ DbUtils.rollbackTransaction(connection);
+ throw e;
+ } finally {
+ DbUtils.clearConnection(connection);
+ }
+ } // persistDashboardReport
+ public String getTotalSql() {
+ return totalSql;
+ }
+
+ public void setTotalSql(String totalSql) {
+ this.totalSql = totalSql;
+ }
+
+ public void setTriggerFormFieldCheck( ReportFormFields FormFieldList, FormField selectedFormField) {
+
+ for (Iterator iter = getReportFormFields().iterator(); iter.hasNext();) {
+ FormField ff = (FormField) iter.next();
+ if(!ff.getFieldName().equals(selectedFormField.getFieldName())) {
+ if(nvl(ff.getBaseSQL()).length()>0 && ff.getBaseSQL().indexOf("["+selectedFormField.getFieldDisplayName() +"]")!= -1) {
+ selectedFormField.setTriggerOtherFormFields(true);
+ }
+
+ }
+ }
+
+ }
+
+ public void setTriggerThisFormFieldCheck( ReportFormFields FormFieldList, FormField selectedFormField) {
+
+ String sql = nvl(selectedFormField.getBaseSQL()).length()>0 ? selectedFormField.getBaseSQL():"";
+ for (Iterator iter = getReportFormFields().iterator(); iter.hasNext();) {
+ FormField ff = (FormField) iter.next();
+ if(!ff.getFieldName().equals(selectedFormField.getFieldName())) {
+ if(sql.indexOf("["+ff.getFieldDisplayName() +"]")!= -1) {
+ selectedFormField.setTriggerThisFormfield(true);
+ break;
+ }
+
+ }
+ }
+
+ }
+
+ private boolean isAllowEdit(HttpServletRequest request) {
+ boolean allowEdit = false;
+ String userId = AppUtils.getUserID(request);
+ try {
+ if( AppUtils.isAdminUser(request) || AppUtils.isSuperUser(request) ) {
+ allowEdit = true;
+ } else {
+ if(getOwnerID().equals(userId)) allowEdit = true;
+ else allowEdit = false;
+ }
+ } catch (RaptorException ex) {
+ allowEdit = false;
+ }
+ return allowEdit;
+ }
+ public ReportJSONRuntime createReportJSONRuntime(HttpServletRequest request, ReportData rd) {
+ String userId = AppUtils.getUserID(request);
+ ObjectMapper mapper = new ObjectMapper();
+ ReportJSONRuntime reportJSONRuntime = new ReportJSONRuntime();
+ reportJSONRuntime.setReportTitle(getReportTitle());
+ //reportJSONRuntime.setReportSubTitle(getReportSubTitle());
+ reportJSONRuntime.setReportID(getReportID());
+ reportJSONRuntime.setReportDescr(getReportDescr());
+ reportJSONRuntime.setReportName(getReportName());
+ reportJSONRuntime.setReportSubTitle(getReportSubTitle());
+ reportJSONRuntime.setAllowSchedule(isAllowSchedule());
+ reportJSONRuntime.setAllowEdit(isAllowEdit(request));
+ reportJSONRuntime.setColIdxTobeFreezed(getFrozenColumnId());
+ reportJSONRuntime.setNumFormCols(getNumFormColsAsInt());
+ //back button url
+ reportJSONRuntime.setBackBtnURL("");
+ String chartType = getChartType();
+ boolean displayChart = (nvl(chartType).length()>0)&&getDisplayChart();
+ boolean displayChartWizard = getDisplayChart();
+ reportJSONRuntime.setChartAvailable(displayChart);
+ reportJSONRuntime.setChartWizardAvailable(displayChartWizard);
+ reportJSONRuntime.setDisplayData(!isDisplayOptionHideData());
+ reportJSONRuntime.setDisplayForm(!isDisplayOptionHideForm());
+ reportJSONRuntime.setHideFormFieldsAfterRun(isHideFormFieldAfterRun());
+ reportJSONRuntime.setDisplayExcel(!isDisplayOptionHideExcelIcons());
+ reportJSONRuntime.setDisplayPDF(!isDisplayOptionHidePDFIcons());
+ ArrayList<IdNameValue> formFieldValues = new ArrayList<IdNameValue>();
+ ArrayList<FormFieldJSON> formFieldJSONList = new ArrayList<FormFieldJSON>();
+ if(getReportFormFields()!=null) {
+ formFieldJSONList = new ArrayList<FormFieldJSON>(getReportFormFields().size());
+ for (Iterator iter = getReportFormFields().iterator(); iter.hasNext();) {
+ formFieldValues = new ArrayList<IdNameValue>();
+ FormField ff = (FormField) iter.next();
+ ff.setDbInfo(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.setVisible(ff.isVisible());
+ //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();
+ setTriggerFormFieldCheck( getReportFormFields(), ff);
+ ffJSON.setTriggerOtherFormFields(ff.isTriggerOtherFormFields());
+ SQL = parseAndFillReq_Session_UserValues(request, SQL, userId);
+ SQL = parseAndFillWithCurrentValues(request, SQL, ff);
+ String defaultSQL = lu.getDefaultSQL();
+ defaultSQL = parseAndFillReq_Session_UserValues(request, defaultSQL, userId);
+ defaultSQL = parseAndFillWithCurrentValues(request, defaultSQL, 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);
+ } else if (AppUtils.nvl(ff.getDefaultValue()).length()>0) {
+ if(ff.getDefaultValue().equals(value.getId())) {
+ 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 {
+ setTriggerFormFieldCheck( getReportFormFields(), ff);
+ ffJSON.setTriggerOtherFormFields(ff.isTriggerOtherFormFields());
+ 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);
+ } else if (AppUtils.nvl(ff.getDefaultValue()).length()>0) {
+ IdNameValue value = new IdNameValue(ff.getDefaultValue(), ff.getDefaultValue(), true, false);
+ formFieldValues.add(value);
+ }
+ }
+ if(!ff.hasPredefinedList) {
+ if(oldSQL != null && !oldSQL.equals("")) {
+ ((IdNameSql)lookup).setSQL(oldSQL);
+ }
+ }
+
+
+
+ ffJSON.setFormFieldValues(formFieldValues);
+ formFieldJSONList.add(ffJSON);
+ } // for
+ }
+ reportJSONRuntime.setFormFieldList(formFieldJSONList);
+ //reportJSONRuntime.setReportDataColumns(get);
+ int count = 0;
+ Map<String,Object> dvJSON = null;
+ if(rd!=null) {
+ count = 0;
+ reportJSONRuntime.setTotalRows(getReportDataSize());
+ ArrayList<ColumnHeader> colList = new ArrayList<ColumnHeader>();
+ ArrayList<Map<String,Object>> reportDataRows = new ArrayList<Map<String,Object>>();
+ for(rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext(); ) {
+ count++;
+ ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
+ for(chr.resetNext(); chr.hasNext(); ) {
+ colList.add(chr.getNext());
+ }
+ }
+ if(getReportDataSize() > 0) {
+ count = 0;
+ for(rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext(); count++) {
+ dvJSON = new HashMap<String,Object>();
+ DataRow dr = rd.reportDataRows.getNext();
+ for(dr.resetNext(); dr.hasNext(); ) {
+ DataValue dv = dr.getNext();
+ try {
+ dvJSON.put(dv.getColId(), dv);
+ } catch (Exception ex) {
+ ex.printStackTrace();
+
+ }
+ }
+ reportDataRows.add(dvJSON);
+ }
+ }
+ reportJSONRuntime.setReportDataColumns(colList);
+ reportJSONRuntime.setReportDataRows(reportDataRows);
+ //reportJSONRuntime.setSqlWhole(getWholeSQL());
+ reportJSONRuntime.setPageSize(getPageSize());
+
+ }
+
+ if(getReportDataSize() <= 0) {
+ reportJSONRuntime.setMessage(getEmptyMessage());
+ }
+ reportJSONRuntime.setSqlWhole(getWholeSQL());
+ return reportJSONRuntime;
+
+ }
+
+ public ReportJSONRuntime createFormFieldJSONRuntime(HttpServletRequest request) {
+ String userId = AppUtils.getUserID(request);
+ ObjectMapper mapper = new ObjectMapper();
+ ReportJSONRuntime reportJSONRuntime = new ReportJSONRuntime();
+ reportJSONRuntime.setReportTitle(getReportTitle());
+ reportJSONRuntime.setReportID(getReportID());
+ reportJSONRuntime.setReportName(getReportName());
+ reportJSONRuntime.setReportSubTitle(getReportSubTitle());
+ reportJSONRuntime.setNumFormCols(getNumFormColsAsInt());
+ ArrayList<IdNameValue> formFieldValues = new ArrayList<IdNameValue>();
+ ArrayList<FormFieldJSON> formFieldJSONList = new ArrayList<FormFieldJSON>();
+ if(reportFormFields!=null) {
+ formFieldJSONList = new ArrayList<FormFieldJSON>(reportFormFields.size());
+ for (Iterator iter = reportFormFields.iterator(); iter.hasNext();) {
+ formFieldValues = new ArrayList<IdNameValue>();
+ FormField ff = (FormField) iter.next();
+ 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.setFormFieldValues(formFieldValues);
+ ffJSON.setVisible(ff.isVisible());
+ formFieldJSONList.add(ffJSON);
+ }
+ for (Iterator iter = reportFormFields.iterator(); iter.hasNext();) {
+ formFieldValues = new ArrayList<IdNameValue>();
+ FormField ff = (FormField) iter.next();
+ ff.setDbInfo(getDbInfo());
+ for (Iterator iter1 = formFieldJSONList.iterator(); iter1.hasNext();) {
+ FormFieldJSON ffJSON = (FormFieldJSON) iter1.next();
+ if(ffJSON.getFieldId().equals(ff.getFieldName())) {
+ 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();
+ setTriggerFormFieldCheck( getReportFormFields(), ff);
+ ffJSON.setTriggerOtherFormFields(ff.isTriggerOtherFormFields());
+ setTriggerThisFormFieldCheck(getReportFormFields(), ff);
+ SQL = parseAndFillReq_Session_UserValues(request, SQL, userId);
+ SQL = parseAndFillOtherFormfieldValues(request, SQL, userId, formFieldJSONList);
+ //SQL = parseAndFillWithCurrentValues(formGrid,SQL, ff);
+ String defaultSQL = lu.getDefaultSQL();
+ defaultSQL = parseAndFillReq_Session_UserValues(request, defaultSQL, userId);
+ //defaultSQL = parseAndFillWithCurrentValues(formGrid,defaultSQL, 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.getParameter(ff.getFieldName());
+ ArrayList<String> requestValueList = new ArrayList<String>();
+ requestValueList.add(requestValue);
+
+ /*if(ff.isTriggerThisFormfield()) {
+ refreshFormFieldsWithLatestValue(request, userId, ff, formFieldJSONList);
+ }*/
+
+
+ for (lookup.resetNext(); lookup.hasNext();) {
+ IdNameValue value = lookup.getNext();
+ readOnly = value.isReadOnly();
+ if(nvl(requestValue).length()>0) {
+ if(value.getId().equals(requestValue))
+ value.setDefaultValue(true);
+ }
+ formFieldValues.add(value);
+ //break;
+ }
+
+ } else {
+ setTriggerFormFieldCheck( getReportFormFields(), ff);
+ ffJSON.setTriggerOtherFormFields(ff.isTriggerOtherFormFields());
+ 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);
+ } else if (AppUtils.nvl(ff.getDefaultValue()).length()>0) {
+ IdNameValue value = new IdNameValue(ff.getDefaultValue(), ff.getDefaultValue(), true, false);
+ formFieldValues.add(value);
+ }
+ }
+ if(!ff.hasPredefinedList) {
+ if(oldSQL != null && !oldSQL.equals("")) {
+ ((IdNameSql)lookup).setSQL(oldSQL);
+ }
+ }
+
+
+ //if(!ff.isTriggerThisFormfield()) {
+ ffJSON.setFormFieldValues(formFieldValues);
+ //}
+
+ break;
+
+ } //if
+ } //for
+ }//for
+ }//if
+
+ reportJSONRuntime.setFormFieldList(formFieldJSONList);
+ //reportJSONRuntime.setReportDataColumns(get);
+
+ return reportJSONRuntime;
+
+ }
+
+
+ private String parseAndFillOtherFormfieldValues(HttpServletRequest request, String SQL, String userId, ArrayList<FormFieldJSON> formFieldJSONList) {
+ ArrayList<IdNameValue> formFieldValues = new ArrayList<IdNameValue>();
+ String selectedValue = "";
+ String displayName = "";
+ for (Iterator iter1 = formFieldJSONList.iterator(); iter1.hasNext();) {
+ FormFieldJSON ffJSON = (FormFieldJSON) iter1.next();
+ displayName = ffJSON.getFieldDisplayName();
+ ArrayList<IdNameValue> formfieldvalues = ffJSON.getFormFieldValues();
+ for (int i = 0; i< formfieldvalues.size(); i++) {
+ IdNameValue formfieldItem = formfieldvalues.get(i);
+ if(formfieldItem.isDefaultValue()) {
+ selectedValue = formfieldItem.getId();
+ }
+ }
+ SQL = Utils.replaceInString(SQL, "["+displayName+"]", selectedValue);
+ }
+ return SQL;
+
+ }
+
+ private void refreshFormFieldsWithLatestValue(HttpServletRequest request, String userId, FormField ff_src, ArrayList<FormFieldJSON> formFieldJSONList) {
+ ArrayList<IdNameValue> formFieldValues = new ArrayList<IdNameValue>();
+ List<String> requestValueList = null;
+ IdNameList lookup = null;
+ lookup = ff_src.getLookupList();
+ IdNameSql lu = (IdNameSql) lookup;
+ String SQL = "" ;
+ String oldSQL = "";
+ String oldDefaultSQL = "";
+ String defaultSQL = "";
+ IdNameList lookupList = null;
+ if(lu != null) {
+ SQL = lu.getSql();
+ oldSQL = lu.getSql();
+ oldDefaultSQL = lu.getDefaultSQL();
+ defaultSQL = lu.getDefaultSQL();
+ }
+ boolean readOnly = false;
+ for (Iterator iter1 = formFieldJSONList.iterator(); iter1.hasNext();) {
+ FormFieldJSON ffJSON = (FormFieldJSON) iter1.next();
+ if((ffJSON.getFieldId().equals(ff_src.getFieldName())) && ffJSON.isVisible()) {
+ for (Iterator iter = reportFormFields.iterator(); iter.hasNext();) {
+ formFieldValues = new ArrayList<IdNameValue>();
+ FormField ff = (FormField) iter.next();
+ if(!ff.getFieldName().equals(ff_src.getFieldName())) {
+ //IdNameList lookup = null;
+ //lookup = ff.getLookupList();
+ String selectedValue = "";
+
+
+
+ String [] requestParam = request.getParameterValues(ff.getFieldName());
+ if(requestParam != null) {
+ requestValueList = Arrays.asList(request.getParameterValues(ff.getFieldName()));
+
+ } else {
+ requestValueList = new ArrayList<String>();
+ }
+
+
+ if(nvl(ff_src.getBaseSQL()).length()>0 && ff_src.getBaseSQL().indexOf("["+ff.getFieldDisplayName() +"]")!= -1) {
+ if(lookup!=null) {
+ try {
+ if(!ff_src.hasPredefinedList) {
+ String formatSelected = null;
+ if(ff_src.getFieldType().equals(FormField.FFT_LIST_MULTI) || ff_src.getFieldType().equals(FormField.FFT_CHECK_BOX)) {
+ formatSelected = formatSelectedItems(requestValueList, ff_src.getFieldType());
+ } else
+ formatSelected = requestValueList.size()>0?requestValueList.get(0):"";
+ SQL = Utils.replaceInString(SQL, "["+ff_src.getFieldDisplayName()+"]", formatSelected);
+ defaultSQL = Utils.replaceInString(defaultSQL, "["+ff_src.getFieldDisplayName()+"]", formatSelected);
+ defaultSQL = parseAndFillWithCurrentValues(request, defaultSQL, ff_src);
+ defaultSQL = parseAndFillReq_Session_UserValues(request, defaultSQL, userId);
+ SQL = parseAndFillReq_Session_UserValues(request, SQL, userId);
+ SQL = parseAndFillWithCurrentValues(request, SQL, ff_src);
+
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+
+ }
+
+ }
+ }
+ }
+
+ if(nvl(ff_src.getBaseSQL()).length()>0) {
+ lookup = new IdNameSql(-1,SQL,defaultSQL);
+ lookupList = lookup;
+ try {
+ lookup.loadUserData(0, "", ff_src.getDbInfo(), ff_src.getUserId());
+ } catch (Exception e ){
+ e.printStackTrace(); //throw new RaptorRuntimeException(e);
+ }
+ if(!ff_src.hasPredefinedList) {
+ lookup.trimToSize();
+ for (lookup.resetNext(); lookup.hasNext();) {
+ IdNameValue value = lookup.getNext();
+ readOnly = value.isReadOnly();
+ formFieldValues.add(value);
+ }
+ }
+ ffJSON.setFormFieldValues(formFieldValues);
+ }
+ if(!ff_src.hasPredefinedList) {
+ if(oldSQL != null && !oldSQL.equals("")) {
+ ((IdNameSql)lookup).setSQL(oldSQL);
+ }
+ if(oldDefaultSQL != null && !oldDefaultSQL.equals("")) {
+ ((IdNameSql)lookup).setDefaultSQL(oldDefaultSQL);
+ }
+ }
+
+ }
+ }
+
+ }
+
+
+ private void triggerOtherFormFieldsWithThisValue(HttpServletRequest request, String userId, FormField ff_src, ArrayList<String> requestValueList, ArrayList<FormFieldJSON> formFieldJSONList) {
+ ArrayList<IdNameValue> formFieldValues = new ArrayList<IdNameValue>();
+ //ArrayList<FormFieldJSON> formFieldJSONList = new ArrayList<FormFieldJSON>();
+ for (Iterator iter = reportFormFields.iterator(); iter.hasNext();) {
+ formFieldValues = new ArrayList<IdNameValue>();
+ FormField ff = (FormField) iter.next();
+ if(!ff_src.getFieldName().equals(ff.getFieldName())) {
+ for (Iterator iter1 = formFieldJSONList.iterator(); iter1.hasNext();) {
+ FormFieldJSON ffJSON = (FormFieldJSON) iter1.next();
+ if(ffJSON.getFieldId().equals(ff.getFieldName()) && ffJSON.isVisible()) {
+ if(nvl(ff.getBaseSQL()).length()>0 && ff.getBaseSQL().indexOf("["+ff_src.getFieldDisplayName() +"]")!= -1) {
+ IdNameList lookup = null;
+ lookup = ff.getLookupList();
+ String selectedValue = "";
+ String oldSQL = "";
+ String oldDefaultSQL = "";
+ IdNameList lookupList = null;
+ boolean readOnly = false;
+ if(lookup!=null) {
+ try {
+ if(!ff.hasPredefinedList) {
+ IdNameSql lu = (IdNameSql) lookup;
+ String SQL = lu.getSql();
+ oldSQL = lu.getSql();
+ oldDefaultSQL = lu.getDefaultSQL();
+ String defaultSQL = lu.getDefaultSQL();
+ String formatSelected = null;
+ if(ff_src.getFieldType().equals(FormField.FFT_LIST_MULTI) || ff_src.getFieldType().equals(FormField.FFT_CHECK_BOX)) {
+ formatSelected = formatSelectedItems(requestValueList, ff.getFieldType());
+ }
+ else
+ formatSelected = requestValueList.size()>0?requestValueList.get(0):"";
+ SQL = Utils.replaceInString(SQL, "["+ff_src.getFieldDisplayName()+"]", formatSelected);
+ defaultSQL = Utils.replaceInString(defaultSQL, "["+ff_src.getFieldDisplayName()+"]", formatSelected);
+ defaultSQL = parseAndFillWithCurrentValues(request, defaultSQL, ff_src);
+ defaultSQL = parseAndFillReq_Session_UserValues(request, defaultSQL, userId);
+ SQL = parseAndFillReq_Session_UserValues(request, SQL, userId);
+ SQL = parseAndFillWithCurrentValues(request, SQL, ff_src);
+ 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();
+
+
+
+ for (lookup.resetNext(); lookup.hasNext();) {
+ IdNameValue value = lookup.getNext();
+ readOnly = value.isReadOnly();
+// if(nvl(requestValue).length()>0) {
+// if(value.getId().equals(requestValue))
+// value.setDefaultValue(true);
+// }
+ formFieldValues.add(value);
+ //break;
+ }
+
+ ffJSON.setFormFieldValues(formFieldValues);
+
+ if(!ff.hasPredefinedList) {
+ if(oldSQL != null && !oldSQL.equals("")) {
+ ((IdNameSql)lookup).setSQL(oldSQL);
+ }
+ if(oldDefaultSQL != null && !oldDefaultSQL.equals("")) {
+ ((IdNameSql)lookup).setDefaultSQL(oldDefaultSQL);
+ }
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ } //ff baseSQL
+ }
+ }
+ }
+ }
+
+ }
+
+ public String formatSelectedItems(List selectedItems, String type) {
+ StringBuffer value = new StringBuffer("");
+ int count = 0;
+ boolean multiple = false;
+ if(type.equals("LIST_MULTI_SELECT"))
+ multiple = true;
+ //multiple = (selectedItems.size()>1);
+ for(Iterator iter = selectedItems.iterator(); iter.hasNext(); ) {
+ count++;
+ String entry = (String) iter.next();
+ if(count == 1 && multiple)
+ value.append("(");
+ //if(type.equals(FormField.FFT_CHECK_BOX))
+ /*if(type.equals(FormField.FFT_CHECK_BOX))
+ value.append("'"+Utils.oracleSafe(entry)+"'");
+ else*/ if (type.equals(FormField.FFT_LIST_MULTI))
+ value.append("'"+Utils.oracleSafe(entry)+"'");
+ else if(type.equals(FormField.FFT_LIST_BOX))
+ value.append(Utils.oracleSafe(entry));
+ else
+ value.append("'"+Utils.oracleSafe(entry)+"'");
+ if((count < selectedItems.size()) && multiple)
+ value.append(",");
+ if((count == selectedItems.size()) && multiple)
+ value.append(")");
+ }
+
+ if(value.length()>0)
+ return value.toString();
+ else
+ return null;
+ }
+
+public String parseAndFillWithCurrentValues(HttpServletRequest request, String sql, FormField source_Formfield) {
+
+ if (getFormFieldList() != null) {
+ for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
+ FormFieldType fft = (FormFieldType) iter.next();
+ String fieldId = fft.getFieldId();
+ String fieldDisplay = getFormFieldDisplayName(fft);
+ String formfield_value = "";
+ List<String> selectedItems = new ArrayList<String>();
+ //Added so that Combo Box in old RAPTOR definition is translated to List box
+ if(fft.getFieldType().equals(FormField.FFT_COMBO_BOX)) {
+ fft.setFieldType(FormField.FFT_LIST_BOX);
+ }
+ if(!fft.getFieldType().equals(FormField.FFT_BLANK)) {
+ //if(source_Formfield==null || (source_Formfield!=null && !fft.getFieldId().equals(source_Formfield.getFieldName()))) {
+ // Add oracle safe
+ // Add param base sql
+ if(fft.getFieldType().equals(FormField.FFT_LIST_MULTI) || fft.getFieldType().equals(FormField.FFT_CHECK_BOX)) {
+ if(request.getParameterValues(fieldId)!=null && request.getParameterValues(fieldId).length > 0) {
+
+ selectedItems = Arrays.asList(request.getParameterValues(fieldId));
+ formfield_value = formatSelectedItems(selectedItems, fft.getFieldType());
+ } else {
+ formfield_value = "";
+ }
+ } else if(fft.getFieldType().equals(FormField.FFT_RADIO_BTN)) {
+ if(request.getParameter(fieldId)!=null) {
+ formfield_value = request.getParameter(fieldId);
+ } else {
+ formfield_value = "";
+ }
+ } else if (fft.getFieldType().equals(FormField.FFT_HIDDEN)) {
+ if(request.getParameter(fieldId)!=null) {
+ formfield_value = request.getParameter(fieldId);
+ } else {
+ formfield_value = "";
+ }
+ } else if((fft.getFieldType().equals(FormField.FFT_TEXT) || fft.getFieldType().equals(FormField.FFT_TEXTAREA)) &&
+ (!fft.getValidationType().equals(FormField.VT_DATE) && !fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)&&
+ !fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) && !fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) ) {
+ if(request.getParameter(fieldId)!=null) {
+ formfield_value = request.getParameter(fieldId);
+ } else {
+ formfield_value = "";
+ }
+ } else if (fft.getValidationType().equals(FormField.VT_DATE) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)||
+ fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
+ /*if(formGrid.hasFellow(fieldId, true)) {
+ Datebox tb = (Datebox) formGrid.getFellowIfAny(fieldId, true);
+ try {
+ formfield_value = tb.getText();
+ } catch (WrongValueException ex) {
+ formfield_value = "";
+ }
+ if(AppUtils.nvl(formfield_value).length() > 0) {
+ if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) {
+ if(formGrid.hasFellow(fieldId+"_Hr", true)) {
+ Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true);
+ formfield_value = formfield_value + " " + hiddenLbHr.getValue();
+ }
+ } else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) {
+ if(formGrid.hasFellow(fieldId+"_Min", true)) {
+ Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true);
+ //formfield_value = formfield_value + " " + hiddenLbHr.getValue();
+ Label hiddenLbMin = (Label) formGrid.getFellowIfAny(fieldId+"_Min", true);
+ formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue();
+
+ }
+ } else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
+ if(formGrid.hasFellow(fieldId+"_Sec", true)) {
+ Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true);
+ //formfield_value = formfield_value + " " + hiddenLbHr.getValue();
+ Label hiddenLbMin = (Label) formGrid.getFellowIfAny(fieldId+"_Min", true);
+ //formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue();
+ Label hiddenLbSec = (Label) formGrid.getFellowIfAny(fieldId+"_Sec", true);
+ formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue()+ ":" +hiddenLbSec.getValue();
+
+ }
+ }
+ }
+
+ } else {
+ formfield_value = "";
+ }*/
+ } else if ((fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)||
+ fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC))) {
+ /*if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)||
+ fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
+ if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) {
+ if(formGrid.hasFellow(fieldId+"_Hr", true)) {
+ Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true);
+ formfield_value = formfield_value + " " + hiddenLbHr.getValue();
+ }
+ } else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) {
+ if(formGrid.hasFellow(fieldId+"_Min", true)) {
+ Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true);
+ //formfield_value = formfield_value + " " + hiddenLbHr.getValue();
+ Label hiddenLbMin = (Label) formGrid.getFellowIfAny(fieldId+"_Min", true);
+ formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue();
+
+ }
+ } else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
+ if(formGrid.hasFellow(fieldId+"_Sec", true)) {
+ Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true);
+ //formfield_value = formfield_value + " " + hiddenLbHr.getValue();
+ Label hiddenLbMin = (Label) formGrid.getFellowIfAny(fieldId+"_Min", true);
+ //formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue();
+ Label hiddenLbSec = (Label) formGrid.getFellowIfAny(fieldId+"_Sec", true);
+ formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue()+ ":" +hiddenLbSec.getValue();
+
+ }
+ }
+
+ } */
+ } else if (fft.getFieldType().equals(FormField.FFT_TEXT_W_POPUP)) {
+ if(request.getParameter(fieldId)!=null) {
+ formfield_value = request.getParameter(fieldId);
+ } else {
+ formfield_value = "";
+ }
+ } else if (fft.getFieldType().equals(FormField.FFT_LIST_BOX)) {
+ if(request.getParameter(fieldId)!=null) {
+ formfield_value = request.getParameter(fieldId);
+ } else {
+ formfield_value = "";
+ }
+ //}
+ }
+ if(nvl(formfield_value).length()>0) {
+ sql = Utils.replaceInString(sql, fieldDisplay, formfield_value);
+ } else {
+ sql = Utils.replaceInString(sql, "'"+fieldDisplay+"'", "null");
+ sql = Utils.replaceInString(sql, fieldDisplay, "null");
+ //sql = Utils.replaceInString(sql, fieldDisplay, "''");
+ }
+ } // for
+ }
+ }
+ return sql;
+ }
+ public String parseAndFillReq_Session_UserValues(HttpServletRequest request, String sql, String user_id) {
+ HttpSession session = request.getSession();
+
+ String[] reqParameters = Globals.getRequestParams().split(",");
+ String[] sessionParameters = Globals.getSessionParams().split(",");
+ String[] scheduleSessionParameters = Globals.getSessionParamsForScheduling().split(",");
+
+
+ if(AppUtils.nvl(sql).length()>0) {
+ for (int i = 0; i < reqParameters.length; i++) {
+ if(!reqParameters[i].startsWith("ff") && (request.getParameter(reqParameters[i].toUpperCase())!=null && request.getParameter(reqParameters[i].toUpperCase()).length() > 0))
+ sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
+ else if (request.getParameter(reqParameters[i])!=null && request.getParameter(reqParameters[i]).length() > 0)
+ sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
+ }
+
+ for (int i = 0; i < scheduleSessionParameters.length; i++) {
+ //debugLogger.debug(" Session " + " scheduleSessionParameters[i] " + scheduleSessionParameters[i].toUpperCase() + " " + request.getParameter(scheduleSessionParameters[i]));
+ if(request.getParameter(scheduleSessionParameters[i])!=null && request.getParameter(scheduleSessionParameters[i]).trim().length()>0 )
+ sql = Utils.replaceInString(sql, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) );
+ if(request.getAttribute(scheduleSessionParameters[i])!=null && ((String)request.getAttribute(scheduleSessionParameters[i])).trim().length()>0 )
+ sql = Utils.replaceInString(sql, "[" + scheduleSessionParameters[i].toUpperCase()+"]", (String) request.getAttribute(scheduleSessionParameters[i]) );
+
+ }
+
+ for (int i = 0; i < sessionParameters.length; i++) {
+ //if(!sessionParameters[i].startsWith("ff"))
+ //fieldSQL = Utils.replaceInString(fieldSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) );
+ //else {
+ if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0) {
+ //debugLogger.debug(" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i]));
+ sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
+ }
+ // }
+ }
+ sql = Utils.replaceInString(sql, "[USERID]", user_id);
+ sql = Utils.replaceInString(sql, "[USER_ID]", user_id);
+ sql = Utils.replaceInString(sql, "[LOGGED_USERID]", user_id);
+
+ }
+ return sql;
+ }
+
+} // ReportRuntime
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+public class TimeSeriesChartOptions {
+ private String lineChartRenderer;
+ private boolean multiSeries;
+ private boolean nonTimeAxis;
+ private boolean showXAxisLabel;
+ private boolean addXAxisTicker;
+
+ public String getLineChartRenderer() {
+ return lineChartRenderer;
+ }
+ public void setLineChartRenderer(String lineChartRenderer) {
+ this.lineChartRenderer = lineChartRenderer;
+ }
+ public boolean isMultiSeries() {
+ return multiSeries;
+ }
+ public void setMultiSeries(boolean multiSeries) {
+ this.multiSeries = multiSeries;
+ }
+ public boolean isNonTimeAxis() {
+ return nonTimeAxis;
+ }
+ public void setNonTimeAxis(boolean nonTimeAxis) {
+ this.nonTimeAxis = nonTimeAxis;
+ }
+ public boolean isShowXAxisLabel() {
+ return showXAxisLabel;
+ }
+ public void setShowXAxisLabel(boolean showXAxisLabel) {
+ this.showXAxisLabel = showXAxisLabel;
+ }
+ public boolean isAddXAxisTicker() {
+ return addXAxisTicker;
+ }
+ public void setAddXAxisTicker(boolean addXAxisTicker) {
+ this.addXAxisTicker = addXAxisTicker;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.runtime;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+
+public class VisualManager extends RaptorObject {
+ private HashMap hiddenCols = new HashMap();
+
+ private String sortByColId = "";
+
+ private String sortByAscDesc = AppConstants.SO_ASC;
+
+ public VisualManager() {
+ super();
+ }
+
+ public void hideColumn(String colId) {
+ hiddenCols.put(colId, "Y");
+ } // hideColumn
+
+ public void showColumn(String colId) {
+ hiddenCols.put(colId, "N");
+ } // showColumn
+
+ public boolean isColumnVisible(String colId) {
+ return nvl((String) hiddenCols.get(colId), "N").equals("N");
+ } // isColumnVisible
+
+ public void setSortByColumn(String colId) {
+ if (sortByColId.equals(colId))
+ sortByAscDesc = sortByAscDesc.equals(AppConstants.SO_ASC) ? AppConstants.SO_DESC
+ : AppConstants.SO_ASC;
+ else {
+ sortByColId = colId;
+ sortByAscDesc = AppConstants.SO_ASC;
+ }
+ } // setSortByColumn
+
+ public String getSortByColId() {
+ return sortByColId;
+ }
+
+ public String getSortByAscDesc() {
+ return sortByAscDesc;
+ }
+
+} // VisualManager
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.search;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+
+public class ReportSearchResult extends SearchResult {
+ private static final String HTML_FORM = "forma";
+
+ public ReportSearchResult(int pageNo) {
+ this(pageNo, Globals.getDefaultPageSize(), -1, -1);
+ } // ReportSearchResult
+
+ public ReportSearchResult(int pageNo, int writeAccessColIndex, int ownerIndicatorColIndex) {
+ this(pageNo, Globals.getDefaultPageSize(), writeAccessColIndex, ownerIndicatorColIndex);
+ } // ReportSearchResult
+
+ public ReportSearchResult(int pageNo, int pageSize, int writeAccessColIndex,
+ int ownerIndicatorColIndex) {
+ super(pageNo, pageSize, writeAccessColIndex, ownerIndicatorColIndex);
+
+ addColumn(new SearchResultColumn("no","No", "5%", "Center"));
+ addColumn(new SearchResultColumn("rep_id","Report ID", "5%", "Center"));
+ addColumn(new SearchResultColumn("rep_name","Report Name", "25%", "Left"));
+ addColumn(new SearchResultColumn("descr","Description", "30%", "Left"));
+ addColumn(new SearchResultColumn("owner","Report Owner", "10%", "Center"));
+ addColumn(new SearchResultColumn("create_date","Create Date", "10%", "Center"));
+ addColumn(new SearchResultColumn("copy"," Copy ", "5%", "Center",
+ "document." + HTML_FORM + "." + AppConstants.RI_ACTION
+ + ".value='report.copy';", "Copy report", HTML_FORM,
+ "Are you sure you want to create a copy of this report?", AppUtils
+ .getImgFolderURL()
+ + "modify_icon.gif", "13", "12", true, false, false));
+ /*addColumn(new SearchResultColumn(" Schedule ", "5%", "Center",
+ "document." + HTML_FORM + "." + AppConstants.RI_ACTION
+ + ".value='report.schedule_only';", "Schedule report", HTML_FORM,
+ null, AppUtils
+ .getImgFolderURL()
+ + "calendar_icon.gif", "13", "12", true, false, false));
+ */
+
+ addColumn(new SearchResultColumn("edit"," Edit ", "5%", "Center",
+ "document." + HTML_FORM + "." + AppConstants.RI_ACTION
+ + ".value='report.edit';", "Edit report", HTML_FORM, null, AppUtils
+ .getImgFolderURL()
+ + "pen_paper.gif", "12", "12", false, true, false));
+ addColumn(new SearchResultColumn("delete","Delete", "5%", "Center", "document." + HTML_FORM
+ + "." + AppConstants.RI_ACTION + ".value='report.delete';", "Delete report",
+ HTML_FORM, "Are you sure you want to delete this report?", AppUtils
+ .getImgFolderURL()
+ + "deleteicon.gif", "12", "12", false, false, true));
+ addColumn(new SearchResultColumn("schedule","Schedule", "5%", "Center", "document." + HTML_FORM
+ + "." + AppConstants.RI_ACTION + ".value='report.schedule.report.submit_wmenu';", "Schedule report",
+ HTML_FORM, null, AppUtils
+ .getImgFolderURL()
+ + "calendar_icon.gif", "20", "20", false, false, false, true));
+ addColumn(new SearchResultColumn("run"," Run ", "5%", "Center",
+ "document." + HTML_FORM + "." + AppConstants.RI_ACTION
+ + ".value='report.run';", "Run report", HTML_FORM, null, AppUtils
+ .getImgFolderURL()
+ + "test_run.gif", "12", "12"));
+ } // ReportSearchResult
+
+} // ReportSearchResult
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.search;
+
+import java.util.*;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+class MetaReport {
+ private boolean pagination = true;
+ private int pageSize;
+ private int totalSize;
+ private int pageNo;
+ public boolean isPagination() {
+ return pagination;
+ }
+ public void setPagination(boolean pagination) {
+ this.pagination = pagination;
+ }
+ public int getPageSize() {
+ return pageSize;
+ }
+ public void setPageSize(int pageSize) {
+ this.pageSize = pageSize;
+ }
+ public int getTotalSize() {
+ return totalSize;
+ }
+ public void setTotalSize(int totalSize) {
+ this.totalSize = totalSize;
+ }
+ public int getPageNo() {
+ return pageNo;
+ }
+ public void setPageNo(int pageNo) {
+ this.pageNo = pageNo;
+ }
+
+
+}
+class SearchReport {
+ private MetaReport metaReport;
+ public MetaReport getMetaReport() {
+ return metaReport;
+ }
+ public void setMetaReport(MetaReport metaReport) {
+ this.metaReport = metaReport;
+ }
+ private ArrayList<ArrayList<SearchResultColumn>> columns = new ArrayList<ArrayList<SearchResultColumn>>();
+ private ArrayList<ArrayList<SearchResultRow>> rows = new ArrayList<ArrayList<SearchResultRow>>();
+ public ArrayList<ArrayList<SearchResultColumn>> getColumns() {
+ return columns;
+ }
+ public void setColumns(ArrayList<ArrayList<SearchResultColumn>> columns) {
+ this.columns = columns;
+ }
+ public ArrayList<ArrayList<SearchResultRow>> getRows() {
+ return rows;
+ }
+ public void setRows(ArrayList<ArrayList<SearchResultRow>> rows) {
+ this.rows = rows;
+ }
+
+}
+
+public class ReportSearchResultJSON extends SearchResultJSON {
+ private static final String HTML_FORM = "forma";
+ private String JSONString= "";
+ private SearchReport searchReport;
+ //private ArrayList<ArrayList<SearchResultColumn>> columns = new ArrayList<ArrayList<SearchResultColumn>>();
+ //private ArrayList<ArrayList<SearchResultRow>> rows = new ArrayList<ArrayList<SearchResultRow>>();
+
+
+ public ReportSearchResultJSON(int pageNo) {
+ this(pageNo, Globals.getDefaultPageSize(), -1, -1);
+ } // ReportSearchResult
+
+ public ReportSearchResultJSON(int pageNo, int writeAccessColIndex, int ownerIndicatorColIndex) {
+ this(pageNo, Globals.getDefaultPageSize(), writeAccessColIndex, ownerIndicatorColIndex);
+ } // ReportSearchResult
+
+ public ReportSearchResultJSON(int pageNo, int pageSize, int writeAccessColIndex,
+ int ownerIndicatorColIndex) {
+
+ searchReport = new SearchReport();
+ MetaReport metaReport = new MetaReport();
+ //if(searchReport.getMetaReport()!=null)
+ searchReport.setMetaReport(metaReport);
+ metaReport.setPageNo(pageNo);
+ metaReport.setPageSize(pageSize);
+ metaReport.setPagination(true);
+ addColumn(new SearchResultColumn("no", "No", "5%", "Center"));
+ addColumn(new SearchResultColumn("rep_id", "Report ID", "5%", "Center"));
+ addColumn(new SearchResultColumn("rep_name", "Report Name", "25%", "Left"));
+ addColumn(new SearchResultColumn("descr", "Description", "30%", "Left"));
+ addColumn(new SearchResultColumn("owner", "Report Owner", "10%", "Center"));
+ addColumn(new SearchResultColumn("create_date", "Create Date", "10%", "Center"));
+ addColumn(new SearchResultColumn("copy", "Copy", "5%", "Center",
+ "document." + HTML_FORM + "." + AppConstants.RI_ACTION
+ + ".value='report.copy';", "Copy report", HTML_FORM,
+ "Are you sure you want to create a copy of this report?", AppUtils
+ .getImgFolderURL()
+ + "modify_icon.gif", "13", "12", true, false, false));
+ /*addColumn(new SearchResultColumn(" Schedule ", "5%", "Center",
+ "document." + HTML_FORM + "." + AppConstants.RI_ACTION
+ + ".value='report.schedule_only';", "Schedule report", HTML_FORM,
+ null, AppUtils
+ .getImgFolderURL()
+ + "calendar_icon.gif", "13", "12", true, false, false));
+ */
+
+ addColumn(new SearchResultColumn("edit", "Edit", "5%", "Center",
+ "document." + HTML_FORM + "." + AppConstants.RI_ACTION
+ + ".value='report.edit';", "Edit report", HTML_FORM, null, AppUtils
+ .getImgFolderURL()
+ + "pen_paper.gif", "12", "12", false, true, false));
+ addColumn(new SearchResultColumn("delete", "Delete", "5%", "Center", "document." + HTML_FORM
+ + "." + AppConstants.RI_ACTION + ".value='report.delete';", "Delete report",
+ HTML_FORM, "Are you sure you want to delete this report?", AppUtils
+ .getImgFolderURL()
+ + "deleteicon.gif", "12", "12", false, false, true));
+ addColumn(new SearchResultColumn("schedule", "Schedule", "5%", "Center", "document." + HTML_FORM
+ + "." + AppConstants.RI_ACTION + ".value='report.schedule.report.submit_wmenu';", "Schedule report",
+ HTML_FORM, null, AppUtils
+ .getImgFolderURL()
+ + "calendar_icon.gif", "20", "20", false, false, false, true));
+ addColumn(new SearchResultColumn("run", "Run", "5%", "Center",
+ "document." + HTML_FORM + "." + AppConstants.RI_ACTION
+ + ".value='report.run';", "Run report", HTML_FORM, null, AppUtils
+ .getImgFolderURL()
+ + "test_run.gif", "12", "12"));
+ searchReport.getColumns().add(searchResultColumns);
+ } // ReportSearchResult
+
+ public void parseData(DataSet ds, HttpServletRequest request, int pageNo, int pageSize, int writeAccessColIndex, int ownerIndicatorColIndex) throws RaptorException {
+ // Presumes single ID field in the first column of the DataSet and row
+ // number in the first SearchResultColumn
+
+ pageNo = AppUtils.getRequestNvlValue(request, "r_page").length()>0?Integer.parseInt(AppUtils.getRequestNvlValue(request, "r_page")):0;
+ String userID = AppUtils.getUserID(request);
+ int dataSize = ds.getRowCount();
+ //pageSize = 0;
+
+ if(searchReport.getMetaReport()!=null) {
+ searchReport.getMetaReport().setPageNo(pageNo);
+ //searchReport.getMetaReport().setPageSize(pageSize);
+ pageSize = searchReport.getMetaReport().getPageSize();
+ searchReport.getMetaReport().setTotalSize(dataSize);
+ }
+ int startRow = (pageNo >= 0) ? (pageNo * pageSize) : 0;
+ int endRow = (pageNo >= 0) ? Math.min(startRow + pageSize, ds.getRowCount()) : ds
+ .getRowCount();
+ for (int r = startRow; r < endRow; r++) {
+ SearchResultRow row = new SearchResultRow();
+ searchResultRows.add(row);
+
+ String idValue = ds.getString(r, 0);
+
+ boolean bCanEdit = true;
+ if (writeAccessColIndex >= 0) {
+ String isReadOnlyValue = nvl(ds.getString(r, writeAccessColIndex), "Y");
+ bCanEdit = AppUtils.isSuperUser(request) || AppUtils.isAdminUser(request)
+ || isReadOnlyValue.equals("N");
+ }
+
+ boolean bCanDelete = bCanEdit;
+ if (Globals.getDeleteOnlyByOwner() && ownerIndicatorColIndex >= 0) {
+ String isOwnedByUserRecord = nvl(ds.getString(r, ownerIndicatorColIndex), "N");
+ bCanDelete = AppUtils.isSuperUser(request) || isOwnedByUserRecord.equals("Y");
+ }
+
+ boolean bCanSchedule = ds.getString(r, getNumColumns()-3).equals("Y");
+
+ row.addColumnContent(new ColumnContent(getColumn(0).getColumnId(), new SearchResultField("" + (r + 1), idValue,
+ getColumn(0), true)));
+ boolean isAuthorized = true;
+ for (int c = 1; c < getNumColumns(); c++) {
+ SearchResultColumn column = getColumn(c);
+ isAuthorized = true;
+
+ if(column.isCopyLink())
+ isAuthorized = Globals.getCanCopyOnReadOnly()? true:bCanEdit;
+ else if (column.isDeleteLink())
+ isAuthorized = bCanDelete;
+ else if (column.isEditLink())
+ isAuthorized = bCanEdit;
+ else if (column.isScheduleLink())
+ isAuthorized = bCanSchedule;
+ row.addColumnContent(new ColumnContent(column.getColumnId(), new SearchResultField(
+ (column.getLinkURL() == null) ? ds.getString(r, c) : column
+ .getLinkTitle(), idValue, column, isAuthorized
+ )));
+ } // for
+ } // for
+ searchReport.getRows().add(searchResultRows);
+ ObjectMapper mapper = new ObjectMapper();
+ String jsonInString = "";
+ try {
+ jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(searchReport);
+ } catch (Exception ex) {
+ ex.printStackTrace();
+
+ }
+ System.out.println(jsonInString);
+ this.JSONString = jsonInString;
+ } // parseData
+
+ private String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ private String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+ public String getJSONString() {
+ return JSONString;
+ }
+
+ public void setJSONString(String jSONString) {
+ JSONString = jSONString;
+ }
+
+
+} // ReportSearchResult
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.search;
+
+import java.util.*;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+
+public class SearchResult{
+ private int pageNo = -1;
+
+ private int pageSize = 50;
+
+ private int dataSize = -1;
+
+ private int writeAccessColIndex = -1;
+
+ private int ownerIndicatorColIndex = -1;
+
+ private String csvPageFileName = null;
+
+
+
+ private String csvAllRowsFileName = null;
+
+ private String excelAllRowsFileName = null;
+
+ public ArrayList searchResultColumns = new ArrayList();
+
+ public ArrayList searchResultRows = new ArrayList();
+
+ public SearchResult(int pageNo) {
+ this(pageNo, Globals.getDefaultPageSize());
+ } // SearchResult
+
+ public SearchResult(int pageNo, int pageSize) {
+ this(pageNo, pageSize, -1, -1);
+ } // SearchResult
+
+ public SearchResult(int pageNo, int pageSize, int writeAccessColIndex,
+ int ownerIndicatorColIndex) {
+ super();
+
+ this.pageNo = pageNo;
+ this.pageSize = pageSize;
+
+ this.writeAccessColIndex = writeAccessColIndex;
+ this.ownerIndicatorColIndex = ownerIndicatorColIndex;
+ } // SearchResult
+
+ public int getPageNo() {
+ return pageNo;
+ }
+
+ public int getPageSize() {
+ return pageSize;
+ }
+
+ public int getDataSize() {
+ return dataSize;
+ }
+
+ public String getCsvPageFileName() {
+ return csvPageFileName;
+ }
+
+ public String getCsvAllRowsFileName() {
+ return csvAllRowsFileName;
+ }
+
+ public String getExcelAllRowsFileName() {
+ return excelAllRowsFileName;
+ }
+
+ private void setDataSize(int dataSize) {
+ this.dataSize = dataSize;
+ }
+
+ public void setCsvPageFileName(String csvPageFileName) {
+ this.csvPageFileName = csvPageFileName;
+ }
+
+
+
+ public void setCsvAllRowsFileName(String csvAllRowsFileName) {
+ this.csvAllRowsFileName = csvAllRowsFileName;
+ }
+
+
+
+ public void addColumn(SearchResultColumn column) {
+ searchResultColumns.add(column);
+ } // addColumn
+
+ public SearchResultColumn getColumn(int index) {
+ return (SearchResultColumn) searchResultColumns.get(index);
+ } // getColumn
+
+ public int getNumColumns() {
+ return searchResultColumns.size();
+ } // getNumColumns
+
+ public int getNumRows() {
+ return searchResultRows.size();
+ } // getNumRows
+
+ public SearchResultRow getRow(int index) {
+ return (SearchResultRow) searchResultRows.get(index);
+ } // getRow
+
+ public void parseData(DataSet ds, HttpServletRequest request) throws RaptorException {
+ // Presumes single ID field in the first column of the DataSet and row
+ // number in the first SearchResultColumn
+ String userID = AppUtils.getUserID(request);
+ setDataSize(ds.getRowCount());
+
+ int startRow = (pageNo >= 0) ? (pageNo * pageSize) : 0;
+ int endRow = (pageNo >= 0) ? Math.min(startRow + pageSize, ds.getRowCount()) : ds
+ .getRowCount();
+ for (int r = startRow; r < endRow; r++) {
+ SearchResultRow row = new SearchResultRow();
+ searchResultRows.add(row);
+
+ String idValue = ds.getString(r, 0);
+
+ boolean bCanEdit = true;
+ if (writeAccessColIndex >= 0) {
+ String isReadOnlyValue = nvl(ds.getString(r, writeAccessColIndex), "Y");
+ bCanEdit = AppUtils.isSuperUser(request) || AppUtils.isAdminUser(request)
+ || isReadOnlyValue.equals("N");
+ }
+
+ boolean bCanDelete = bCanEdit;
+ if (Globals.getDeleteOnlyByOwner() && ownerIndicatorColIndex >= 0) {
+ String isOwnedByUserRecord = nvl(ds.getString(r, ownerIndicatorColIndex), "N");
+ bCanDelete = AppUtils.isSuperUser(request) || isOwnedByUserRecord.equals("Y");
+ }
+
+ boolean bCanSchedule = ds.getString(r, getNumColumns()-3).equals("Y");
+
+ row.addSearchResultField(new SearchResultField("" + (r + 1), idValue,
+ getColumn(0), true));
+ boolean isAuthorized = true;
+ for (int c = 1; c < getNumColumns(); c++) {
+ SearchResultColumn column = getColumn(c);
+ isAuthorized = true;
+
+ if(column.isCopyLink())
+ isAuthorized = Globals.getCanCopyOnReadOnly()? true:bCanEdit;
+ else if (column.isDeleteLink())
+ isAuthorized = bCanDelete;
+ else if (column.isEditLink())
+ isAuthorized = bCanEdit;
+ else if (column.isScheduleLink())
+ isAuthorized = bCanSchedule;
+
+ row.addSearchResultField(new SearchResultField(
+ (column.getLinkURL() == null) ? ds.getString(r, c) : column
+ .getLinkTitle(), idValue, column, isAuthorized
+ ));
+ } // for
+ } // for
+ } // parseData
+
+ public void truncateToPage(int pageNo) {
+ if (this.pageNo >= 0 || pageNo < 0)
+ return;
+
+ this.pageNo = pageNo;
+
+ int startRow = pageNo * pageSize;
+ int endRow = Math.min(startRow + pageSize, dataSize);
+
+ for (int r = getNumRows() - 1; r >= endRow; r--)
+ searchResultRows.remove(r);
+
+ for (int r = startRow - 1; r >= 0; r--)
+ searchResultRows.remove(r);
+ } // truncateToPage
+
+ /** *********************************************************************** */
+
+ private String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ private String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+} // SearchResult
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.search;
+
+import org.onap.portalsdk.analytics.util.*;
+
+public class SearchResultColumn extends org.onap.portalsdk.analytics.RaptorObject {
+ private String columnId = "";
+ private String columnTitle = "";
+
+ private String columnWidth = "";
+
+ private String alignment = "Left";
+
+ private String linkURL = null; // if not null => display link instead of
+ // text
+
+ private String linkTitle = null; // if img => hint, otherwise link
+ // display text
+
+ private String linkForm = null; // if not null => displays input submit
+ // instead of link
+
+ private String linkConfirmMsg = null; // if not null => display conf. box
+ // on link click
+
+ private String linkImg = null; // if not null => link shows image, not text
+
+ private String linkImgWidth = null; // optional
+
+ private String linkImgHeight = null; // optional
+
+ private boolean copyLink = false; // optional
+
+ private boolean editLink = false; // optional
+
+ private boolean deleteLink = false; // optional
+
+ private boolean scheduleLink = false; // optional
+
+ public SearchResultColumn(String columnId, String columnTitle) {
+ super();
+ setColumnId(columnId);
+ setColumnTitle(columnTitle);
+ } // SearchResultColumn
+
+ public SearchResultColumn(String columnId, String columnTitle, String columnWidth, String alignment) {
+ super();
+ setColumnId(columnId);
+ setColumnTitle(columnTitle);
+ setColumnWidth(columnWidth);
+ setAlignment(alignment);
+ } // SearchResultColumn
+
+ public SearchResultColumn(String columnId, String columnTitle, String columnWidth, String alignment,
+ String linkURL, String linkTitle, String linkForm, String linkConfirmMsg,
+ String linkImg) {
+ super();
+ setColumnId(columnId);
+ setColumnTitle(columnTitle);
+ setColumnWidth(columnWidth);
+ setAlignment(alignment);
+ setLinkURL(linkURL);
+ setLinkTitle(linkTitle);
+ setLinkForm(linkForm);
+ setLinkConfirmMsg(linkConfirmMsg);
+ setLinkImg(linkImg);
+ } // SearchResultColumn
+
+ public SearchResultColumn(String columnId, String columnTitle, String columnWidth, String alignment,
+ String linkURL, String linkTitle, String linkForm, String linkConfirmMsg,
+ String linkImg, String linkImgWidth, String linkImgHeight) {
+ this(columnId, columnTitle, columnWidth, alignment, linkURL, linkTitle, linkForm,
+ linkConfirmMsg, linkImg);
+
+ setLinkWidth(linkImgWidth);
+ setLinkHeight(linkImgHeight);
+ } // SearchResultColumn
+
+ public SearchResultColumn(String columnId, String columnTitle, String columnWidth, String alignment,
+ String linkURL, String linkTitle, String linkForm, String linkConfirmMsg,
+ String linkImg, String linkImgWidth, String linkImgHeight, boolean copyLink,
+ boolean editLink, boolean deleteLink) {
+ this(columnId, columnTitle, columnWidth, alignment, linkURL, linkTitle, linkForm,
+ linkConfirmMsg, linkImg, linkImgWidth, linkImgHeight);
+
+ setCopyLink(copyLink);
+ setEditLink(editLink);
+ setDeleteLink(deleteLink);
+ } // SearchResultColumn
+
+ public SearchResultColumn(String columnId, String columnTitle, String columnWidth, String alignment,
+ String linkURL, String linkTitle, String linkForm, String linkConfirmMsg,
+ String linkImg, String linkImgWidth, String linkImgHeight, boolean copyLink,
+ boolean editLink, boolean deleteLink, boolean scheduleLink) {
+ this(columnId, columnTitle, columnWidth, alignment, linkURL, linkTitle, linkForm,
+ linkConfirmMsg, linkImg, linkImgWidth, linkImgHeight);
+
+ setCopyLink(copyLink);
+ setEditLink(editLink);
+ setDeleteLink(deleteLink);
+ setScheduleLink(scheduleLink);
+ } // SearchResultColumn
+
+ public String getColumnTitle() {
+ return columnTitle;
+ }
+
+ public String getColumnWidth() {
+ return columnWidth;
+ }
+
+ public String getAlignment() {
+ return alignment;
+ }
+
+ public String getLinkURL() {
+ return linkURL;
+ }
+
+ public String getLinkTitle() {
+ return linkTitle;
+ }
+
+ public String getLinkForm() {
+ return linkForm;
+ }
+
+ public String getLinkConfirmMsg() {
+ return linkConfirmMsg;
+ }
+
+ public String getLinkImg() {
+ return linkImg;
+ }
+
+ public String getLinkImgWidth() {
+ return linkImgWidth;
+ }
+
+ public String getLinkImgHeight() {
+ return linkImgHeight;
+ }
+
+ public boolean isCopyLink() {
+ return copyLink;
+ }
+
+ public boolean isEditLink() {
+ return editLink;
+ }
+
+ public boolean isDeleteLink() {
+ return deleteLink;
+ }
+
+ public void setColumnTitle(String columnTitle) {
+ this.columnTitle = nvl(columnTitle);
+ }
+
+ public void setColumnWidth(String columnWidth) {
+ this.columnWidth = nvl(columnWidth);
+ }
+
+ public void setAlignment(String alignment) {
+ this.alignment = alignment;
+ }
+
+ public void setLinkURL(String linkURL) {
+ this.linkURL = linkURL;
+ }
+
+ public void setLinkTitle(String linkTitle) {
+ this.linkTitle = linkTitle;
+ }
+
+ public void setLinkForm(String linkForm) {
+ this.linkForm = linkForm;
+ }
+
+ public void setLinkConfirmMsg(String linkConfirmMsg) {
+ this.linkConfirmMsg = linkConfirmMsg;
+ }
+
+ public void setLinkImg(String linkImg) {
+ this.linkImg = linkImg;
+ }
+
+ public void setLinkWidth(String linkImgWidth) {
+ this.linkImgWidth = linkImgWidth;
+ }
+
+ public void setLinkHeight(String linkImgHeight) {
+ this.linkImgHeight = linkImgHeight;
+ }
+
+ public void setCopyLink(boolean copyLink) {
+ this.copyLink = copyLink;
+ }
+
+ public void setEditLink(boolean editLink) {
+ this.editLink = editLink;
+ }
+
+ public void setDeleteLink(boolean deleteLink) {
+ this.deleteLink = deleteLink;
+ }
+
+ public String getColumnTitleHtml() {
+ return (columnTitle.length() == 0) ? " " : columnTitle;
+ }
+
+ public String getColumnWidthHtml() {
+ return (columnWidth.length() == 0) ? "" : (" width=" + columnWidth);
+ }
+
+ public String getLinkImgSizeHtml() {
+ return ((nvl(linkImgWidth).length() > 0) ? " width=\"" + linkImgWidth + "\"" : "")
+ + ((nvl(linkImgHeight).length() > 0) ? " height=\"" + linkImgHeight + "\""
+ : "");
+ }
+
+ public boolean isScheduleLink() {
+ return scheduleLink;
+ }
+
+ public void setScheduleLink(boolean scheduleLink) {
+ this.scheduleLink = scheduleLink;
+ }
+
+ public String getColumnId() {
+ return columnId;
+ }
+
+ public void setColumnId(String columnId) {
+ this.columnId = columnId;
+ }
+
+} // SearchResultColumn
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.search;
+
+import org.onap.portalsdk.analytics.util.*;
+
+public class SearchResultField extends org.onap.portalsdk.analytics.RaptorObject {
+ private String columnId;
+ private String displayValue = "";
+
+ private String alignment = "Left";
+
+ private String drillDownLink = null;
+
+ private String drillDownImage = null;
+
+ private String confirmationText = null;
+
+
+
+ public String getConfirmationText() {
+ return confirmationText;
+ }
+
+ public void setConfirmationText(String confirmationText) {
+ this.confirmationText = confirmationText;
+ }
+
+ public String getDrillDownImage() {
+ return drillDownImage;
+ }
+
+ public void setDrillDownImage(String drillDownImage) {
+ this.drillDownImage = drillDownImage;
+ }
+
+ public SearchResultField() {
+ }
+
+ public SearchResultField(String displayValue, String linkIdValue,
+ SearchResultColumn column, boolean isAuthorized) {
+ super();
+
+ if (!isAuthorized)
+ return;
+
+ setColumnId(column.getColumnId());
+ setDisplayValue(displayValue);
+ setAlignment(column.getAlignment());
+ if(column.getColumnId().equals("edit")) {
+// setDrillDownLink("report_wizard.htm?action=report.edit&c_master="+linkIdValue);
+ setDrillDownLink("report#/report_wizard/"+linkIdValue);
+ setDrillDownImage(column.getLinkImg());
+ setConfirmationText(null);
+ } else if(column.getColumnId().equals("copy")) {
+// setDrillDownLink("report_wizard.htm?action=report.copy&c_master="+linkIdValue);
+ setDrillDownLink("report#/report_wizard/copy/"+linkIdValue);
+ setDrillDownImage(column.getLinkImg());
+ setConfirmationText(column.getLinkConfirmMsg());
+ } else if(column.getColumnId().equals("delete")) {
+ setDrillDownLink("raptor.htm?action=report.delete&c_master="+linkIdValue);
+ setDrillDownImage(column.getLinkImg());
+ setConfirmationText(column.getLinkConfirmMsg());
+ } else if(column.getColumnId().equals("schedule")) {
+ setDrillDownLink("report_wizard.htm?action=report.schedule.report.submit_wmenu&c_master="+linkIdValue+"&refresh=Y");
+ setDrillDownImage(column.getLinkImg());
+ setConfirmationText(null);
+ } else if(column.getColumnId().equals("run")) {
+ setDrillDownLink("raptor.htm?action=report.run.container&c_master="+linkIdValue+"&refresh=Y");
+ setDrillDownImage(column.getLinkImg());
+ setConfirmationText(null);
+ } else {
+ if (column.getLinkURL() != null) {
+ StringBuffer sb = new StringBuffer();
+
+ if (column.getLinkForm() == null) {
+ sb.append("<a href=\"");
+ sb.append(column.getLinkURL());
+ sb.append(nvl(linkIdValue));
+ if (column.getLinkConfirmMsg() != null) {
+ sb.append(" onClick=\"return confirm('");
+ sb.append(column.getLinkConfirmMsg());
+ sb.append("');\"");
+ }
+ sb.append("\">");
+ if (column.getLinkImg() != null) {
+ sb.append("<img src=\"");
+ sb.append(column.getLinkImg());
+ sb.append("\"");
+ sb.append(column.getLinkImgSizeHtml());
+ sb.append(" border=\"0\"");
+ sb.append(column.getLinkTitle() != null ? " alt=\""
+ + column.getLinkTitle()/*
+ * +(column.isDeleteLink()?"
+ * "+linkIdValue:"")
+ */
+ + "\"" : "");
+ sb.append(">");
+ } else
+ sb.append(column.getLinkTitle());
+ sb.append("</a>");
+ } else {
+ sb.append("<input type=\"");
+ if (column.getLinkImg() != null) {
+ sb.append("image\" src=\"");
+ sb.append(column.getLinkImg());
+ sb.append("\"");
+ sb.append(column.getLinkImgSizeHtml());
+ sb.append(" border=\"0\"");
+ sb.append(column.getLinkTitle() != null ? " alt=\""
+ + column.getLinkTitle()/*
+ * +(column.isDeleteLink()?"
+ * "+linkIdValue:"")
+ */
+ + "\"" : "");
+ } else {
+ sb.append("submit\" value=\"");
+ sb.append(column.getLinkTitle());
+ sb.append("\"");
+ }
+ sb.append(" onClick=\"");
+ if (column.getLinkConfirmMsg() != null) {
+ sb.append("if(! confirm('");
+ sb.append(column.getLinkConfirmMsg());
+ sb.append("')) return false; ");
+ }
+ sb.append(column.getLinkURL());
+ sb.append(" document.");
+ sb.append(column.getLinkForm());
+ sb.append(".");
+ sb.append(AppConstants.RI_REPORT_ID);
+ sb.append(".value='");
+ sb.append(nvl(linkIdValue));
+ sb.append("';");
+ sb.append(" document.");
+ sb.append(column.getLinkForm());
+ sb.append(".");
+ sb.append("refresh");
+ sb.append(".value='");
+ sb.append("Y");
+ sb.append("';\">");
+ } // else
+
+ setDrillDownLink(sb.toString());
+ } // if
+ }
+ } // SearchResultField
+
+ public String getDisplayValue() {
+ return displayValue;
+ }
+
+ public String getAlignment() {
+ return alignment;
+ }
+
+ public String getDrillDownLink() {
+ return drillDownLink;
+ }
+
+ public void setDisplayValue(String displayValue) {
+ this.displayValue = nvl(displayValue);
+ }
+
+ public void setAlignment(String alignment) {
+ this.alignment = alignment;
+ }
+
+ public void setDrillDownLink(String drillDownLink) {
+ this.drillDownLink = drillDownLink;
+ }
+
+ public String getTooltipValue() {
+ return (displayValue.length() == 0) ? " " : displayValue;
+ }
+
+ /*public String getAlignmentHtml() {
+ return (alignment.length() == 0) ? "" : (" align=" + alignment);
+ }*/
+
+ /*public String getDisplayValueLinkHtml() {
+ if (nvl(drillDownLink).length() == 0)
+ return getDisplayValueHtml();
+ else
+ return getDrillDownLink();
+ } // getDisplayValueLinkHtml*/
+
+ public String getColumnId() {
+ return columnId;
+ }
+
+ public void setColumnId(String columnId) {
+ this.columnId = columnId;
+ }
+
+
+} // SearchResultField
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.search;
+
+import java.util.*;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+
+public class SearchResultJSON{
+
+ public ArrayList<SearchResultColumn> searchResultColumns = new ArrayList<SearchResultColumn>();
+
+ public ArrayList<SearchResultRow> searchResultRows = new ArrayList<SearchResultRow>();
+
+
+
+
+
+
+ public ArrayList<SearchResultColumn> getSearchResultColumns() {
+ return searchResultColumns;
+ }
+
+ public void setSearchResultColumns(ArrayList<SearchResultColumn> searchResultColumns) {
+ this.searchResultColumns = searchResultColumns;
+ }
+
+ public ArrayList<SearchResultRow> getSearchResultRows() {
+ return searchResultRows;
+ }
+
+ public void setSearchResultRows(ArrayList<SearchResultRow> searchResultRows) {
+ this.searchResultRows = searchResultRows;
+ }
+
+ public void addColumn(SearchResultColumn column) {
+ searchResultColumns.add(column);
+ } // addColumn
+
+ public SearchResultColumn getColumn(int index) {
+ return (SearchResultColumn) searchResultColumns.get(index);
+ } // getColumn
+
+ public int getNumColumns() {
+ return searchResultColumns.size();
+ } // getNumColumns
+
+ public int getNumRows() {
+ return searchResultRows.size();
+ } // getNumRows
+
+ public SearchResultRow getRow(int index) {
+ return (SearchResultRow) searchResultRows.get(index);
+ } // getRow
+
+
+ private String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ private String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+} // SearchResultJSON
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.model.search;
+
+import java.util.*;
+
+class ColumnContent {
+ String columnId;
+ SearchResultField searchresultField;
+
+ public ColumnContent(String columnId, SearchResultField searchresultField) {
+ this.columnId = columnId;
+ this.searchresultField = searchresultField;
+ }
+ public String getColumnId() {
+ return columnId;
+ }
+ public void setColumnId(String columnId) {
+ this.columnId = columnId;
+ }
+ public SearchResultField getSearchresultField() {
+ return searchresultField;
+ }
+ public void setSearchresultField(SearchResultField searchresultField) {
+ this.searchresultField = searchresultField;
+ }
+
+
+
+}
+public class SearchResultRow extends ArrayList {
+
+
+ //private SearchResultField searchresultField;
+ 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 SearchResultField getNext() {
+ return hasNext() ? getSearchResultField(nextElemIdx++) : null;
+ } // getNext
+
+ public SearchResultField getSearchResultField(int idx) {
+ return (SearchResultField) get(idx);
+ } // getRowHeader
+
+ public void addSearchResultField(SearchResultField searchResultField) {
+ add(searchResultField);
+ } // addSearchResultField
+
+ public void addSearchResultField(int idx, SearchResultField searchResultField) {
+ add(idx, searchResultField);
+ } // addSearchResultField
+
+ public void addColumnContent(ColumnContent cc ) {
+
+ add(cc);
+ } // addSearchResultField
+
+ public void addColumnContent(int idx, ColumnContent cc) {
+ add(idx, cc);
+ } // addSearchResultField
+
+
+} // SearchResultRow
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.scheduler;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.math.BigDecimal;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Types;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.system.DbUtils;
+
+//import oracle.jdbc.*;
+//import oracle.sql.BLOB;
+
+
+public class SchedulerUtil {
+
+ private Connection conn = null;
+
+ protected Connection getConnection() {
+ return conn;
+ }
+
+ protected void setConnection(Connection _conn) {
+ conn = _conn;
+ }
+
+ protected Connection init() throws SQLException, ReportSQLException{
+ if(conn != null)
+ return conn;
+ conn = DbUtils.getConnection();
+ return conn;
+ }
+
+ protected void closeConnection() throws SQLException {
+ if(conn != null) conn.close();
+ }
+
+ public void insertOrUpdate(String sql) throws SQLException, ReportSQLException {
+
+ Statement stat = null;
+ try{
+ //conn = getConnection();
+ stat = conn.createStatement();
+ stat.executeUpdate(sql);
+
+ } finally{
+ stat.close();
+ //conn.close();
+ }
+ }
+
+ public void updateBinaryStream(String sql, BigDecimal id, InputStream is, int size) throws SQLException, ReportSQLException, IOException {
+
+ // cludge hack for oracle databases
+ if(conn.getMetaData().getDatabaseProductName().toLowerCase().contains("oracle")) {
+/* updateBlob(sql,id,is,size);
+*/ throw new ReportSQLException("only maria db support for this ");
+
+ }
+
+ PreparedStatement stat = null;
+ try {
+ stat = conn.prepareStatement(sql);
+ stat.setBigDecimal(2, id);
+ stat.setBinaryStream(1, is, size);
+ stat.executeUpdate();
+
+ } finally{
+ stat.close();
+ }
+
+ }
+
+ /*public void updateBlob(String sql, BigDecimal id, InputStream is, int size) throws SQLException, ReportSQLException, IOException {
+ PreparedStatement stat = null;
+ OutputStream out = null;
+ BLOB blob = null;
+ try {
+ stat = conn.prepareStatement(sql);
+ blob = BLOB.createTemporary(conn,false, BLOB.DURATION_SESSION);
+ out = blob.getBinaryOutputStream();
+
+ int read;
+ while((read = is.read()) != -1) {
+ out.write(read);
+ }
+ out.flush();
+
+ stat.setBigDecimal(2, id);
+ stat.setBlob(1, blob);
+ stat.executeUpdate();
+
+ }
+ catch (SQLException sqL) {
+ sqL.printStackTrace();
+ }
+ finally{
+ out.close();
+ stat.close();
+ }
+
+ }*/
+
+
+ public void insertOrUpdateWithPrepared(String sql, List<Object> params, List<Integer> types) throws SQLException, ReportSQLException {
+
+ PreparedStatement stat = null;
+ try{
+ //conn = getConnection();
+ stat = conn.prepareStatement(sql);
+ conn.getMetaData();
+ int i2;
+ int paramLength = params.size();
+ for(int i = 0 ; i< paramLength ; i++) {
+ i2 = i+1;
+ Object param = params.get(i);
+ int type = types.get(i);
+
+ if(param.equals("NULL")) {
+ stat.setNull(i2, type);
+ }
+ else if(type == Types.VARCHAR) {
+ stat.setString(i2, (String)param);
+ }
+ else if(type == Types.INTEGER) {
+ stat.setInt(i2, (Integer)param);
+ }
+ else if(type == Types.NUMERIC) {
+ stat.setLong(i2, (Long)param);
+ }
+ else if(type == Types.DOUBLE) {
+ stat.setDouble(i2, (Double)param);
+ }
+ else if(type == Types.DATE) {
+ stat.setDate(i2, (java.sql.Date)param);
+ }
+ else if(type == Types.TIMESTAMP) {
+ stat.setTimestamp(i2, (java.sql.Timestamp)param);
+ }
+ else if(type == Types.BIGINT) {
+ stat.setBigDecimal(i2, (BigDecimal)param);
+ }
+ else
+ throw new SQLException("Unidentified Object; Please contact admin and have this method updated with the current object type");
+
+ }
+
+ stat.executeUpdate();
+
+ } finally{
+ stat.close();
+ //conn.close();
+ }
+ }
+
+
+ public Object getSingleResult(String sql, String fieldname) throws SQLException, ReportSQLException{
+
+ Statement stat = null;
+ ResultSet rs = null;
+ Object o=null;
+ try{
+ //conn = getConnection();
+ stat = conn.createStatement();
+ rs = stat.executeQuery(sql);
+
+ while (rs.next()) {
+ o = rs.getObject(fieldname);
+ }
+ }
+ catch(SQLException sqlE){
+ sqlE.printStackTrace();
+ }
+
+ finally{
+ if(rs!=null)
+ rs.close();
+ if(stat!=null)
+ stat.close();
+ //conn.close();
+ }
+ return o;
+ }
+
+ public InputStream getDBStream(String sql, String fieldname) throws SQLException, ReportSQLException, IOException{
+
+ // cludge hack for oracle databases
+ if(conn.getMetaData().getDatabaseProductName().toLowerCase().contains("oracle")) {
+ /*return getDBBlob(sql,fieldname);*/
+ throw new ReportSQLException("only maria db support for this ");
+
+ }
+
+
+ Statement stat = null;
+ ResultSet rs = null;
+ InputStream o=null;
+ try{
+ //conn = getConnection();
+ stat = conn.createStatement();
+ rs = stat.executeQuery(sql);
+
+ while (rs.next()) {
+ o = rs.getBinaryStream(fieldname);
+ }
+ }
+ catch(SQLException sqlE){
+ sqlE.printStackTrace();
+ }
+
+ finally{
+ if(rs!=null)
+ rs.close();
+ if(stat!=null)
+ stat.close();
+ //conn.close();
+ }
+ return o;
+ }
+
+ /*public InputStream getDBBlob(String sql, String fieldname) throws SQLException, ReportSQLException, IOException{
+
+
+ Statement stat = null;
+ ResultSet rs = null;
+ BLOB blob=null;
+ ByteArrayInputStream in = null;
+ try{
+ stat = conn.createStatement();
+ rs = stat.executeQuery(sql);
+
+ if (rs.next()) {
+ blob = ((OracleResultSet) rs).getBLOB(fieldname);
+ in = new ByteArrayInputStream(blob.getBytes(1,(int)blob.length()));
+
+ }
+ }
+ catch(SQLException sqlE){
+ sqlE.printStackTrace();
+ }
+
+ finally{
+ if(rs!=null)
+ rs.close();
+ if(stat!=null)
+ stat.close();
+ //conn.close();
+ }
+ return in;
+ }
+ */
+
+ public void getAndExecute(String sql, Executor executor) throws SQLException, ReportSQLException{
+ //Connection conn = getConnection();
+ Statement stat = conn.createStatement();
+ ResultSet rs = stat.executeQuery(sql);
+
+
+ while (rs.next()) {
+ executor.execute(rs);
+ }
+
+ if(rs!=null)
+ rs.close();
+ if(stat!=null)
+ stat.close();
+ //conn.close();
+ }
+
+ interface Executor{
+ public void execute(ResultSet rs) throws SQLException;
+ }
+
+
+
+
+
+
+ public static Date trunc_hour(Date v_date) {
+
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(v_date);
+ calendar.set(Calendar.MILLISECOND, 0);
+ calendar.set(Calendar.SECOND, 0);
+ calendar.set(Calendar.MINUTE, 0);
+ return calendar.getTime();
+ }
+
+ public static Date add_hours(Date v_date, int i) {
+
+ Calendar cal = Calendar.getInstance();
+ cal.setTime(v_date);
+ cal.add(Calendar.HOUR, i);
+ return cal.getTime();
+ }
+
+ public static Date add_months(Date v_date, int i) {
+
+ Calendar cal = Calendar.getInstance();
+ cal.setTime(v_date);
+ cal.add(Calendar.MONTH, i);
+ return cal.getTime();
+ }
+
+ public static Date add_days(Date v_date, int i) {
+
+ Calendar cal = Calendar.getInstance();
+ cal.setTime(v_date);
+ cal.add(Calendar.DATE, i);
+ return cal.getTime();
+ }
+
+ public static Date to_date(String input, String format) {
+
+ Date date = null;
+ try {
+ date = new SimpleDateFormat(format, Locale.ENGLISH).parse(input);
+ } catch (Exception e) {
+ }
+ return date;
+ }
+
+ public static String to_date_str(Date input, String format) {
+
+ String date = null;
+ try {
+ date = new SimpleDateFormat(format, Locale.ENGLISH).format(input);
+ } catch (Exception e) {
+ }
+ return date;
+ }
+
+ public static String[] cr_dissecturl(String formfields, String delimiter){
+ if(formfields == null || formfields.isEmpty())
+ return new String[]{};
+ return formfields.split("&");
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.scheduler;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.math.BigDecimal;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.List;
+
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.scheduler.SchedulerUtil.Executor;
+import org.onap.portalsdk.analytics.system.Globals;
+
+
+
+
+public class SendEmail {
+
+SchedulerUtil schedulerUtil;
+
+ public SendEmail() {
+
+ }
+
+
+ public void sendEmail( String p_mail_server, String p_sender, String p_subject, String p_mail_text, String p_url, int p_file_type, int p_schedule_id, int p_time_interval, boolean p_send_attachment, int connectionTimeout) throws SQLException, ReportSQLException{
+
+ String allEmailAddr = "";
+ final List<String> emailArr = new ArrayList<String>();
+ //int count1 = 0;
+ String schedular_email;
+
+
+ schedular_email = (String) schedulerUtil.getSingleResult("select email from fn_user au, cr_report_schedule crs where CRS.SCHED_USER_ID = AU.USER_ID and CRS.SCHEDULE_ID = "+ p_schedule_id, "email");
+
+
+ String sql=Globals.getSchedulerUserEmails().replace("[p_schedule_id]", p_schedule_id+"");
+ schedulerUtil.getAndExecute(sql, new Executor() {
+
+ @Override
+ public void execute(ResultSet rs) throws SQLException {
+
+ emailArr.add(rs.getString("email"));
+ // count1 = count1 + 1
+ }
+
+ });
+
+ if (!p_send_attachment) {
+ http_to_blob(p_url, p_file_type, p_schedule_id, connectionTimeout);
+ }
+
+ int i = 0;
+ for (String email : emailArr) {
+ /* If the email address is invalid ignore that email address */
+ if (email.contains("@")) {
+
+ if (i == 0)
+ allEmailAddr = email;
+ else
+ allEmailAddr += ',' + email;
+
+ i++;
+ }
+ }
+
+ /*List<MailAttachment> mailAttachments = null;
+
+ if (p_file_type > 1 && p_send_attachment) {
+ mailAttachments = add_attachment(p_url, p_file_type, p_schedule_id, connectionTimeout);
+ }
+ AppUtils.notifyWithAttachments(p_mail_text, emailArr.toArray(new String[emailArr.size()]), p_sender, p_subject, new String[] { schedular_email }, null, mailAttachments, true);
+ */
+ }
+
+ class HistRec {
+
+ String file_blob;
+ BigDecimal rep_id;
+ BigDecimal hist_id;
+ String file_name;
+ int sched_user_id;
+ String recurrence;
+ int file_size = 0;
+ String raptor_url;
+ int schedule_id;
+ int file_type_id;
+ int user_id;
+ String deleted_yn;
+ }
+
+
+ private HistRec http_to_blob(String p_url, int v_file_type, int p_schedule_id, int connectionTimeout) throws SQLException , ReportSQLException{
+
+
+ final HistRec v_hist_rec = initializeVHistoryRecord(p_url, v_file_type, p_schedule_id);
+ HttpURLConnection con = null;
+ try {
+ URL url = new URL(p_url);
+ con = (HttpURLConnection) url.openConnection();
+ con.setConnectTimeout(connectionTimeout*1000);
+ con.setRequestMethod("GET");
+ schedulerUtil.insertOrUpdate("INSERT INTO cr_filehist_log (SCHEDULE_ID, url, notes, run_time) VALUES ("+ p_schedule_id +",'" + p_url+ "','http_to_blob: Initiated HTTP request', " + Globals.getCurrentDateString() + " )");
+ int responseCode = con.getResponseCode();
+ String outputFolder = Globals.getProjectFolder() + java.io.File.separator + Globals.getOutputFolder();
+ String fileName = v_hist_rec.file_name;
+ createFile(con, outputFolder, fileName);
+
+ File readFile = new File(outputFolder + java.io.File.separator + fileName);
+ // need to revist this conversion; may not be safe for large file sizes
+ v_hist_rec.file_size = (int)readFile.length();
+
+ schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url +"', 'http_to_blob: http response recieved. Code " + responseCode + "', " + Globals.getCurrentDateString() + " )");
+
+ //v_hist_rec.file_blob = response.toString();
+ //v_hist_rec.file_size = v_hist_rec.file_blob.length();
+
+ List<Object> params = new ArrayList<Object>();
+ List<Integer> types = new ArrayList<Integer>();
+ prepareHisRecUpdate(v_hist_rec, params, types);
+
+ schedulerUtil
+ .insertOrUpdateWithPrepared("INSERT INTO cr_report_file_history(HIST_ID, SCHED_USER_ID, SCHEDULE_ID, USER_ID, REP_ID, RUN_DATE, RECURRENCE, FILE_TYPE_ID, FILE_NAME, FILE_SIZE, RAPTOR_URL, ERROR_YN, ERROR_CODE, DELETED_YN, DELETED_BY)"
+ + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
+ params, types
+ );
+
+ FileInputStream fileStream = new FileInputStream(readFile);
+ schedulerUtil.updateBinaryStream("update cr_report_file_history set file_blob = ? where hist_id = ?", v_hist_rec.hist_id, fileStream, v_hist_rec.file_size);
+ fileStream.close();
+
+ String userAddRecSql =
+ Globals.getSchedulerUserEmails().replace("[p_schedule_id]", p_schedule_id+"");
+
+ schedulerUtil.getAndExecute(userAddRecSql, new Executor() {
+
+ @Override
+ public void execute(ResultSet rs) throws SQLException {
+
+ try {
+ schedulerUtil.insertOrUpdate("INSERT INTO CR_HIST_USER_MAP (HIST_ID, USER_ID) values ( " + v_hist_rec.hist_id + "," + rs.getInt("user_id") + ")");
+ } catch (ReportSQLException e) {
+ throw new SQLException(e.getMessage());
+ }
+ }
+
+ });
+
+ schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url + "','Success: http_to_blob', " + Globals.getCurrentDateString() + " )");
+
+
+ } catch (Exception e) {
+ schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url + "', 'Failure: http_to_blob : Exception" + e.getMessage() +"', " + Globals.getCurrentDateString() + " )");
+ e.printStackTrace();
+ } finally {
+ if(con != null)
+ con.disconnect();
+ }
+ return v_hist_rec;
+
+ }
+
+
+ protected void prepareHisRecUpdate(final HistRec v_hist_rec, List<Object> params,
+ List<Integer> types) {
+ params.add( v_hist_rec.hist_id);
+ types.add(Types.BIGINT);
+ params.add( v_hist_rec.sched_user_id);
+ types.add(Types.INTEGER);
+ params.add( v_hist_rec.schedule_id);
+ types.add(Types.INTEGER);
+ params.add( v_hist_rec.user_id);
+ types.add(Types.INTEGER);
+ params.add( v_hist_rec.rep_id);
+ types.add(Types.BIGINT);
+ params.add( new java.sql.Date(Calendar.getInstance().getTime().getTime()));
+ types.add(Types.DATE);
+ params.add( v_hist_rec.recurrence);
+ types.add(Types.VARCHAR);
+ params.add( v_hist_rec.file_type_id);
+ types.add(Types.INTEGER);
+ params.add( v_hist_rec.file_name);
+ types.add(Types.VARCHAR);
+ params.add( v_hist_rec.file_size);
+ types.add(Types.INTEGER);
+ params.add( v_hist_rec.raptor_url);
+ types.add(Types.VARCHAR);
+ params.add( "N");
+ types.add(Types.VARCHAR);
+ params.add( "NULL");
+ types.add(Types.INTEGER);
+ params.add( v_hist_rec.deleted_yn);
+ types.add(Types.VARCHAR);
+ params.add(v_hist_rec.sched_user_id );
+ types.add(Types.INTEGER);
+ }
+
+
+ protected HistRec initializeVHistoryRecord(String p_url, int v_file_type,
+ int p_schedule_id) throws SQLException,
+ ReportSQLException {
+
+ final HistRec v_hist_rec = new HistRec();
+
+ v_hist_rec.rep_id = (BigDecimal) schedulerUtil.getSingleResult("SELECT rep_id FROM cr_report_schedule WHERE schedule_id =" + p_schedule_id, "rep_id");
+
+ Object sequenceId = schedulerUtil.getSingleResult(Globals.getSequenceNextVal().replace("[sequenceName]", "seq_cr_report_file_history"),"ID");
+
+ if(sequenceId instanceof Long)
+ v_hist_rec.hist_id = new BigDecimal((Long)sequenceId);
+ else if(sequenceId instanceof BigDecimal)
+ v_hist_rec.hist_id = (BigDecimal)sequenceId;
+
+ v_hist_rec.file_name = (String) schedulerUtil.getSingleResult("select translate(title||to_char( "+ Globals.getCurrentDateString() + ",'MM-dd-yyyyHH24:mm:ss'), "
+ + "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'||'():;.-`~^\\|'||chr(34)||chr(39)||chr(9)||' ', "
+ + "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')|| "+ v_hist_rec.hist_id +" as title FROM cr_report WHERE rep_id = "+v_hist_rec.rep_id, "title");
+
+
+ class File {
+
+ String file_name;
+ String file_ext;
+ }
+ final File file = new File();
+ schedulerUtil.getAndExecute("select template_file from cr_report_template_map where report_id = " + v_hist_rec.rep_id, new Executor() {
+
+ @Override
+ public void execute(ResultSet rs) throws SQLException {
+
+ file.file_name = rs.getString("template_file");
+ file.file_ext = file.file_name.substring(file.file_name.indexOf('.'));
+
+ }
+ });
+
+ if (v_file_type == 2) {
+ v_hist_rec.file_name = v_hist_rec.file_name + ".pdf";
+
+ } else if (v_file_type == 4) {
+ v_hist_rec.file_name = v_hist_rec.file_name + ".xls";
+
+ } else if (v_file_type == 5) {
+ if (file.file_name != null && file.file_ext.length() > 0) {
+ v_hist_rec.file_name = v_hist_rec.file_name + file.file_ext;
+ } else {
+ v_hist_rec.file_name = v_hist_rec.file_name + ".xlsx";
+ }
+ } else if (v_file_type == 3) {
+ v_hist_rec.file_name = v_hist_rec.file_name + ".csv";
+
+ }
+
+
+ schedulerUtil.getAndExecute("select sched_user_id, rep_id, recurrence from cr_report_schedule where schedule_id="+p_schedule_id, new Executor() {
+
+ @Override
+ public void execute(ResultSet rs) throws SQLException {
+ v_hist_rec.sched_user_id = rs.getInt("sched_user_id");
+ v_hist_rec.rep_id = rs.getBigDecimal("rep_id");
+ v_hist_rec.recurrence = rs.getString("recurrence");
+ }
+ });
+
+
+ v_hist_rec.file_size = 0;
+ v_hist_rec.raptor_url = p_url;
+ v_hist_rec.schedule_id = p_schedule_id;
+ v_hist_rec.file_type_id = v_file_type;
+ v_hist_rec.user_id = v_hist_rec.sched_user_id;
+ v_hist_rec.deleted_yn = "N";
+
+ return v_hist_rec;
+ }
+
+
+
+ /*private List<MailAttachment> add_attachment(String p_url, int v_file_type, int p_schedule_id, int connectionTimeout) throws SQLException,ReportSQLException{
+
+
+ List<MailAttachment> mailAttachmentList = new ArrayList<MailAttachment>();
+ final HistRec vHistRec = initializeVHistoryRecord(p_url, v_file_type, p_schedule_id);
+
+ /*
+ refer to http_to_blob for more details
+
+ String v_content_type;
+ String v_content_disposition;
+ int transfer_timeout_limit = 1800;
+ String v_title;
+
+ if (v_file_type == 2) {
+ v_content_type = "application/pdf";
+ v_content_disposition ="inline; filename=\""+v_title+".pdf\"";
+
+ }else if(v_file_type == 4){
+ v_content_type = "application/excel";
+ v_content_disposition ="inline; filename=\""+v_title+".xls\"";
+
+ }else if(v_file_type == 5){
+ v_content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
+
+ if (file.file_ext != null && file.file_ext.length() > 0) {
+ v_content_disposition ="inline; filename=\""+v_title+ file.file_ext+"\"";
+ if (".xlsm".equals(file.file_ext)) {
+ v_content_type = "application/vnd.ms-excel.sheet.macroEnabled.12";
+ }
+ } else {
+ v_content_disposition ="inline; filename=\""+v_title+".xlsx\"";
+ };
+ }else if(v_file_type == 3){
+ v_content_type = "application/csv";
+ v_content_disposition ="inline; filename=\""+v_title+".csv\"";
+
+ }
+ * ... /
+ HttpURLConnection con = null;
+ try {
+ URL url = new URL(p_url);
+ con = (HttpURLConnection) url.openConnection();
+ con.setConnectTimeout(connectionTimeout*1000);
+ con.setRequestMethod("GET");
+ schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'"+ p_url +"', 'Success: http request began.', " + Globals.getCurrentDateString() + " )");
+ int responseCode = con.getResponseCode();
+
+ String outputFolder = Globals.getProjectFolder() + java.io.File.separator + Globals.getOutputFolder();
+ String fileName = vHistRec.file_name;
+ createFile(con, outputFolder, fileName);
+
+ MailAttachment mailAttachment = new MailAttachment();
+ mailAttachment.setAttachmentType(MailAttachment.FILE_ATTACHMENT);
+ mailAttachment.setFilePathName(outputFolder);
+ mailAttachment.setFileName(fileName);
+ mailAttachmentList.add(mailAttachment);
+
+ schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url +"', 'Success: http response recieved. Code " + responseCode + "', " + Globals.getCurrentDateString() + " )");
+
+ schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url + "','Success: added attachment', " + Globals.getCurrentDateString() + " )");
+
+ } catch (Exception e) {
+ schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url + "', 'Failure: adding attachment : Exception" + e.getMessage() +"', " + Globals.getCurrentDateString() + " )");
+ e.printStackTrace();
+ } finally {
+ if(con != null)
+ con.disconnect();
+ }
+
+
+ return mailAttachmentList;
+ }*/
+
+
+ void createFile(HttpURLConnection con, String outputFolder, String fileName)
+ throws IOException, FileNotFoundException {
+ //BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
+ InputStream in = con.getInputStream();
+
+ try {
+
+ FileOutputStream out = new FileOutputStream(outputFolder + java.io.File.separator + fileName );
+ try {
+ int inputLine;
+
+ while ((inputLine = in.read()) != -1) {
+ out.write(inputLine);
+ }
+ out.flush();
+ }
+ finally {
+ out.close();
+ }
+
+ }
+ finally {
+ in.close();
+ }
+ }
+
+
+ public SchedulerUtil getSchedulerUtil() {
+ return schedulerUtil;
+ }
+
+
+ public void setSchedulerUtil(SchedulerUtil schedulerUtil) {
+ this.schedulerUtil = schedulerUtil;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.scheduler;
+
+import java.math.BigDecimal;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.UUID;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.scheduler.SchedulerUtil.Executor;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.Log;
+
+public class SendNotifications {
+
+ SchedulerUtil schedulerUtil;
+ public SendEmail sendEmail;
+
+ public SendNotifications() throws Exception {
+ schedulerUtil = new SchedulerUtil();
+ sendEmail = new SendEmail();
+ sendEmail.setSchedulerUtil(schedulerUtil);
+ init();
+ }
+
+
+ public void deInit() throws SQLException {
+ schedulerUtil.closeConnection();
+ }
+
+ public void init() throws SQLException, ReportSQLException {
+ schedulerUtil.init();
+ }
+
+ public void send_notification(String p_mail_server, String p_sender, String p_system_name, String p_system_url, int connectionTimeout) throws RaptorException, Exception {
+
+ System.out.println(p_mail_server + " " + p_sender + " " + p_system_name + " " + p_system_url);
+ int p_time_interval = Globals.getSchedulerInterval();
+ int v_num_recs = 0;
+ String v_gen_key;
+ BigDecimal v_id = null;
+ String v_url;
+ String v_r_action = "report.download.pdf";
+ String v_email_msg;
+ String v_formfields;
+ // String error_m;
+ // int transfer_timeout_limit = 1800;
+ // boolean v_attach_email_yn = true;
+ int v_schedule_id;
+ Date v_touch_date;
+ // Exception for_rec;
+
+ Connection conn = schedulerUtil.getConnection();
+ Statement stat = conn.createStatement();
+
+ String CNotificationsql =
+ /*
+ "SELECT x.rep_id, x.schedule_id, x.conditional_yn, x.condition_large_sql, x.notify_type, x.max_row, x.initial_formfields, x.processed_formfields, r.title, x.user_id "
+ + "FROM ("
+ + "SELECT rs.rep_id, rs.schedule_id, rs.sched_user_id user_id, rs.conditional_yn, rs.condition_large_sql, "
+ + "rs.notify_type, rs.max_row, rs.initial_formfields, rs.processed_formfields "
+ + "FROM cr_report_schedule rs "
+ + "WHERE rs.enabled_yn='Y' "
+ + "AND rs.start_"
+ + "date <= sysdate "
+ + "AND (rs.end_date >= sysdate or rs.end_date is null ) "
+ + "AND rs.run_date IS NOT NULL "
+ + ") x, cr_report r "
+ + "WHERE x.rep_id = r.rep_id ";
+ */
+
+ Globals.getAvailableSchedules().replace("[currentDate]", Globals.getCurrentDateString());
+
+
+ ResultSet rs = stat.executeQuery(CNotificationsql);
+
+ while (rs.next()) {
+
+ v_schedule_id = rs.getInt("schedule_id");
+ int offset = get_report_sched_offset(rs.getInt("rep_id"), v_schedule_id);
+
+ if(offset >= p_time_interval) continue;
+
+
+ v_touch_date = (Date) schedulerUtil.getSingleResult("select touch_date from cr_report_email_sent_log where schedule_id = " + v_schedule_id + " and log_id = (select max(log_id) from cr_report_email_sent_log where schedule_id = " + v_schedule_id + ")", "touch_date");
+ if (v_touch_date != null) {
+ if (Math.abs(System.currentTimeMillis() - v_touch_date.getTime()) /1000 < (p_time_interval - 1)) {
+ return;
+ }
+ }
+
+ if ("Y".equals(rs.getString("conditional_yn"))) {
+
+ v_num_recs = (Integer) schedulerUtil.getSingleResult("select count(*) count from (" + rs.getString("condition_large_sql") + " )", "count");
+ }
+
+ if (v_num_recs > 0 || "N".equals(rs.getString("conditional_yn"))) {
+
+ v_gen_key = ("Z" + UUID.randomUUID()).toString().substring(0,24); // 25 character string
+ Object sequenceId = schedulerUtil.getSingleResult(Globals.getSequenceNextVal().replace("[sequenceName]", "seq_email_sent_log_id"), "id");
+
+ if(sequenceId instanceof Long)
+ v_id = new BigDecimal((Long)sequenceId);
+ else if(sequenceId instanceof BigDecimal)
+ v_id = (BigDecimal)sequenceId;
+
+ schedulerUtil.insertOrUpdate("insert into cr_report_email_sent_log (log_id, gen_key, schedule_id, rep_id, user_id, touch_date) values (" + v_id + ",'" + v_gen_key + "'," + rs.getInt("schedule_id") + "," + rs.getInt("rep_id") + "," + rs.getInt("user_id") + ", " + Globals.getCurrentDateString() + " )");
+
+ int notify_type = rs.getInt("notify_type");
+ if (notify_type == 4)
+ v_r_action = "report.download";
+ else if (notify_type == 2)
+ v_r_action = "report.download.pdf";
+ else if (notify_type == 3)
+ v_r_action = "report.csv.download";
+ else if (notify_type == 5)
+ v_r_action = "report.download.excel2007";
+ else if (notify_type == 6)
+ v_r_action = "download.all";
+
+ if (rs.getObject("processed_formfields") != null)
+ v_formfields = modify_formfields(v_schedule_id, rs.getString("processed_formFields"));
+ else
+ v_formfields = strip_formfields(v_schedule_id, rs.getString("initial_formfields"));
+
+ v_url = p_system_url + "&r_action=" + v_r_action + "&log_id=" + v_id + "&user_id=" + rs.getString("user_id") + "&pdfAttachmentKey=" + v_gen_key + "&download_limit=" + rs.getInt("max_row") + v_formfields;
+
+ boolean v_attach_email_yn = shouldSendAttachmentInEmail(v_schedule_id);
+
+ v_email_msg = "<html><body><p><b><u><i>" + p_system_name + " System Notification</i></u></b></p>" + "<p>Report <b>" + rs.getString("title") + "</b> is available for viewing.</p><p>You can view the report if it is attached. </br>"
+ + "If it is not attached, or you have problem to open it, you can log into Business Direct and run the report.</p>" + "</body></html>";
+
+ if (rs.getInt("notify_type") != 6) {
+
+ sendEmail.sendEmail(p_mail_server, p_sender, p_system_name + " System Notification: Report " + rs.getString("title") + " generated", v_email_msg, v_url, rs.getInt("notify_type"), v_schedule_id, p_time_interval, v_attach_email_yn,connectionTimeout);
+
+ } else {
+
+ // may not necessary
+ schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + v_schedule_id + ",'" + v_url + "'," + "'Success: http request began.', " + Globals.getCurrentDateString() + " )");
+ schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + v_schedule_id + ",'" + v_url + "'," + "'Success: http response recieved. Code resp.status_code '' desc '' resp.reason_phrase', " + Globals.getCurrentDateString() + " )");
+
+ }
+
+ schedulerUtil.insertOrUpdate("update cr_report_schedule set run_date = " + Globals.getCurrentDateString() +" where schedule_id=" + v_schedule_id);
+
+ schedulerUtil.insertOrUpdate("update cr_report_email_sent_log set sent_date= " + Globals.getCurrentDateString() +" , access_flag='N' where log_id=" + v_id);
+ schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + v_schedule_id + ",'" + v_url + "','Success: Email Sent', " + Globals.getCurrentDateString() + " )");
+
+ }
+
+ }
+
+ if(rs!=null)
+ rs.close();
+ if(stat!=null)
+ stat.close();
+ //conn.close();
+
+ }
+
+ private boolean shouldSendAttachmentInEmail(int v_schedule_id) throws SQLException, ReportSQLException {
+
+ String l_boolean = (String) schedulerUtil.getSingleResult("SELECT ATTACHMENT_YN from cr_report_schedule where schedule_id = " + v_schedule_id, "ATTACHMENT_YN");
+ if ("Y".equals(l_boolean))
+ return true;
+ return false;
+ }
+
+ private String strip_formfields(int v_schedule_id, String p_formfields) throws SQLException, ReportSQLException {
+
+ String v_formfields_insert = "";
+ String v_formfields_generate = "";
+ String v_name = "";
+ String v_value = "";
+
+
+ String[] column_values = schedulerUtil.cr_dissecturl(p_formfields, "&");
+
+ for(String column_value : column_values){
+ if(column_value == null || column_value.isEmpty())
+ continue;
+
+ v_name = column_value.substring(0, column_value.indexOf('='));
+ v_formfields_insert += column_value + "&";
+ v_value = column_value.substring(column_value.indexOf('=') + 1);
+ if (column_value.indexOf("_auto") > 0) {
+ v_formfields_generate = v_formfields_generate + v_name.substring(0, v_name.indexOf("_auto")) + "=" + v_value + "&";
+ } else {
+ v_formfields_generate = v_formfields_generate + column_value + "&";
+ }
+ }
+
+ schedulerUtil.insertOrUpdate("update CR_REPORT_SCHEDULE set processed_formfields ='" + v_formfields_insert + "' where schedule_id = " + v_schedule_id);
+
+ return v_formfields_generate.substring(0, v_formfields_generate.length());
+
+ }
+
+ private String modify_formfields(int v_schedule_id, String p_formfields) throws SQLException, ReportSQLException {
+
+ class Result {
+
+ String v_formfields_insert = "";
+ String v_formfields_generate = "";
+ String v_name = "";
+ String v_value = "";
+ Date v_date;
+ String v_hour = "";
+ String v_hour_value = "";
+ }
+
+ final Result result = new Result();
+
+ final String v_recurrence = (String) schedulerUtil.getSingleResult("select recurrence from cr_report_schedule where schedule_id = " + v_schedule_id, "recurrence");
+
+ String[] column_values = schedulerUtil.cr_dissecturl(p_formfields, "&");
+
+ for(String column_value : column_values){
+ if (column_value == null)
+ column_value = "";
+
+ if ("MONTHLY".equals(v_recurrence)) {
+ if (column_value.indexOf("_auto") > 0) {
+ result.v_name = column_value.substring(0, column_value.indexOf('='));
+ result.v_date = schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
+ result.v_value = schedulerUtil.add_months(result.v_date, 1).toString();
+
+ if (result.v_name.length() > 0) {
+ result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
+ result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value + "&";
+ }
+ } else {
+ result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
+ result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
+ }
+
+ } else if ("DAILY".equals(v_recurrence)) {
+ if (column_value.indexOf("_auto") > 0) {
+ result.v_name = column_value.substring(0, column_value.indexOf('='));
+ result.v_date = schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
+ result.v_value = schedulerUtil.add_months(result.v_date, 1).toString();
+
+ if (result.v_name.length() > 0) {
+ result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
+ result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value + "&";
+ }
+ } else {
+ result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
+ result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
+ }
+
+ } else if ("DAILY_MO_FR".equals(v_recurrence)) {
+ if (column_value.indexOf("_auto") > 0) {
+ result.v_name = column_value.substring(0, column_value.indexOf('='));
+ result.v_date = schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
+ SimpleDateFormat sdf = new SimpleDateFormat("EEE");
+ sdf.format(result.v_date);
+ if ("FRI".equals(result.v_date.toString())) {
+ result.v_date = schedulerUtil.add_days(result.v_date, 3);
+ } else if ("SAT".equals(result.v_date.toString())) {
+ result.v_date = schedulerUtil.add_days(result.v_date, 2);
+ } else {
+ result.v_date = schedulerUtil.add_days(result.v_date, 1);
+ }
+ result.v_value = result.v_date.toString();
+ if (result.v_name.length() > 0) {
+ result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
+ result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value + "&";
+ }
+
+ } else {
+ result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
+ result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
+ }
+
+ } else if ("HOURLY".equals(v_recurrence)) {
+
+ result.v_name = column_value.indexOf('=')>0?column_value.substring(0, column_value.indexOf('=')) : "";
+ if (column_value.indexOf("_auto") > 0) {
+
+
+ String[] column_values2 = schedulerUtil.cr_dissecturl(p_formfields, "&");
+
+ for(String column_value2 : column_values2){
+
+ String key = column_value2.substring(0, column_value2.indexOf("="));
+ if(key.equals(result.v_name.substring(0, result.v_name.indexOf("_auto"))) || key.equals(result.v_name.substring(0, result.v_name.indexOf("_Hr")))){
+ result.v_hour = column_value2;
+ }
+ }
+
+// schedulerUtil.getAndExecute("select c.column_value from table(CR_DISSECTURL(p_formfields)) c where substr(c.column_value, 1, instr(c.column_value, '=')-1) = substr(" + result.v_name + ",1,instr(" + result.v_name + ",'_auto')-1)||'_Hr'", new Executor() {
+//
+// @Override
+// public void execute(ResultSet rs) throws SQLException {
+//
+// result.v_hour = rs.getString("column_value");
+// }
+//
+// });
+
+ if (result.v_hour.length() > 0) {
+ result.v_hour_value = result.v_hour.substring(result.v_hour.indexOf('=') + 1);
+ }
+
+ result.v_date = schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1) + " " + result.v_hour_value, "mm/dd/yyyy HH24:MI:SS");
+
+ result.v_value = schedulerUtil.to_date_str(schedulerUtil.add_hours(result.v_date, 1), "mm/dd/yyyy HH24");
+
+ if (result.v_name.length() > 0) {
+ if (result.v_hour.length() > 0) {
+
+ result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value.substring(0, 10) + "&" + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "_Hr=" + result.v_value.substring(11, 13);
+ result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value.substring(0, 10) + "&" + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "_Hr="
+ + result.v_value.substring(11, 13) + "&";
+
+ } else {
+ result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
+ result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value + "&";
+ }
+ }
+ }
+ if (column_value.indexOf("_Hr") <= 0) {
+ result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
+ result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
+ }
+ } else if ("WEEKLY".equals(v_recurrence)) {
+
+ if (column_value.indexOf("_auto") > 0) {
+ result.v_name = column_value.substring(0, column_value.indexOf('='));
+ result.v_date = schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
+ result.v_value = schedulerUtil.add_days(result.v_date, 7).toString();
+
+ if (result.v_name.length() > 0) {
+ result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
+ result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value + "&";
+ }
+
+ } else {
+ result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
+ result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
+ }
+
+ } else {
+ if (column_value.indexOf("_auto") > 0) {
+ result.v_name = column_value.substring(0, column_value.indexOf('='));
+ result.v_date = schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
+ result.v_value = schedulerUtil.add_days(result.v_date, 7).toString();
+ if (result.v_name.length() > 0) {
+ result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
+ result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value + "&";
+ }
+
+ } else {
+ result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
+ result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
+ }
+ }
+ }
+
+ schedulerUtil.insertOrUpdate("update CR_REPORT_SCHEDULE set processed_formfields ='" + result.v_formfields_insert + "' where schedule_id =" + v_schedule_id);
+ return "&" + result.v_formfields_generate.substring(0, result.v_formfields_generate.length());
+ }
+
+ private int get_report_sched_offset(int p_rep_id, int p_schedule_id) throws SQLException, ReportSQLException {
+
+ class CrReportSchedule {
+
+ Date run_date;
+ String recurrence;
+ }
+ Date v_last_date = null;
+ Date v_sysdate = new Date();
+
+ final CrReportSchedule v_report_schedule_rec = new CrReportSchedule();
+
+ schedulerUtil.getAndExecute("SELECT * FROM cr_report_schedule WHERE rep_id = " + p_rep_id + " and schedule_id = " + p_schedule_id, new Executor() {
+
+ @Override
+ public void execute(ResultSet rs) throws SQLException {
+
+ v_report_schedule_rec.recurrence = rs.getString("recurrence");
+ java.sql.Timestamp runDate = rs.getTimestamp("run_date");
+ v_report_schedule_rec.run_date = new Date(runDate.getTime()) ;
+ }
+
+ });
+
+ if (v_report_schedule_rec.run_date == null || v_report_schedule_rec.run_date.compareTo(v_sysdate) > 0) {
+ return Integer.MAX_VALUE;
+ }
+
+ Date v_next_date = v_report_schedule_rec.run_date;
+
+ while (v_next_date.compareTo(v_sysdate) < 0) {
+
+ if ("HOURLY".equals(v_report_schedule_rec.recurrence)) {
+ v_next_date = SchedulerUtil.add_hours(v_next_date, 1);
+ } else if ("DAILY".equals(v_report_schedule_rec.recurrence)) {
+ v_next_date = SchedulerUtil.add_days(v_next_date, 1);
+ } else if ("DAILY_MO_FR".equals(v_report_schedule_rec.recurrence)) {
+ SimpleDateFormat sdf = new SimpleDateFormat("EEE");
+ sdf.format(v_next_date);
+ if ("FRI".equals(v_next_date.toString())) {
+ v_next_date = SchedulerUtil.add_days(v_next_date, 3);
+ } else if ("SAT".equals(v_next_date.toString())) {
+ v_next_date = SchedulerUtil.add_days(v_next_date, 2);
+ } else {
+ v_next_date = SchedulerUtil.add_days(v_next_date, 1);
+ }
+ } else if ("WEEKLY".equals(v_report_schedule_rec.recurrence)) {
+ v_next_date = SchedulerUtil.add_days(v_next_date, 7);
+ } else if ("MONTHLY".equals(v_report_schedule_rec.recurrence)) {
+ v_next_date = SchedulerUtil.add_months(v_next_date, 1);
+ } else {
+ break;
+ }
+ v_last_date = v_next_date;
+ }
+
+ if (SchedulerUtil.trunc_hour(v_last_date).compareTo(SchedulerUtil.trunc_hour(v_sysdate)) == 0) {
+ return (int)(Math.abs (v_sysdate.getTime() - v_last_date.getTime()) / 1000);
+ } else {
+ // More than an hour
+ return 3601;
+ }
+ }
+
+ public SchedulerUtil getSchedulerUtil() {
+ return schedulerUtil;
+ }
+
+ public void setSchedulerUtil(SchedulerUtil schedulerUtil) {
+ this.schedulerUtil = schedulerUtil;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system;
+
+import java.io.File;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+import javax.servlet.http.*;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.util.*;
+
+public class AppUtils /* implements IAppUtils */{
+ private static String baseURL = null;
+
+ private AppUtils() {
+ }
+
+ /** ******************************************************** */
+
+ public static String generateFileName(HttpServletRequest request, String fileTypeExtension) {
+ return AppConstants.FILE_PREFIX + getUserID(request) + fileTypeExtension;
+ } // generateFileName
+
+ public static String generateUniqueFileName(HttpServletRequest request, String reportName, String fileTypeExtension) {
+ String formattedReportName = new HtmlStripper().stripSpecialCharacters(reportName);
+ String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date());
+ return formattedReportName+formattedDate+getUserID(request)+fileTypeExtension;
+ } // generateFileName
+
+ public static String getRequestValue(HttpServletRequest request, String valueID) {
+ String value = (String) request.getAttribute(valueID);
+ if (value == null)
+ value = request.getParameter(valueID);
+ return value;
+ } // getRequestValue
+
+ public static String getRequestNvlValue(HttpServletRequest request, String valueID) {
+ String value = getRequestValue(request, valueID);
+ return (value == null) ? "" : value;
+ } // getRequestValue
+
+ public static boolean getRequestFlag(HttpServletRequest request, String valueID) {
+ String value = getRequestNvlValue(request, valueID);
+ return value.toLowerCase().equals("true") || value.toUpperCase().startsWith("Y");
+ } // getRequestFlag
+
+ /** ******************************************************** */
+
+ public static String getUserID(HttpServletRequest request) {
+ return Globals.getAppUtils().getUserID(request);
+ } // getUserID
+
+ public static String getUserName(HttpServletRequest request) {
+ return Globals.getAppUtils().getUserName(request);
+ } // getUserName
+
+ public static String getUserName(String userId) {
+ return Globals.getAppUtils().getUserName(userId);
+ } // getUserName
+
+ public static String getUserEmail(String userId) {
+ return Globals.getAppUtils().getUserEmail(userId);
+ } // getUserEmail
+
+ public static String getUserEmail(HttpServletRequest request) {
+ return Globals.getAppUtils().getUserEmail(request);
+ } // getUserEmail
+
+ public static String getUserLoginId(HttpServletRequest request) {
+ return Globals.getAppUtils().getUserLoginId(request);
+ } // getUserLoginId
+
+ public static String getUserLoginId(String userId) {
+ return Globals.getAppUtils().getUserLoginId(userId);
+ } // getUserLoginId
+
+ public static String getUserBackdoorLoginId(HttpServletRequest request) {
+ return Globals.getAppUtils().getUserBackdoorLoginId(request);
+ } // getUserBackdoorLoginId
+
+ public static Vector getAllUsers(String customizedQuery, String param, boolean isAdmin) {
+ return Globals.getAppUtils().getAllUsers(customizedQuery, param, isAdmin);
+ } // getAllUsers
+
+ public static String getRoleName(String roleId) {
+ return Globals.getAppUtils().getRoleName(roleId);
+ } // getRoleName
+
+ public static Vector getAllRoles(String customizedQuery, String param, boolean isAdmin) {
+ return Globals.getAppUtils().getAllRoles(customizedQuery, param, isAdmin);
+ } // getAllRoles
+
+ public static boolean isUserInRole(HttpServletRequest request, String roleId) throws RaptorException {
+ return Globals.getAppUtils().isUserInRole(request,roleId);
+ } // isUserInRole
+
+// public static boolean isUserInRole(String userId, String roleId) throws RaptorException {
+// return Globals.getAppUtils().isUserInRole(userId, roleId);
+// } // isUserInRole
+
+ public static Vector getUserRoles(HttpServletRequest request) throws RaptorException {
+ return Globals.getAppUtils().getUserRoles(request);
+ } // getUserRoles
+
+ public static Vector getUserRoles(String userID) throws RaptorException {
+ return Globals.getAppUtils().getUserRoles(userID);
+ } // getUserRoles
+
+// public static Vector getUserRoles(HttpServletRequest request) throws RaptorException {
+// return Globals.getAppUtils().getUserRoles(request);
+// } // getUserRoles
+
+ public static void resetUserCache() {
+ Globals.getAppUtils().resetUserCache();
+ } // resetUserCache
+
+ public static String getSuperRoleID() {
+ return Globals.getAppUtils().getSuperRoleID();
+ } // getSuperRoleID
+
+ public static Vector getAdminRoleIDs() {
+ return Globals.getAppUtils().getAdminRoleIDs();
+ } // getAdminRoleIDs
+
+ // This is changed to check for Admin User as admin user also need super user privilege if explicitly specified in properties file.
+ public static boolean isSuperUser(HttpServletRequest request)throws RaptorException {
+ if(Globals.isAdminRoleEquivalenttoSuperRole()) return isAdminUser(request);
+ else return isUserInRole(request, getSuperRoleID());
+ } // isSuperUser
+
+ /*public static boolean isSuperUser(String userId) throws RaptorException {
+ if(Globals.isAdminRoleEquivalenttoSuperRole()) return isAdminUser(userId);
+ else return isUserInRole(userId, getSuperRoleID());
+ } // isSuperUser
+ */
+
+ public static boolean isAdminUser(HttpServletRequest request) throws RaptorException {
+ if (isSuperUser(request))
+ return true;
+ for (int i = 0; i < getAdminRoleIDs().size(); i++)
+ if (isUserInRole(request, (String) getAdminRoleIDs().get(i)))
+ return true;
+
+ return false;
+ } // isAdminUser
+
+ /*public static boolean isAdminUser(String userId) throws RaptorException {
+ if (isSuperUser(userId))
+ return true;
+
+ for (int i = 0; i < getAdminRoleIDs().size(); i++)
+ if (isUserInRole(userId, (String) getAdminRoleIDs().get(i)))
+ return true;
+
+ return false;
+ } // isAdminUser
+ */
+
+ public static String getTempFolderPath() {
+ String path = Globals.getAppUtils().getTempFolderPath();
+ if (path.endsWith(File.separator) || path.endsWith("/")){
+ return path;
+ } else {
+ path = path + File.separator;
+ return path;
+ }
+ } // getTempFolderPath
+
+ public static String getUploadFolderPath() {
+ String path = Globals.getAppUtils().getUploadFolderPath();
+ if (path.endsWith(File.separator)){
+ return path;
+ } else {
+ path = path + File.separator;
+ return path;
+ }
+ } // getUploadFolderPath
+
+ public static String getTempFolderURL() {
+ return Globals.getAppUtils().getTempFolderURL();
+ } // getTempFolderURL
+
+ public static String getUploadFolderURL() {
+ return Globals.getAppUtils().getUploadFolderURL();
+ } // getUploadFolderURL
+
+ public static String getSMTPServer()throws Exception {
+ return Globals.getAppUtils().getSMTPServer();
+ } // getSMTPServer
+
+ public static String getDefaultEmailSender() throws RaptorException {
+ return Globals.getAppUtils().getDefaultEmailSender();
+ } // getDefaultEmailSender
+
+ public static String getErrorPage() {
+ return getJspContextPath() + Globals.getAppUtils().getErrorPage();
+ } // getErrorPage
+
+ public static String getErrorPageWMenu() {
+ return getJspContextPath() + Globals.getAppUtils().getErrorPageWMenu();
+ } // getErrorPage
+
+ public static String getJspContextPath() {
+ return Globals.getAppUtils().getJspContextPath();
+ } // getJspContextPath
+
+ public static String getImgFolderURL() {
+ return Globals.getAppUtils().getImgFolderURL();
+ } // getImgFolderURL
+
+ public static String getBaseFolderURL() {
+ return Globals.getAppUtils().getBaseFolderURL();
+ } // getBaseFolderURL
+
+ public static String getChartScriptsPath() {
+ return getFolderPathAdj()+getBaseFolderURL();
+ } // getBaseFolderURL
+
+ public static String getChartScriptsPath(String folderAdj1) {
+ return folderAdj1+getBaseFolderURL();
+ } // getBaseFolderURL
+
+ public static String getFolderPathAdj() {
+ return Globals.getAppUtils().getFolderPathAdj();
+ } // getBaseFolderURL
+
+
+ /*
+ * public static String getReportExecuteActionURL() { return
+ * Globals.getAppUtils().getReportExecuteActionURL(); } //
+ * getReportExecuteActionURL
+ *
+ * public static String getDataViewActionURL() { return
+ * Globals.getAppUtils().getDataViewActionURL(); } // getDataViewActionURL
+ *
+ * public static String getDataViewActionParam() { return
+ * Globals.getAppUtils().getDataViewActionParam(); } //
+ * getDataViewActionParam
+ */
+ public static String getDirectAccessURL() {
+ return Globals.getAppUtils().getDirectAccessURL();
+ } // getDirectAccessURL
+
+ public static String getBaseURL() {
+ if (baseURL == null) {
+ baseURL = getBaseActionURL();
+ if (baseURL.indexOf("?") > 0)
+ baseURL = baseURL.substring(0, baseURL.indexOf("?"));
+ } // if
+
+ return baseURL;
+ } // getBaseURL
+
+ public static String getBaseActionURL() {
+ return Globals.getAppUtils().getBaseActionURL();
+ } // getBaseActionURL
+
+ public static String getDrillActionURL() {
+ return Globals.getAppUtils().getDrillActionURL();
+ } // getBaseActionURL
+
+ public static String getRaptorActionURL() {
+ return Globals.getAppUtils().getBaseActionURL() + "raptor&" + AppConstants.RI_ACTION
+ + "=";
+ } // getRaptorActionURL
+
+ public static String getRaptorActionURLNG() {
+ return Globals.getAppUtils().getBaseActionURLNG();
+ } // getRaptorActionURL
+
+ public static String getReportExecuteActionURL() {
+ return getRaptorActionURL() + "report.run.container&" + AppConstants.RI_REPORT_ID + "="; // getBaseActionParam();
+ } // getReportExecuteActionURL
+
+ public static String getReportExecuteActionURLNG() {
+ return getRaptorActionURLNG() + "report_run/"; // getBaseActionParam();
+ } // getReportExecuteActionURL
+
+ public static String getBaseActionParam() {
+ return Globals.getAppUtils().getBaseActionParam();
+ } // getBaseActionParam
+
+ public static Vector getQuickLinksMenuIDs() {
+ return Globals.getAppUtils().getQuickLinksMenuIDs();
+ } // getQuickLinksMenuIDs
+
+ public static String getMenuLabel(String menuId) {
+ return Globals.getAppUtils().getMenuLabel(menuId);
+ } // getMenuLabel
+
+ public static String getReportDbColsMaskSQL() {
+ return Globals.getAppUtils().getReportDbColsMaskSQL();
+ } // getReportDbColsMaskSQL
+
+ public static String getReportDbLookupsSQL() {
+ return Globals.getAppUtils().getReportDbLookupsSQL();
+ } // getReportDbLookupsSQL
+
+ public static void processErrorNotification(HttpServletRequest request, RaptorException e) {
+ Globals.getAppUtils().processErrorNotification(request, e);
+ } // processErrorNotification
+
+ public static String getExcelTemplatePath() {
+ String path = Globals.getAppUtils().getExcelTemplatePath();
+ if (path.endsWith(File.separator)){
+ return path;
+ } else {
+ path = path + File.separator;
+ return path;
+ }
+ } // getTempFolderPath
+
+ public static String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ public static boolean isNotEmpty(String s) {
+ return nvl(s).length()>0;
+ }
+ public static String nvls(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+} // AppUtils
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system;
+
+import java.sql.Connection;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+
+public class ConnectionUtils {
+
+ public static DataSet getDataSet(String sql, String remoteDbPrefix)
+ throws RaptorException {
+ return getDataSet(sql, remoteDbPrefix, false);
+ }
+
+ public static Connection getConnection(String remoteDbPrefix) throws ReportSQLException {
+ if (!isNull(remoteDbPrefix) && (!remoteDbPrefix.equals(AppConstants.DB_LOCAL)) && !Globals.getSystemType().equals(Globals.ST_GENERIC) ) {
+ return RemDbUtils.getConnection(remoteDbPrefix);
+ } else {
+ return DbUtils.getConnection();
+ }
+ }
+
+ public static DataSet getDataSet(String sql, String remoteDbPrefix,
+ boolean pagesize) throws ReportSQLException {
+ DataSet ds = null;
+ if (!isNull(remoteDbPrefix) && (!remoteDbPrefix.equals(AppConstants.DB_LOCAL)) && !Globals.getSystemType().equals(Globals.ST_GENERIC) ) {
+ if (pagesize == false)
+ ds = RemDbUtils.executeQuery(sql,remoteDbPrefix);
+ else
+ ds = RemDbUtils.executeQuery(sql, Globals.getDefaultPageSize() + 1,remoteDbPrefix);
+ } else {
+ if (pagesize == false)
+ ds = DbUtils.executeQuery(sql);
+ else
+ ds = DbUtils.executeQuery(sql, Globals.getDefaultPageSize() + 1);
+ }
+ return ds;
+ }
+
+ public static boolean isNull(String a) {
+ if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null"))
+ return true;
+ else
+ return false;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system;
+
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Types;
+
+import javax.sql.DataSource;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.web.support.AppUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+
+public class DbUtils {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DbUtils.class);
+
+ private static DataSource dataSource;
+
+ public DbUtils() {
+ }
+
+ public static Connection getConnection() throws ReportSQLException {
+ try {
+ return AppUtils.getDatasource().getConnection();
+ } catch(SQLException ex) {
+ ex.printStackTrace();
+ }
+ return null;
+ } // getConnection
+
+ public static void clearConnection(Connection con) throws ReportSQLException {
+ try {
+ if ((con != null) && !con.isClosed())
+ Globals.getDbUtils().clearConnection(con);
+ } catch (SQLException ex) {
+ throw new ReportSQLException(ex.getMessage(), ex.getCause());
+ } catch (Exception ex2 ) {
+ throw new ReportSQLException (ex2.getMessage(), ex2.getCause());
+ }
+ } // clearConnection
+
+ public static Connection startTransaction() throws ReportSQLException {
+ Connection con = null;
+ try {
+ con = getConnection();
+ con.setAutoCommit(false);
+ } catch (SQLException ex) {
+ throw new ReportSQLException (ex.getMessage(), ex.getCause());
+ } catch (Exception ex2 ) {
+ throw new ReportSQLException (ex2.getMessage(), ex2.getCause());
+ }
+ return con;
+ } // startTransaction
+
+ public static void commitTransaction(Connection con) throws ReportSQLException {
+ try {
+ con.commit();
+ } catch (SQLException ex) {
+ throw new ReportSQLException (ex.getMessage(), ex.getCause());
+ } catch (Exception ex2 ) {
+ throw new ReportSQLException (ex2.getMessage(), ex2.getCause());
+ }
+ } // commitTransaction
+
+ public static void rollbackTransaction(Connection con) throws ReportSQLException {
+ try {
+ con.rollback();
+ clearConnection(con);
+ } catch (SQLException ex) {
+ throw new ReportSQLException (ex.getMessage(), ex.getCause());
+ } catch (Exception ex2 ) {
+ throw new ReportSQLException (ex2.getMessage(), ex2.getCause());
+ }
+ } // rollbackTransaction
+
+ public static String executeCall(Connection con, String sql, boolean expectResult)
+ throws ReportSQLException {
+ String result = null;
+
+ try {
+ if(con.isClosed()) con = getConnection();
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[SQL CALL FROM RAPTOR] [SQL Call] " + sql));
+ CallableStatement stmt = con.prepareCall(sql);
+ if (expectResult)
+ stmt.registerOutParameter(1, Types.CHAR);
+ stmt.executeUpdate();
+ if (expectResult)
+ result = stmt.getString(1);
+ stmt.close();
+ con.commit();
+ } catch (SQLException e) {
+ throw new ReportSQLException(e.getMessage(), sql);
+ } finally {
+ clearConnection(con);
+ }
+
+ return result;
+ } // executeCall
+
+ public static String executeCall(String sql, boolean expectResult)
+ throws RaptorException {
+ Connection con = null;
+ con = getConnection();
+ String result = executeCall(con, sql, expectResult);
+ //con.commit();
+ return result;
+ } // executeCall
+
+ public static int executeUpdate(Connection con, String sql) throws ReportSQLException {
+ int rcode = -1;
+ try {
+ Statement stmt = con.createStatement();
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[SQL CALL FROM RAPTOR] [SQL Update] " + sql));
+ rcode = stmt.executeUpdate(sql);
+ stmt.close();
+ //con.commit();
+ } catch (SQLException e) {
+ //e.printStackTrace();
+ throw new ReportSQLException(e.getMessage(), sql);
+ }
+ return rcode;
+ } // executeUpdate
+
+ public static int executeUpdate(String sql) throws ReportSQLException {
+ Connection con = null;
+ try {
+ con = getConnection();
+ int rcode = executeUpdate(con, sql);
+ if(Globals.getDBType().equals("oracle"))
+ con.commit();
+
+ return rcode;
+ } catch (SQLException e) {
+ throw new ReportSQLException(e.getMessage(), sql);
+ } finally {
+ clearConnection(con);
+ }
+ } // executeUpdate
+
+ public static DataSet executeQuery(Connection con, String sql) throws ReportSQLException {
+ return executeQuery(con, sql, Integer.MAX_VALUE);
+ } // executeQuery
+
+ public static DataSet executeQuery(Connection con, String sql, int maxRowLimit)
+ throws ReportSQLException {
+ try {
+ if(con.isClosed()) con = getConnection();
+ //con.
+ Statement stmt = con.createStatement();
+
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[SQL CALL FROM RAPTOR] [SQL] " + sql));
+ ResultSet rs = stmt.executeQuery(sql);
+ DataSet ds = new DataSet(rs, maxRowLimit);
+
+ if(rs!=null)
+ rs.close();
+ if(stmt!=null)
+ stmt.close();
+
+ return ds;
+ } catch (SQLException e) {
+ throw new ReportSQLException(e.getMessage(), sql);
+ }
+ } // executeQuery
+
+ public static DataSet executeQuery(String sql) throws ReportSQLException {
+ return executeQuery(sql, Integer.MAX_VALUE);
+ } // executeQuery
+
+ public static DataSet executeQuery(String sql, int maxRowLimit) throws ReportSQLException {
+ Connection con = null;
+ try {
+ con = getConnection();
+ return executeQuery(con, sql, maxRowLimit);
+ }catch (ReportSQLException ex) {
+ logger.error(EELFLoggerDelegate.debugLogger, ("Error " + sql));
+ throw new ReportSQLException(ex.getMessage(), ex);
+ }catch(Exception ex1) {
+ throw new ReportSQLException(ex1.getMessage(), ex1.getCause());
+ } finally {
+ clearConnection(con);
+ }
+ } // executeQuery
+
+ //For ZK Support
+
+ public static int executeQuery(ReportRuntime rr, int dateOption) {
+ Connection con = null;
+ int rowCount = 0;
+ try {
+ con = ConnectionUtils.getConnection(rr.getDBInfo());
+ String wholeSql = rr.getWholeSQL();
+
+ DataColumnType dc = rr.getColumnWhichNeedEnhancedPagination();
+ String date_ColId = dc.getColId();
+ String dataFormat = dc.getColFormat();
+ if(dataFormat!=null && dataFormat.length()>0)
+ date_ColId = "to_date("+date_ColId+", '"+ dataFormat +"')";
+ String sql = "";
+ if(dateOption == 1)
+ sql = "select count(distinct to_char("+date_ColId+", 'YYYY/MM')) from ("+wholeSql+")";
+ else if (dateOption == 3)
+ sql = "select count(distinct to_char("+date_ColId+", 'YYYY/MM/DD')) from ("+wholeSql+")";
+ else if (dateOption == 2)
+ sql = "select count(distinct to_char("+date_ColId+", 'YYYY')) from ("+wholeSql+")";
+ DataSet ds = executeQuery(con, sql.toString());
+ rowCount = ds.getInt(0,0);
+ } catch (ReportSQLException ex) {
+ ex.printStackTrace();
+ }catch(Exception ex1) {
+ ex1.printStackTrace();
+ } finally {
+ try {
+ clearConnection(con);
+ } catch (ReportSQLException ex2) {
+ ex2.printStackTrace();
+ }
+ }
+ return rowCount;
+ }
+
+ public String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ public static String nvls(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ public static String nvl(String s, String sDefault) {
+ return nvls(s).equals("") ? sDefault : s;
+ }
+
+ public static DataSource getDataSource() {
+ return dataSource;
+ }
+
+ @Autowired
+ public void setDataSource(DataSource dataSource) {
+ dataSource = dataSource;
+ }
+
+} // DbUtils
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.concurrent.Callable;
+
+public class ExecuteQuery implements Callable<ResultSet>{
+
+ private Statement stmt;
+ private String sql = "";
+ private int maxRowLimit;
+ private ResultSet resultSet;
+
+ public ResultSet getResultSet() {
+ return resultSet;
+ }
+ public void setResultSet(ResultSet resultSet) {
+ this.resultSet = resultSet;
+ }
+
+ public ExecuteQuery(Statement stmt, String sql, int maxRowLimit) {
+ super();
+ this.stmt = stmt;
+ this.sql = sql;
+ this.maxRowLimit = maxRowLimit;
+ }
+
+ public ResultSet call() throws SQLException {
+ try {
+ System.out.println("Query Started" + new java.util.Date());
+ resultSet = stmt.executeQuery(sql);
+ System.out.println("Query End" + new java.util.Date());
+ } catch (SQLException ex) {
+ System.out.println("Query Exception" + new java.util.Date());
+ ex.printStackTrace();
+ throw ex;
+ }
+ return resultSet;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+/* ===========================================================================================
+ * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
+ * Raptor : This tool is used to generate different kinds of reports with lot of utilities
+ * ===========================================================================================
+ *
+ * -------------------------------------------------------------------------------------------
+ * Globals.java - This class is used to read properties file and call the common methods
+ * existing among all the frameworks.
+
+ * -------------------------------------------------------------------------------------------
+ *
+ *
+ * Changes
+ * -------
+ * 31-Jul-2009 : Version 8.4 (Sundar); <UL><LI> getRequestparametersMap method iterates form field collections. </LI>
+ * </UL>
+ * 27-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Added property "admin_role_equiv_to_super_role" to specify Admin User equivalent to Super User.</LI>
+ * </UL>
+ * 14-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Added property to showing/hiding params displayed in dashboard reports.</LI>
+ * </UL>
+ *
+ */
+package org.onap.portalsdk.analytics.system;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.analytics.config.ConfigLoader;
+import org.onap.portalsdk.analytics.controller.ActionMapping;
+import org.onap.portalsdk.analytics.model.runtime.FormField;
+import org.onap.portalsdk.analytics.model.runtime.ReportFormFields;
+import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.ExcelColorDef;
+import org.onap.portalsdk.analytics.util.Scheduler;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class Globals extends org.onap.portalsdk.analytics.RaptorObject {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Globals.class);
+
+ private static boolean systemInitialized = false;
+
+ private static ActionMapping raptorActionMapping = null;
+
+ private static Scheduler scheduler = null;
+
+ // System type constants
+ public final static String ST_FUSION = "fusion";
+
+ public final static String ST_GENERIC = "generic";
+
+ public final static String ST_PRISMS = "prisms";
+
+ private static String systemType = ST_PRISMS; // default
+
+ private static IAppUtils appUtils = null;
+
+ private static IDbUtils dbUtils = null;
+
+ private static RDbUtils rdbUtils = null;
+
+ private static int debugLevel = 5;
+
+ private static int downloadLimit = 65000; // max number rows for download
+ // csv file
+
+ private static int defaultPageSize = 50;
+
+ private static int formFieldsListSize = 50;
+
+ private static int schedulerInterval = 0;
+
+ private static String systemName = "MSA Databank";
+
+ private static String baseTitle = "ANALYSIS";
+
+ private static String sheet_name = "Raptor Reports";
+
+ private static boolean allowSQLBasedReports = true; // whether to allow
+ // SQL-based report
+ // definition (security
+ // risk); super users
+ // are always allowed to
+ // create SQL-based
+ // reports
+
+ private static boolean showDisclaimer = true; // whether to include
+ // disclaimer page at the
+ // bottom of each screen
+
+ private static boolean displayFormBeforeRun = true; // whether to display
+ // the form page as a
+ // separate page before
+ // running the report
+
+ private static boolean includeFormWithData = true; // whether to include
+ // the form page on the
+ // report data page
+
+ private static boolean cacheChartData = true; // whether to cache chart
+ // data in the session =>
+ // faster re-display if the
+ // data volume does not get
+ // too large
+
+ private static boolean cacheCurPageData = true; // whether to cache report
+ // data for the currently
+ // displayed page in the
+ // session => faster
+ // re-display if the data
+ // volume does not get too
+ // large
+
+ private static boolean deleteOnlyByOwner = true; // whether to permit
+ // report deletion only
+ // by report owner or by
+ // everyone with "write"
+ // access
+
+ private static boolean enableReportLog = true; // whether to log each
+ // report execution and
+ // update time and user ID
+
+ private static boolean cacheUserRoles = true; // whether to cache user
+ // roles info in memory
+ // (saves many DB reads, but
+ // does not account for
+ // roles assigned after the
+ // cache was loaded)
+
+ private static boolean monthFormatUseLastDay = true; // whether to
+ // convert month
+ // formats (e.g.
+ // MM/YYYY) to the
+ // last day of the
+ // month (true) or
+ // first day (false)
+ // - like 12/2003 is
+ // converted to
+ // either 12/31/2003
+ // or 12/01/2003
+
+ private static boolean printTitleInDownload = false; // whether to print
+ // the report title
+ // in the download
+ // files
+
+ private static boolean showDescrAtRuntime = false; // whether to show
+ // report description
+ // when the report is
+ // run and in the quick
+ // links
+
+ // private static boolean skipChartLabelsToFit = false; // whether to skip
+ // labels on the Line chart axis when they overlap
+ private static boolean showNonstandardCharts = false; // whether to show
+ // chart types that
+ // are purpose
+ // and/or data
+ // specific
+
+ private static boolean allowRuntimeChartSel = true; // whether to allow the
+ // user to change the
+ // chart type at runtime
+
+ private static boolean displayChartTitle = false; // whether to display
+ // the report title as
+ // chart title as well
+
+ private static boolean mergeCrosstabRowHeadings = true; // whether to
+ // merge/blank
+ // multi-level row
+ // headings in
+ // cross-tab report
+
+ private static boolean displayChartByDefault = true; // whether to
+ // display chart
+ // when displaying
+ // the report at
+ // first or just a
+ // "Show Chart"
+ // button
+
+ private static boolean printParamsInDownload = false; // whether to print
+ // the form field
+ // values in the
+ // download files
+
+ // private static boolean chartLinesAlwaysSolid = true; // whether
+ // multi-lines chart uses solid line for all series or dashed/dotted/etc for
+ // each
+ // private static boolean chartLinesAlwaysSmooth = true; // whether line
+ // charts display smooth lines or with marked points on them for each value
+ private static int maxDecimalsOnTotals = 2; // Maximum number of decimals
+ // displayed in totals; decimal
+ // digits beyond that number
+ // will be truncated; if
+ // negative => display all
+ // decimal digits
+
+ private static int defaultChartWidth = 700;
+
+ private static int defaultChartHeight = 420;
+
+ private static int skipChartLabelsLimit = 30;
+
+ private static boolean canCopyOnReadOnly = true; // whether to users with
+ // read-only rights for
+ // a report can copy it
+
+ // Currently not loaded from a property file
+ private static boolean restrictTablesByRole = true; // whether to restrict
+ // DB tables
+ // accessibility by user
+ // role; defaults to
+ // false if table
+ // CR_TABLE_ROLE is
+ // empty, otherwise true
+
+ private static String javaTimeFormat = "MM/dd/yyyy h:m:s a";
+
+ private static String oracleTimeFormat = "%m/%d/%Y %h:%i:%s %p"; // must
+ // correspond
+ // to
+ // the
+ // java
+ // format
+ // modifier
+
+ private static String raptorVersion = "10.5.1";
+
+ private static int flatFileLowerLimit = 0;
+
+ private static int flatFileUpperLimit = 0;
+
+ private static String shellScriptDir = "";
+
+ private static String queryFolder = "";
+
+ private static String requestParams = "";
+
+ private static String sessionParams = "";
+
+ private static boolean displayAllUsers = true;
+
+ private static boolean user_col_def = true;
+
+ private static boolean printFooterInDownload = true;
+
+ private static String footerFirstLine = "";
+
+ private static String footerSecondLine = "";
+
+ private static boolean reportsInPoPUpWindow = false;
+
+ private static boolean poPUpInNewWindow = false;
+
+ private static boolean passRequestParamInDrilldown = false;
+
+ private static Properties raptorPdfProperties;
+
+ private static Properties raptorProperties;
+
+ private static Properties sqlProperty;
+
+ private static boolean showPDFDownloadIcon = false;
+
+
+
+ private Globals() {
+ }
+
+ public static synchronized void initializeSystem(ServletContext servletContext) {
+ if (systemInitialized)
+ return;
+ AppConstants.initializeAppConstants();
+ ExcelColorDef.initializeExcelColorDef();
+
+ //DB Agnostic Addition
+ try{
+ Properties sqlProperty = ConfigLoader.getProperties(servletContext, ConfigLoader.SQL_PROPERTIES);
+ Globals.sqlProperty = sqlProperty;
+ }
+
+ catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ try {
+ Properties raptorProperties = ConfigLoader.getProperties(servletContext,
+ ConfigLoader.RAPTOR_PROPERTIES);
+ initializeRaptorProperties(raptorProperties);
+
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] Globals: Unable to load properties ["
+ + ConfigLoader.RAPTOR_PROPERTIES + "]. Exception: " + e.getMessage()));
+ // throw new RuntimeException(e.getMessage());
+ }
+
+ systemInitialized = true;
+
+ try {
+ appUtils = (IAppUtils) Class.forName(
+ "org.onap.portalsdk.analytics.system." + systemType.toLowerCase() + ".AppUtils")
+ .newInstance();
+ appUtils.initializeAppUtils(servletContext);
+
+ dbUtils = (IDbUtils) Class.forName(
+ "org.onap.portalsdk.analytics.system." + systemType.toLowerCase() + ".DbUtils")
+ .newInstance();
+ dbUtils.initializeDbUtils(servletContext);
+
+ if(!Globals.getSystemType().equals(Globals.ST_GENERIC)) {
+ rdbUtils = (RDbUtils) Class.forName(
+ "org.onap.portalsdk.analytics.system." + systemType.toLowerCase() + ".RemoteDbUtils")
+ .newInstance();
+ rdbUtils.initializeDbUtils(servletContext);
+ }
+ } catch (Exception e) {
+ String eMsg = "[SYSTEM ERROR] Globals: Unable to instantiate system classes. Exception: "
+ + e.getMessage();
+ logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] " + eMsg));
+ systemInitialized = false;
+ throw new RuntimeException(eMsg);
+ }
+
+ try {
+ raptorActionMapping = ConfigLoader.loadRaptorActionMapping(servletContext);
+ } catch (Exception e) {
+ String eMsg = "[SYSTEM ERROR] Globals: Unable to load Raptor action mapping. Exception: "
+ + e.getMessage();
+ logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] " + eMsg));
+ systemInitialized = false;
+ throw new RuntimeException(eMsg);
+ } // catch
+
+ /*try {
+ //DataSet ds = DbUtils
+ // .executeQuery("SELECT 1 FROM dual WHERE EXISTS (SELECT 1 FROM cr_table_role)");
+
+ String p_sql = Globals.getInitializeRoles();
+ DataSet ds = DbUtils.executeQuery(p_sql);
+
+ restrictTablesByRole = (ds.getRowCount() > 0);
+ } catch (Exception e) {
+ String eMsg = "[SYSTEM ERROR] Globals: Unable to load Raptor version. Exception: "
+ + e.getMessage();
+ debugLogger.error("[EXCEPTION ENCOUNTERED IN RAPTOR] " + eMsg, e);
+ } // catch
+ */
+ /*try {
+ //DataSet ds = DbUtils.executeQuery("SELECT cr_raptor.get_version FROM dual");
+
+ //String n_sql = Globals.getInitializeVersion();
+ //DataSet ds = DbUtils.executeQuery(n_sql);
+ //raptorVersion = Globals.get
+ // if(ds.getRowCount()>0)
+ // raptorVersion = " v"+ds.getString(0, 0);
+ } catch (Exception e) {
+ String eMsg = "[SYSTEM ERROR] Globals: Unable to load Raptor version. Exception: "
+ + e.getMessage();
+ debugLogger.error("[EXCEPTION ENCOUNTERED IN RAPTOR] " + eMsg, e);
+ } // catch*/
+
+
+ //initiate pdf global config
+ try {
+ raptorPdfProperties = ConfigLoader.getProperties(servletContext, ConfigLoader.RAPTOR_PDF_PROPERTIES);
+ }
+ catch (Exception e) {
+ logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] Globals: Unable to load properties ["
+ + ConfigLoader.RAPTOR_PDF_PROPERTIES + "]. Exception: " + e.getMessage()));
+
+ }
+
+ scheduler = new Scheduler(schedulerInterval);
+
+ } // initializeSystem
+
+ public static void initializeRaptorProperties(Properties raptorProperties) {
+ Globals.raptorProperties = raptorProperties;
+ systemType = raptorProperties.getProperty("system");
+
+ try {
+ debugLevel = Integer.parseInt(nvls(raptorProperties
+ .getProperty("debug_level")).trim());
+ } catch (NumberFormatException nfe) {
+ }
+
+ try {
+ downloadLimit = Integer.parseInt(nvls(raptorProperties
+ .getProperty("download_limit")).trim());
+ } catch (NumberFormatException nfe) {
+ }
+
+ try {
+ defaultPageSize = Integer.parseInt(nvls(raptorProperties
+ .getProperty("default_page_size")).trim());
+ } catch (NumberFormatException nfe) {
+ }
+
+ try {
+ formFieldsListSize = Integer.parseInt(nvls(raptorProperties
+ .getProperty("form_fields_list_size")).trim());
+ } catch (NumberFormatException nfe) {
+ }
+
+ try {
+ schedulerInterval = Integer.parseInt(nvls(raptorProperties
+ .getProperty("scheduler_interval")).trim());
+ } catch (NumberFormatException nfe) {
+ System.out.println("NUMBERFORMATEXCEPTION Schedular " + raptorProperties
+ .getProperty("scheduler_interval"));
+ schedulerInterval = 0;
+ }
+
+ try {
+ maxDecimalsOnTotals = Integer.parseInt(nvls(raptorProperties
+ .getProperty("max_decimals_on_totals")).trim());
+ } catch (NumberFormatException nfe) {
+ }
+
+ try {
+ defaultChartWidth = Integer.parseInt(nvls(raptorProperties
+ .getProperty("default_chart_width")).trim());
+ } catch (NumberFormatException nfe) {
+ }
+
+ try {
+ defaultChartHeight = Integer.parseInt(nvls(raptorProperties
+ .getProperty("default_chart_height")).trim());
+ } catch (NumberFormatException nfe) {
+ }
+
+ try {
+ skipChartLabelsLimit = Integer.parseInt(nvls(raptorProperties
+ .getProperty("skip_chart_labels_limit")).trim());
+ } catch (NumberFormatException nfe) {
+ }
+
+ systemName = nvls(raptorProperties.getProperty("system_name"), "MSA Databank");
+ baseTitle = nvls(raptorProperties.getProperty("base_title"), "ANALYSIS");
+
+ allowSQLBasedReports = nvls(
+ raptorProperties.getProperty("allow_sql_based_reports"), "yes")
+ .toUpperCase().startsWith("Y");
+ showDisclaimer = nvls(raptorProperties.getProperty("show_disclaimer"), "yes")
+ .toUpperCase().startsWith("Y");
+ displayFormBeforeRun = nvls(
+ raptorProperties.getProperty("display_form_before_run"), "yes")
+ .toUpperCase().startsWith("Y");
+ includeFormWithData = nvls(raptorProperties.getProperty("include_form_with_data"),
+ "yes").toUpperCase().startsWith("Y");
+ cacheChartData = nvls(raptorProperties.getProperty("cache_chart_data"), "yes")
+ .toUpperCase().startsWith("Y");
+ cacheCurPageData = nvls(raptorProperties.getProperty("cache_cur_page_data"), "yes")
+ .toUpperCase().startsWith("Y");
+ deleteOnlyByOwner = nvls(raptorProperties.getProperty("delete_only_by_owner"),
+ "yes").toUpperCase().startsWith("Y");
+ enableReportLog = nvls(raptorProperties.getProperty("enable_report_log"), "yes")
+ .toUpperCase().startsWith("Y");
+ cacheUserRoles = nvls(raptorProperties.getProperty("cache_user_roles"), "yes")
+ .toUpperCase().startsWith("Y");
+ monthFormatUseLastDay = nvls(
+ raptorProperties.getProperty("month_format_use_last_day"), "yes")
+ .toUpperCase().startsWith("Y");
+ printTitleInDownload = nvls(
+ raptorProperties.getProperty("print_title_in_download"), "no")
+ .toUpperCase().startsWith("Y");
+ showDescrAtRuntime = nvls(raptorProperties.getProperty("show_descr_at_runtime"),
+ "no").toUpperCase().startsWith("Y");
+ // skipChartLabelsToFit =
+ // nvls(raptorProperties.getProperty("skip_chart_labels_to_fit"),
+ // "no" ).toUpperCase().startsWith("Y");
+ showNonstandardCharts = nvls(
+ raptorProperties.getProperty("show_nonstandard_charts"), "no")
+ .toUpperCase().startsWith("Y");
+ allowRuntimeChartSel = nvls(
+ raptorProperties.getProperty("allow_runtime_chart_sel"), "yes")
+ .toUpperCase().startsWith("Y");
+ displayChartTitle = nvls(raptorProperties.getProperty("display_chart_title"), "no")
+ .toUpperCase().startsWith("Y");
+ mergeCrosstabRowHeadings = nvls(
+ raptorProperties.getProperty("merge_crosstab_row_headings"), "yes")
+ .toUpperCase().startsWith("Y");
+ displayChartByDefault = nvls(
+ raptorProperties.getProperty("display_chart_by_default"), "yes")
+ .toUpperCase().startsWith("Y");
+ //System.out.println("Params Globals " + raptorProperties.getProperty("print_params_in_download"));
+
+ printParamsInDownload = nvls(
+ raptorProperties.getProperty("print_params_in_download"), "no")
+ .toUpperCase().startsWith("Y");
+ //System.out.println("printParamsInDownload " + printParamsInDownload);
+
+ canCopyOnReadOnly = nvls(raptorProperties.getProperty("can_copy_on_read_only"),
+ "yes").toUpperCase().startsWith("Y");
+ // chartLinesAlwaysSolid =
+ // nvls(raptorProperties.getProperty("chart_lines_always_solid"),
+ // "yes").toUpperCase().startsWith("Y");
+ // chartLinesAlwaysSmooth =
+ // nvls(raptorProperties.getProperty("chart_lines_always_smooth"),
+ // "yes").toUpperCase().startsWith("Y");
+ displayAllUsers = nvls(
+ raptorProperties.getProperty("display_all_users"), "yes")
+ .toUpperCase().startsWith("Y");
+ requestParams = nvls(
+ raptorProperties.getProperty("request_get_params"), "");
+ sessionParams = nvls(
+ raptorProperties.getProperty("session_params"), "");
+ user_col_def = nvls(
+ raptorProperties.getProperty("user_col_def"), "no")
+ .toUpperCase().startsWith("Y");
+ sheet_name = nvls(raptorProperties.getProperty("sheet_name"), "Raptor Reports");
+ try {
+ flatFileLowerLimit = Integer.parseInt(raptorProperties
+ .getProperty("flat_file_lower_limit"));
+ } catch (NumberFormatException nfe) {
+ }
+ try {
+ flatFileUpperLimit = Integer.parseInt(raptorProperties
+ .getProperty("flat_file_upper_limit"));
+ } catch (NumberFormatException nfe) {
+ }
+ shellScriptDir = nvls(raptorProperties.getProperty("shell_script_dir"), "");
+ //queryFolder = nvls(raptorProperties.getProperty("download_query_folder"), AppUtils.getTempFolderPath()+"../raptor/dwnld/query/");
+ queryFolder = nvls(raptorProperties.getProperty("download_query_folder"),"../raptor/dwnld/query/");
+
+
+ printFooterInDownload = nvls(
+ raptorProperties.getProperty("print_footer_in_download"), "no")
+ .toUpperCase().startsWith("Y");
+ footerFirstLine = nvls(raptorProperties.getProperty("footer_first_line"), "AT&T Proprietary");
+ footerSecondLine = nvls(raptorProperties.getProperty("footer_second_line"), "Use Pursuant to Company Instructions");
+ reportsInPoPUpWindow = nvls(
+ raptorProperties.getProperty("report_in_popup_window"), "no")
+ .toUpperCase().startsWith("Y");
+ poPUpInNewWindow = nvls(
+ raptorProperties.getProperty("popup_in_new_window"), "no")
+ .toUpperCase().startsWith("Y") && reportsInPoPUpWindow;
+
+ passRequestParamInDrilldown = nvls(
+ raptorProperties.getProperty("pass_request_param_in_drilldown"), "yes")
+ .toUpperCase().startsWith("Y");
+ showPDFDownloadIcon = nvls(
+ raptorProperties.getProperty("show_pdf_download"), "no")
+ .toUpperCase().startsWith("Y");
+ }
+
+ /** *********************************************************************** */
+
+ public static ActionMapping getRaptorActionMapping() {
+ if (!systemInitialized)
+ throw new RuntimeException("[SYSTEM ERROR] Globals not initialized");
+
+ return raptorActionMapping;
+ } // getRaptorActionMapping
+
+ public static String getSystemType() {
+ if (!systemInitialized)
+ throw new RuntimeException("[SYSTEM ERROR] Globals not initialized");
+
+ return systemType;
+ } // getSystemType
+
+ public static IAppUtils getAppUtils() {
+ if (!systemInitialized)
+ throw new RuntimeException("[SYSTEM ERROR] Globals not initialized");
+
+ return appUtils;
+ } // getAppUtils
+
+ public static IDbUtils getDbUtils() {
+ if (!systemInitialized)
+ throw new RuntimeException("[SYSTEM ERROR] Globals not initialized");
+
+ return dbUtils;
+ } // getDbUtils
+
+ public static RDbUtils getRDbUtils() {
+ if (!systemInitialized)
+ throw new RuntimeException("[SYSTEM ERROR] Globals not initialized");
+ return rdbUtils;
+ } // getDbUtils
+
+ /** *********************************************************************** */
+
+ public static int getDebugLevel() {
+ return debugLevel;
+ }
+
+ public static int getDownloadLimit() {
+ return downloadLimit;
+ }
+
+ public static int getCSVDownloadLimit() {
+ return Integer.parseInt(nvls(raptorProperties.getProperty("csv_download_limit"), new Integer(getDownloadLimit()).toString()).trim());
+ }
+
+ public static String getDownloadLimitAsText() {
+ return java.text.NumberFormat.getNumberInstance(java.util.Locale.US).format(
+ downloadLimit);
+ }
+
+ public static int getDefaultPageSize() {
+ return defaultPageSize;
+ }
+
+ public static int getFormFieldsListSize() {
+ return formFieldsListSize;
+ }
+
+ public static int getSchedulerInterval() {
+ return schedulerInterval;
+ }
+
+ public static String getBaseTitle() {
+ return baseTitle;
+ }
+
+ public static String getSystemName() {
+ return systemName;
+ }
+
+ public static boolean getAllowSQLBasedReports() {
+ return allowSQLBasedReports;
+ }
+
+ public static boolean getShowDisclaimer() {
+ return showDisclaimer;
+ }
+
+ public static boolean getDisplayFormBeforeRun() {
+ return displayFormBeforeRun;
+ }
+
+ public static boolean getIncludeFormWithData() {
+ return includeFormWithData;
+ }
+
+ public static boolean getCacheChartData() {
+ return cacheChartData;
+ }
+
+ public static boolean getCacheCurPageData() {
+ return cacheCurPageData;
+ }
+
+ public static boolean getDeleteOnlyByOwner() {
+ return deleteOnlyByOwner;
+ }
+
+ public static boolean getEnableReportLog() {
+ return enableReportLog;
+ }
+
+ public static boolean getCacheUserRoles() {
+ return cacheUserRoles;
+ }
+
+ public static boolean getMonthFormatUseLastDay() {
+ return monthFormatUseLastDay;
+ }
+
+ public static boolean getPrintTitleInDownload() {
+ return printTitleInDownload;
+ }
+
+ public static boolean getShowDescrAtRuntime() {
+ return showDescrAtRuntime;
+ }
+
+ // public static boolean getSkipChartLabelsToFit() { return
+ // skipChartLabelsToFit; }
+ public static boolean getShowNonstandardCharts() {
+ return showNonstandardCharts;
+ }
+
+ public static boolean getAllowRuntimeChartSel() {
+ return allowRuntimeChartSel;
+ }
+
+ public static boolean getDisplayChartTitle() {
+ return displayChartTitle;
+ }
+
+ public static boolean getMergeCrosstabRowHeadings() {
+ return mergeCrosstabRowHeadings;
+ }
+
+ public static boolean getDisplayChartByDefault() {
+ return displayChartByDefault;
+ }
+
+ public static boolean getPrintParamsInDownload() {
+ return printParamsInDownload;
+ }
+
+ public static boolean getCanCopyOnReadOnly() {
+ return canCopyOnReadOnly;
+ }
+
+ // public static boolean getChartLinesAlwaysSolid() { return
+ // chartLinesAlwaysSolid; }
+ // public static boolean getChartLinesAlwaysSmooth() { return
+ // chartLinesAlwaysSmooth; }
+ public static int getMaxDecimalsOnTotals() {
+ return maxDecimalsOnTotals;
+ }
+
+ public static int getDefaultChartWidth() {
+ return defaultChartWidth;
+ }
+
+ public static int getDefaultChartHeight() {
+ return defaultChartHeight;
+ }
+
+ public static int getSkipChartLabelsLimit() {
+ return skipChartLabelsLimit;
+ }
+
+ public static boolean getRestrictTablesByRole() {
+ return restrictTablesByRole;
+ }
+
+ public static String getJavaTimeFormat() {
+ return javaTimeFormat;
+ }
+
+/* public static String getOracleTimeFormat() {
+ return oracleTimeFormat;
+ }
+*/
+
+ public static String getRaptorVersion() {
+ return raptorVersion;
+ }
+
+ public static boolean getDisplayAllUsers() {
+ return displayAllUsers;
+ }
+
+ public static boolean getUserColDef() {
+ return user_col_def;
+ }
+
+ public static String getSheetName() {
+ return sheet_name;
+ }
+
+ public static int getFlatFileLowerLimit() {
+ return flatFileLowerLimit;
+ }
+
+ public static int getFlatFileUpperLimit() {
+ return flatFileUpperLimit;
+ }
+
+
+ public static String getShellScriptDir() {
+ return shellScriptDir;
+ }
+
+ public static String getQueryFolder() {
+ return AppUtils.getTempFolderPath()+queryFolder;
+ }
+
+ public static String getRequestParams() {
+ return requestParams;
+ }
+
+ public static String getSessionParams() {
+ return sessionParams;
+ }
+
+ public static boolean getPrintFooterInDownload() {
+ return printFooterInDownload;
+ }
+
+ public static String getFooterFirstLine() {
+ return footerFirstLine;
+ }
+
+ public static String getFooterSecondLine() {
+ return footerSecondLine;
+ }
+
+ public static boolean getReportsInPoPUpWindow() {
+ return reportsInPoPUpWindow;
+ }
+
+ public static boolean getPoPUpInNewWindow() {
+ return poPUpInNewWindow;
+ }
+
+ public static boolean getPassRequestParamInDrilldown() {
+ return passRequestParamInDrilldown;
+ }
+
+
+ //pdf specific properties
+ public static float getDataFontSize() {
+ float size = 10f;
+
+ try {
+ size = Float.parseFloat(nvls(raptorPdfProperties.getProperty("pdf_data_font_size")).trim());
+ } catch (Exception ex) {
+
+ }
+ return size;
+ }
+
+ public static float getDataFontSizeOffset() {
+ float size = 9f;
+
+ try {
+ size = Float.parseFloat(nvls(raptorPdfProperties.getProperty("pdf_data_font_size_offset")).trim());
+ } catch (Exception ex) {
+
+ }
+ return size;
+ }
+
+ public static float getFooterFontSize() {
+ float size = 9f;
+
+ try {
+ size = Float.parseFloat(nvls(raptorPdfProperties.getProperty("pdf_footer_font_size")).trim());
+ } catch (Exception ex) {
+
+ }
+ return size;
+ }
+
+ public static int getPageNumberPosition() {
+ int size = 1;
+
+ try {
+ size = Integer.parseInt(nvls(raptorPdfProperties.getProperty("pdf_page_number_position")).trim());
+ } catch (Exception ex) {
+
+ }
+ return size;
+ }
+
+ public static String getDataFontFamily() {
+
+ return nvls(raptorPdfProperties.getProperty("pdf_data_font_family"),"Arial").trim();
+ }
+
+ public static String getFooterFontFamily() {
+
+ return nvls(raptorPdfProperties.getProperty("pdf_footer_font_family"),"Arial").trim();
+ }
+
+ public static boolean isCoverPageNeeded() {
+
+ return nvls(raptorPdfProperties.getProperty("display_cover_page"),"true").trim().equalsIgnoreCase("true");
+ }
+
+ public static boolean isDataAlternateColor() {
+
+ return nvls(raptorPdfProperties.getProperty("pdf_data_alternate_color"),"true").trim().equalsIgnoreCase("true");
+ }
+
+ public static String getPDFFooter() {
+
+ return nvls(raptorPdfProperties.getProperty("pdf_footer"));
+ }
+
+ public static boolean isCreatedOwnerInfoNeeded() {
+ return nvls(raptorPdfProperties.getProperty("display_create_owner_info"),"true").trim().equalsIgnoreCase("true");
+ }
+
+ // Selected Form field section in the run page
+ public static boolean displayFormFieldInfo() {
+ return nvls(raptorProperties.getProperty("display_formfield_info"),"no").trim().toUpperCase().startsWith("Y");
+ }
+
+ // Customize Form field section in the run page
+ public static boolean customizeFormFieldInfo() {
+ return nvls(raptorProperties.getProperty("customize_formfield_info"),"no").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean displayLoginIdForDownloadedBy() {
+ return nvls(raptorPdfProperties.getProperty("display_loginid_for_downloaded_by"),"false").trim().equalsIgnoreCase("true");
+ }
+
+ public static boolean isDefaultOrientationPortrait() {
+ return nvls(raptorPdfProperties.getProperty("is_default_orientation_portrait"),"true").trim().equalsIgnoreCase("true");
+ }
+
+ public static String getSessionInfoForTheCoverPage() {
+ return nvls(raptorPdfProperties.getProperty("session_info"));
+ }
+
+ public static String getDatePattern() {
+
+ return nvls(raptorPdfProperties.getProperty("pdf_date_pattern"),"MM/dd/yyyy hh:mm:ss a");
+ }
+
+ public static String getTimeZone() {
+
+ return nvls(raptorPdfProperties.getProperty("pdf_date_timezone"),"EST");
+ }
+
+ public static String getWordBeforePageNumber() {
+
+ return nvls(raptorPdfProperties.getProperty("pdf_word_before_page_number"));
+ }
+
+ public static String getWordAfterPageNumber() {
+
+ return nvls(raptorPdfProperties.getProperty("pdf_word_after_page_number"));
+ }
+
+ public static float getPDFFooterFontSize() {
+ float size = 7f;
+
+ try {
+ size = Float.parseFloat(nvls(raptorPdfProperties.getProperty("pdf_footer_font_size")).trim());
+ } catch (Exception ex) {
+
+ }
+ return size;
+ }
+
+ public static String getDataBackgroundAlternateHexCode() {
+
+ return nvls(raptorPdfProperties.getProperty("pdf_data_background_alternate_hex_code"),"#FFFFFF");
+ }
+
+ public static String getDataDefaultBackgroundHexCode() {
+
+ return nvls(raptorPdfProperties.getProperty("pdf_data_default_background_hex_code"),"#FFFFFF");
+ }
+
+ public static String getDataTableHeaderFontColor() {
+
+ return nvls(raptorPdfProperties.getProperty("pdf_data_table_header_font_hex_code"),"#FFFFFF");
+ }
+
+ public static String getDataTableHeaderBackgroundFontColor() {
+
+ return nvls(raptorPdfProperties.getProperty("pdf_data_table_header_background_hex_code"),"#8A9BB3");
+ }
+
+ public static boolean isFolderTreeAllowed() {
+ return nvls(raptorProperties.getProperty("show_folder_tree"),"yes").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean isFolderDefaultMinimized() {
+ return nvls(raptorProperties.getProperty("folder_tree_minimized"),"no").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean isFolderTreeAllowedOnlyForAdminUsers() {
+ return nvls(raptorProperties.getProperty("show_folder_tree_only_to_admin_users"),"yes").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static float getCoverPageFirstColumnSize() {
+ float size = 0.3f;
+
+ try {
+ size = Float.parseFloat(nvls(raptorPdfProperties.getProperty("pdf_coverpage_firstcolumn_size")).trim());
+ } catch (Exception ex) {
+
+ }
+ return size;
+ }
+
+ public static boolean isImageAutoRotate() {
+ return nvls(raptorPdfProperties.getProperty("pdf_image_auto_rotate"),"false").trim().equalsIgnoreCase("true");
+ }
+
+
+ public static boolean isShowPDFDownloadIcon() {
+ return showPDFDownloadIcon;
+ }
+
+
+ public static void setShowPDFDownloadIcon(boolean showPDFDownloadIcon) {
+ Globals.showPDFDownloadIcon = showPDFDownloadIcon;
+ }
+
+ public static int getScheduleLimit() {
+ int limit = 1000;
+ try {
+ limit = Integer.parseInt(nvls(raptorProperties.getProperty("schedule_limit")).trim());
+ } catch (Exception ex) {
+
+ }
+ return limit;
+ }
+
+// public static String getWhereConditionForUserRole() {
+// return nvls(raptorProperties.getProperty("schedule_where_condition"),"").trim();
+// }
+ public static String getCustomizedScheduleQueryForUsers() {
+ return nvls(raptorProperties.getProperty("schedule_custom_query_for_users"),"").trim();
+ }
+
+ public static String getTimeFormat() {
+ return nvls(raptorProperties.getProperty("time_format"),"%m/%d/%Y %h:%i:%s %p").trim();
+ }
+
+ public static String getCustomizedScheduleQueryForRoles() {
+ return nvls(raptorProperties.getProperty("schedule_custom_query_for_roles"),"").trim();
+ }
+
+ public static String getScheduleDatePattern() {
+ return nvls(raptorProperties.getProperty("schedule_date_pattern"),"MM/dd/yyyy hh:mm:ss a");
+ }
+
+ public static String getChartYearlyPattern() {
+ return nvls(raptorProperties.getProperty("chart_yearly_format"),"yyyy");
+ }
+
+ public static String getChartMonthlyPattern() {
+ return nvls(raptorProperties.getProperty("chart_monthly_format"),"MMM-yyyy");
+ }
+
+ public static String getChartDailyPattern() {
+ return nvls(raptorProperties.getProperty("chart_daily_format"),"MM-dd-yyyy");
+ }
+
+ public static String getChartWeeklyPattern() {
+ return nvls(raptorProperties.getProperty("chart_weekly_format"),"MM-dd-yyyy");
+ }
+
+ public static String getChartHourlyPattern() {
+ return nvls(raptorProperties.getProperty("chart_hourly_format"),"HH");
+ }
+
+ public static String getChartMinutePattern() {
+ return nvls(raptorProperties.getProperty("chart_minute_format"),"HH:mm");
+ }
+
+ public static String getChartSecPattern() {
+ return nvls(raptorProperties.getProperty("chart_second_format"),"HH:mm:ss");
+ }
+
+ public static String getChartMilliSecPattern() {
+ return nvls(raptorProperties.getProperty("chart_millisecond_format"),"HH:mm:ss.S");
+ }
+
+ public static String getSessionParamsForScheduling() {
+ return nvls(raptorProperties.getProperty("session_params_for_scheduling"),"");
+ }
+
+ public static String getDisplaySessionParamInPDFEXCEL() {
+ return nvls(raptorProperties.getProperty("display_session_param_pdfexcel"),"");
+ }
+
+ public static String getDisplayScheduleSessionParamInPDFEXCEL() {
+ return nvls(raptorProperties.getProperty("session_params_for_displaying_in_scheduling"),"");
+ }
+
+ public static boolean isScheduleDateParamAutoIncr() {
+ return nvls(raptorProperties.getProperty("session_date_formfield_auto_incr"),"yes").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static int getMaxCellWidthInExcel() {
+ int cellWidth = 40;
+ try {
+ cellWidth = Integer.parseInt(nvls(raptorProperties.getProperty("max_cell_width_in_excel")).trim());
+ } catch (Exception ex) {
+
+ }
+ return cellWidth;
+ }
+
+ public static synchronized int getFormFieldsCount(HttpServletRequest request)
+ {
+ if(request.getSession().getAttribute(
+ AppConstants.SI_REPORT_RUNTIME) == null )
+ {
+ return 0;
+ }
+
+ ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(
+ AppConstants.SI_REPORT_RUNTIME);
+
+ 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++;
+ }
+ return countOfFields;
+
+ }
+
+ public static synchronized java.util.HashMap getRequestParametersMap(HttpServletRequest request, HashMap paramsMap) {
+ HashMap valuesMap = new HashMap();
+ if(paramsMap.size() <= 0) {
+ return valuesMap;
+ }
+
+ ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(
+ AppConstants.SI_REPORT_RUNTIME);
+ if(rr.getReportType().equals(AppConstants.RT_DASHBOARD)) {
+ rr = (ReportRuntime) request.getSession().getAttribute("FirstDashReport");
+ }
+ 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();
+
+ if(paramsMap.containsKey(formField) ) {
+ String vals = (String) paramsMap.get(formField);
+ StringBuffer value = new StringBuffer("");
+ 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(isMultiValue) {
+ value.append("(");
+ }
+ StringTokenizer st = new StringTokenizer(vals, "|");
+ if(st.countTokens()>0) {
+ while(st.hasMoreTokens()) {
+ if(isMultiValue) value.append("'");
+ String token = st.nextToken();
+ try {
+ if(token !=null && token.length() > 0)
+ token = java.net.URLDecoder.decode(token, "UTF-8");
+ } catch (UnsupportedEncodingException ex) {}
+ catch (IllegalArgumentException ex1){}
+ catch (Exception ex2){}
+ value.append(token);
+ if(isMultiValue) value.append("'");
+ if(st.hasMoreTokens()) {
+ value.append(",");
+ }
+ }
+ } else {
+ String valueStr = "";
+ valueStr = request.getParameter(formField);
+ valueStr = Utils.oracleSafe(valueStr);
+ valueStr = "('" + Utils.replaceInString(valueStr, ",", "'|'") + "')";
+ valueStr = Utils.replaceInString(valueStr, "|", ",");
+ valuesMap.put(fieldNameMap.get(formField), valueStr);
+ valueStr = "";
+ }
+ if(isMultiValue) value.append(")");
+
+ valuesMap.put(fieldNameMap.get(formField), value.toString());
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
+ String valueStr = "";
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) {
+ valueStr = (String) paramsMap.get(formField +"_Hr");
+ valuesMap.put(formField+"_Hr", valueStr);
+ valueStr = "";
+ } else if (ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) {
+ valueStr =(String) paramsMap.get(formField +"_Hr");
+ valuesMap.put(formField+"_Hr", valueStr);
+ valueStr = "";
+ valueStr = (String) paramsMap.get(formField +"_Min");
+ valuesMap.put(formField+"_Min", valueStr);
+ valueStr = "";
+ } else if (ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
+ valueStr = (String) paramsMap.get(formField +"_Hr");
+ valuesMap.put(formField+"_Hr", valueStr);
+ valueStr = "";
+ valueStr =(String) paramsMap.get(formField +"_Min");
+ valuesMap.put(formField+"_Min", valueStr);
+ valueStr = "";
+ valueStr = (String) paramsMap.get(formField +"_Sec");
+ valuesMap.put(formField+"_Sec", valueStr);
+ valueStr = "";
+ }
+ }
+
+ value = new StringBuffer("");
+
+ } else if (paramsMap.containsKey(formField +"_auto")) {
+ String vals = (String) paramsMap.get(formField +"_auto");
+ StringBuffer value = new StringBuffer("");
+ 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(isMultiValue) {
+ value.append("(");
+ }
+ StringTokenizer st = new StringTokenizer(vals, "|");
+ if(st.countTokens()>0) {
+ while(st.hasMoreTokens()) {
+ if(isMultiValue) value.append("'");
+ String token = st.nextToken();
+ try {
+ if(token !=null && token.length() > 0)
+ token = java.net.URLDecoder.decode(Utils.oracleSafe(token), "UTF-8");
+ } catch (UnsupportedEncodingException ex) {}
+ catch (IllegalArgumentException ex1){}
+ catch (Exception ex2){}
+ value.append(token);
+ if(isMultiValue) value.append("'");
+ if(st.hasMoreTokens()) {
+ value.append(",");
+ }
+ }
+ } else {
+ String valueStr = "";
+ valueStr = request.getParameter(formField +"_auto");
+ valueStr = "('" + Utils.replaceInString(valueStr, ",", "'|'") + "')";
+ valueStr = Utils.replaceInString(valueStr, "|", ",");
+ valuesMap.put(fieldNameMap.get(formField), valueStr);
+ valueStr = "";
+ }
+ if(isMultiValue) value.append(")");
+
+ valuesMap.put(fieldNameMap.get(formField), value.toString());
+
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
+ String valueStr = "";
+ if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) {
+ valueStr = (String) paramsMap.get(formField +"_Hr");
+ valuesMap.put(formField+"_Hr", valueStr);
+ valueStr = "";
+ } else if (ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) {
+ valueStr = (String) paramsMap.get(formField +"_Hr");
+ valuesMap.put(formField+"_Hr", valueStr);
+ valueStr = "";
+ valueStr = (String) paramsMap.get(formField +"_Min");
+ valuesMap.put(formField+"_Min", valueStr);
+ valueStr = "";
+ } else if (ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
+ valueStr = (String) paramsMap.get(formField +"_Hr");
+ valuesMap.put(formField+"_Hr", valueStr);
+ valueStr = "";
+ valueStr = (String) paramsMap.get(formField +"_Min");
+ valuesMap.put(formField+"_Min", valueStr);
+ valueStr = "";
+ valueStr = (String) paramsMap.get(formField +"_Sec");
+ valuesMap.put(formField+"_Sec", valueStr);
+ valueStr = "";
+ }
+ }
+ value = new StringBuffer("");
+
+
+ } else
+ valuesMap.put(fieldNameMap.get(formField), "" );
+ }
+ return valuesMap;
+ }
+
+ public static synchronized java.util.HashMap getRequestParamtersMap(HttpServletRequest request) {
+ return getRequestParamtersMap(request, false);
+ }
+
+ public static synchronized java.util.HashMap getRequestParamtersMap(HttpServletRequest request, boolean isFromChild)
+ {
+ HashMap valuesMap = new HashMap();
+ ReportRuntime rr = null;
+ if(request.getSession().getAttribute(
+ AppConstants.SI_REPORT_RUNTIME) == null )
+ {
+ rr = (ReportRuntime) request.getSession().getAttribute("FirstDashReport");
+ if(rr==null)
+ return valuesMap;
+ }
+
+ rr = (ReportRuntime) request.getSession().getAttribute(
+ AppConstants.SI_REPORT_RUNTIME);
+ if(rr!=null && rr.getReportType().equals(AppConstants.RT_DASHBOARD)) {
+ rr = (ReportRuntime) request.getSession().getAttribute("FirstDashReport");
+ }
+
+ 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++;
+ }
+ if(isFromChild) {
+ Hashtable ht = rr.getReportParamValues();
+ Set set = ht.entrySet();
+ HashMap hashMap = new HashMap();
+ Iterator itr = set.iterator();
+ while(itr.hasNext()){
+ Map.Entry entry = (Map.Entry)itr.next();
+ Object key = entry.getKey();
+ Object val = entry.getValue();
+ if(key==null){
+ key = ""; // Or whatever you want
+ }
+ if(val==null){
+ val = ""; // Or whatever you want
+ }
+ hashMap.put(fieldNameMap.get((String)key),val);
+ }
+ return hashMap;
+
+ } else {
+ List formParameter = new ArrayList();
+ String formField = "";
+
+// for(int i = 1 ; i < (countOfFields+1); i++)
+// {
+// formField ="ff"+i;
+//
+// if(request.getParameterValues(formField) != null && request.getParameterValues(formField).length > 1 )
+// {
+// String[] vals = request.getParameterValues(formField);
+// boolean isMultiValue = false;
+// StringBuffer value = new StringBuffer("");
+// if(vals.length > 1) {
+// isMultiValue = true;
+// value.append("(");
+// }
+// for(int j = 0 ; j < vals.length; j++)
+// {
+// if(isMultiValue) value.append("'");
+// try {
+// if(vals[j] !=null && vals[j].length() > 0)
+// 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 > 1) {
+// value.append(")");
+// }
+//
+// //value = value.substring(0 , value.length());
+//
+// valuesMap.put(fieldNameMap.get(formField), value.toString());
+// value = new StringBuffer("");
+//
+// }
+// else if(request.getParameter(formField) != null)
+// {
+// String value = "";
+// value = request.getParameter(formField);
+// try {
+// if(value !=null && value.length() > 0)
+// value = java.net.URLDecoder.decode(request.getParameter(formField), "UTF-8");
+// } catch (UnsupportedEncodingException ex) {}
+// catch (IllegalArgumentException ex1){}
+// catch (Exception ex2){}
+// valuesMap.put(fieldNameMap.get(formField), value);
+//
+// }else
+// {
+// valuesMap.put(fieldNameMap.get(formField), "NULL" );
+// }
+// }
+ 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);
+/* try {
+ value = java.net.URLDecoder.decode(value, "UTF-8");
+ } catch (UnsupportedEncodingException ex) {}
+ catch (IllegalArgumentException ex1){}
+ catch (Exception ex2){}
+*/
+ 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);
+ /*try {
+ value = java.net.URLDecoder.decode(value, "UTF-8");
+ } catch (UnsupportedEncodingException ex) {}
+ catch (IllegalArgumentException ex1){}
+ catch (Exception ex2){}
+*/
+ valuesMap.put(fieldNameMap.get(formField), Utils.oracleSafe(value));
+ }
+
+ } else {
+ valuesMap.put(fieldNameMap.get(formField), "" );
+ }
+
+ }
+
+ return valuesMap;
+ }
+ }
+
+ //new method added to get the help message for schedule tab
+ public static String getScheduleHelpMessage() {
+ return nvls(raptorProperties.getProperty("schedule_help_text"),"").trim();
+ }
+
+ //new method added to get the help message for schedule tab
+ public static String getUseLoginIdInSchedYN() {
+ return nvls(raptorProperties.getProperty("use_loginid_in_schedYN"),"N").trim();
+ }
+
+ //new method to check if map is allowed or not
+ public static String getMapAllowedYN() {
+ return nvls(raptorProperties.getProperty("map_allowed"),"").trim();
+ }
+
+ //new method added to get gmap key
+ public static String getGmapKey() {
+ return nvls(raptorProperties.getProperty("gmap_key"),"").trim();
+ }
+
+// new method added to get gmap
+ public static String getProjectFolder() {
+ return nvls(raptorProperties.getProperty("PROJECT-FOLDER"),"").trim();
+ }
+
+
+ //new method added to get gmap
+ public static String getMarketShapefileFolder() {
+ return nvls(raptorProperties.getProperty("MARKET-SHAPEFILE-FOLDER"),"").trim();
+ }
+
+ //new method added to get gmap
+ public static String getTileSize() {
+ return nvls(raptorProperties.getProperty("TILE-SIZE"),"").trim();
+ }
+
+ // new method added to get gmap
+ public static String getOutputFolder() {
+ return nvls(raptorProperties.getProperty("OUTPUT-FOLDER"),"").trim();
+ }
+
+ //getting server details
+ public static boolean isWeblogicServer() {
+ return nvls(raptorProperties.getProperty("application_server"),"tomcat").trim().toUpperCase().startsWith("WEBLOGIC");
+ }
+
+ public static String getTempFolderURL() {
+ return nvls(AppUtils.getTempFolderURL(),"").trim();
+ }
+
+ public static int getMaxDrillDownLevel() {
+ int drillDownLevel = 1;
+ try {
+ drillDownLevel = Integer.parseInt(nvls(raptorProperties.getProperty("max_drilldown_level")).trim());
+ } catch (Exception ex) {
+
+ }
+ return drillDownLevel;
+ }
+
+ public static int getMemoryThreshold() {
+ int threshold = Integer.parseInt(nvls(raptorProperties.getProperty("memory_threshold_percentage"),"0").trim());
+ if(threshold <= 0) threshold = 0;
+ return threshold;
+ }
+
+ public static boolean showParamsInAllDashboardReports() {
+ return nvls(raptorProperties.getProperty("show_params_in_all_dashboard_reports"),"N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean isAdminRoleEquivalenttoSuperRole() {
+ return nvls(raptorProperties.getProperty("admin_role_equiv_to_super_role"),"N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean showLoadingMsgDuringFormFieldChain() {
+ return nvls(raptorProperties.getProperty("show_loading_during_formfield_chain"),"Y").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean showPrintIcon() {
+ return nvls(raptorProperties.getProperty("show_print_icon"),"Y").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean IsGlobalNoWrap() {
+ return nvls(raptorProperties.getProperty("globally_nowrap"),"N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static String getCalendarOutputDateFormat() {
+ return nvls(raptorProperties.getProperty("calendar_output_date_format"),"MM/dd/yyyy");
+ }
+
+ public static String getUserDefinedMessageForMemoryLimitReached() {
+ return nvls(raptorProperties.getProperty("user_defined_message_memory_limit"),"Please note: Due to limited computing resource at this time,");
+ }
+
+ public static String getAdhocUserRoldId() {
+ return nvls(raptorProperties.getProperty("adhoc_user_roleId"),"");
+ }
+
+ public static String getAdhocReportSequence() {
+ return nvls(raptorProperties.getProperty("adhoc_report_sequence"),"");
+ }
+
+ public static boolean hideToolTipsGlobally() {
+ return nvls(raptorProperties.getProperty("hide_tooltips_in_chart"),"N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean showScheduleIconBeforeRun() {
+ return nvls(raptorProperties.getProperty("show_schedule_icon_before_run"),"Y").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean hideRaptorFooter() {
+ return nvls(raptorProperties.getProperty("hide_raptor_footer"),"N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean getPrintParamsInCSVDownload() {
+ return nvls(raptorProperties.getProperty("print_params_in_csv_download"),"N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static String getLogVariablesInSession() {
+ return nvls(raptorProperties.getProperty("log_variable_in_session"), "");
+ }
+
+ public static boolean hideTitleInDashboard() {
+ return nvls(raptorProperties.getProperty("notitle_in_dashboard"), "N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static String getEncryptedSMTPServer() {
+ return nvls(raptorProperties.getProperty("secure_smtp_server"), "");
+ }
+
+ public static boolean generateSchedReportsInFileSystem() {
+ return nvls(raptorProperties.getProperty("generate_store_sched_reports"), "N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean showExcel2007DownloadIcon() {
+ return nvls(raptorProperties.getProperty("show_excel_2007_download"), "N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean printExcelInLandscapeMode() {
+ return nvls(raptorProperties.getProperty("print_excel_in_landscape"), "").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static String getAppDefinedMessageForSendingSchedAsAttachment() {
+ return nvls(raptorProperties.getProperty("app_defined_message_schedule_attachment"),"Send as Attachment");
+ }
+
+ public static String getReportEmptyMessage() {
+ return nvls(raptorProperties.getProperty("no_rows_found"),"Your Search didn't yield any results.");
+ }
+
+ public static boolean showAnimatedChartOption() {
+ return nvls(raptorProperties.getProperty("show_animated_chart_option"),"N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean showAnimatedChartOnly() {
+ return nvls(raptorProperties.getProperty("show_animated_chart_only"),"N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean adjustContentBasedOnHeight() {
+ return nvls(raptorProperties.getProperty("adjust_content_based_on_height"),"N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean disclaimerPositionedTopInCSVExcel() {
+ return nvls(raptorProperties.getProperty("disclaimer_positioned_top_in_csvexcel"),"N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static String customizedSubmitButtonText() {
+ return nvls(raptorProperties.getProperty("custom_submit_button_text"),"submit");
+ }
+
+ public static String customizedResetButtonText() {
+ return nvls(raptorProperties.getProperty("custom_reset_button_text"),"reset");
+ }
+ public static boolean customizeFormFieldLayout() {
+ return nvls(raptorProperties.getProperty("customize_formfield_layout"),"N").trim().toUpperCase().startsWith("Y");
+ }
+ public static String getRaptorTheme() {
+ return nvls(raptorProperties.getProperty("raptor_theme"),"default");
+ }
+
+ public static String getFormfieldAlignment() {
+ return nvls(raptorProperties.getProperty("formfield_alignment"),"left");
+ }
+
+ public static boolean displayExcelOptionInDashboard() {
+ return nvls(raptorProperties.getProperty("display_excel_option_in_dashboard"),"N").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean displayRuntimeOptionsAsDefault() {
+ return nvls(raptorProperties.getProperty("display_runtime_options_as_default"),"Y").trim().toUpperCase().startsWith("Y");
+ }
+
+ public static boolean displayHiddenFormfieldinExcel() {
+ return nvls(raptorProperties.getProperty("display_hidden_field_in_excel"),"N").trim().toUpperCase().startsWith("Y");
+ }
+
+ //ReportLoader.java
+ public static String getLoadCustomReportXml(){
+ return nvls(sqlProperty.getProperty("load.custom.report.xml"));
+ }
+
+ public static String getDBUpdateReportXml(){
+ return nvls(sqlProperty.getProperty("db.update.report.xml"));
+ }
+
+ public static String getDBUpdateReportXmlMySql(){
+ return nvls(sqlProperty.getProperty("db.update.report.xml.mysql"));
+ }
+
+ public static String getDBUpdateReportXmlMySqlSelect(){
+ return nvls(sqlProperty.getProperty("db.update.report.xml.mysql.select"));
+ }
+
+ public static String getUpdateCustomReportRec(){
+ return nvls(sqlProperty.getProperty("update.custom.report.rec"));
+ }
+
+ public static String getIsReportAlreadyScheduled(){
+ return nvls(sqlProperty.getProperty("is.report.already.scheduled"));
+ }
+
+ public static String getCreateCustomReportRec(){
+ return nvls(sqlProperty.getProperty("create.custom.report.rec"));
+ }
+
+ public static String getTheUserReportNames(){
+ return nvls(sqlProperty.getProperty("get.user.report.names"));
+ }
+
+ public static String getTheReportOwnerId(){
+ return nvls(sqlProperty.getProperty("get.report.owner.id"));
+ }
+
+ public static String getReportSecurity(){
+ return nvls(sqlProperty.getProperty("report.security.create"));
+ }
+
+ public static String getDeleteReportRecordLog(){
+ return nvls(sqlProperty.getProperty("delete.report.record.log"));
+ }
+
+ public static String getDeleteReportRecordUsers(){
+ return nvls(sqlProperty.getProperty("delete.report.record.users"));
+ }
+
+ public static String getDeleteReportRecordSchedule(){
+ return nvls(sqlProperty.getProperty("delete.report.record.schedule"));
+ }
+
+ public static String getDeleteReportRecordAccess(){
+ return nvls(sqlProperty.getProperty("delete.report.record.access"));
+ }
+
+ public static String getDeleteReportRecordEmail(){
+ return nvls(sqlProperty.getProperty("delete.report.record.email"));
+ }
+
+ public static String getDeleteReportRecordFavorite(){
+ return nvls(sqlProperty.getProperty("delete.report.record.favorite"));
+ }
+
+ public static String getDeleteReportRecordReport(){
+ return nvls(sqlProperty.getProperty("delete.report.record.report"));
+ }
+
+ public static String getLoadQuickLinks(){
+ return nvls(sqlProperty.getProperty("load.quick.links"));
+ }
+
+ public static String getLoadFolderReports(){
+ return nvls(sqlProperty.getProperty("load.folder.reports"));
+ }
+
+ public static String getLoadFolderReportsUser(){
+ return nvls(sqlProperty.getProperty("load.folder.reports.user"));
+ }
+
+ public static String getLoadFolderReportsPublicSql(){
+ return nvls(sqlProperty.getProperty("load.folder.reports.publicsql"));
+ }
+
+ public static String getLoadQuickDownloadLinks(){
+ return nvls(sqlProperty.getProperty("load.quick.download.links"));
+ }
+
+ public static String getLoadReportsToSchedule(){
+ return nvls(sqlProperty.getProperty("load.reports.to.schedule"));
+ }
+
+ public static String getLoadReportsToAddInDashboard(){
+ return nvls(sqlProperty.getProperty("load.reports.to.add.in.dashboard"));
+ }
+
+ public static String getLoadMyRecentLinks(){
+ return nvls(sqlProperty.getProperty("load.my.recent.links"));
+ }
+
+ public static String getCreateReportLogEntry(){
+ return nvls(sqlProperty.getProperty("create.report.log.entry"));
+ }
+
+ public static String getCreateReportLogEntryExecTime(){
+ return nvls(sqlProperty.getProperty("create.report.log.entry.exec.time"));
+ }
+
+ public static String getClearReportLogEntries(){
+ return nvls(sqlProperty.getProperty("clear.report.log.entries"));
+ }
+
+ public static String getLoadReportLogEntries(){
+ return nvls(sqlProperty.getProperty("load.report.log.entries"));
+ }
+
+ public static String getDoesUserCanScheduleReport(){
+ return nvls(sqlProperty.getProperty("does.user.can.schedule.report"));
+ }
+
+ public static String getDoesUserCanSchedule(){
+ return nvls(sqlProperty.getProperty("does.user.can.schedule"));
+ }
+
+ public static String getTheSystemDateTime(){
+ return nvls(sqlProperty.getProperty("get.system.date.time"));
+ }
+
+ public static String getTheNextDayDateTime(){
+ return nvls(sqlProperty.getProperty("get.next.day.date.time"));
+ }
+
+ public static String getTheNextFifteenMinDateTime(){
+ return nvls(sqlProperty.getProperty("get.next.fifteen.minutes.date.time"));
+ }
+
+ public static String getTheNextThirtyMinDateTime(){
+ return nvls(sqlProperty.getProperty("get.next.thirty.minutes.date.time"));
+ }
+
+ public static String getTheTemplateFile(){
+ return nvls(sqlProperty.getProperty("get.template.file"));
+ }
+
+ public static String getLoadPdfImgLookup(){
+ return nvls(sqlProperty.getProperty("load.pdf.img.lookup"));
+ }
+
+ public static String getLoadActionImgLookup(){
+ return nvls(sqlProperty.getProperty("load.action.img.lookup"));
+ }
+
+ //ActionHandler.java
+
+ public static String getReportValuesMapDefA(){
+ return nvls(sqlProperty.getProperty("report.values.map.def.a"));
+ }
+ public static String getReportValuesMapDefB(){
+ return nvls(sqlProperty.getProperty("report.values.map.def.b"));
+ }
+ public static String getReportValuesMapDefC(){
+ return nvls(sqlProperty.getProperty("report.values.map.def.c"));
+ }
+ public static String getReportValuesMapDefD(){
+ return nvls(sqlProperty.getProperty("report.values.map.def.d"));
+ }
+
+ public static String getTestSchedCondPopup(){
+ return nvls(sqlProperty.getProperty("test.sched.cond.popup"));
+ }
+
+ public static String getDownloadAllEmailSent(){
+ return nvls(sqlProperty.getProperty("download.all.email.sent"));
+ }
+
+ public static String getDownloadAllGenKey(){
+ return nvls(sqlProperty.getProperty("download.all.gen.key"));
+ }
+
+ public static String getDownloadAllRetrieve(){
+ return nvls(sqlProperty.getProperty("download.all.retrieve"));
+ }
+
+ public static String getDownloadAllInsert(){
+ return nvls(sqlProperty.getProperty("download.all.insert"));
+ }
+
+ //ReportWrapper.java
+
+ public static String getReportWrapperFormat(){
+ return nvls(sqlProperty.getProperty("report.wrapper.format"));
+ }
+
+ public static String getGenerateSubsetSql(){
+ return nvls(sqlProperty.getProperty("generate.subset.sql"));
+ }
+
+ public static String getReportSqlForFormfield(){
+ return nvls(sqlProperty.getProperty("formfield.id.name.sql"));
+ }
+
+ public static String getReportSqlForFormfieldPrefix(){
+ return nvls(sqlProperty.getProperty("formfield.id.name.sql.prefix"));
+ }
+
+ public static String getReportSqlForFormfieldSuffix(){
+ return nvls(sqlProperty.getProperty("formfield.id.name.sql.suffix"));
+ }
+
+ public static String getReportSqlOnlyFirstPart(){
+ return nvls(sqlProperty.getProperty("report.sql.only.first.part"));
+ }
+
+ public static String getReportSqlOnlySecondPartA(){
+ return nvls(sqlProperty.getProperty("report.sql.only.second.part.a"));
+ }
+
+ public static String getReportSqlOnlySecondPartB(){
+ return nvls(sqlProperty.getProperty("report.sql.only.second.part.b"));
+ }
+
+ public static String getReportSqlOnlySecondPartBNoOrderBy(){
+ return nvls(sqlProperty.getProperty("report.sql.only.second.part.b.noorderby"));
+ }
+
+ public static String getGenerateSqlVisualSelect(){
+ return nvls(sqlProperty.getProperty("generate.sql.visual.select"));
+ }
+
+ public static String getGenerateSqlVisualCount(){
+ return nvls(sqlProperty.getProperty("generate.sql.visual.count"));
+ }
+
+ public static String getGenerateSqlVisualDual(){
+ return nvls(sqlProperty.getProperty("generate.sql.visual.select"));
+ }
+
+ //ReportRuntime.java
+
+ public static String getLoadCrosstabReportData(){
+ return nvls(sqlProperty.getProperty("load.crosstab.report.data"));
+ }
+
+ //ReportRunHandler.java
+
+ public static String getGenerateSqlHandler(){
+ return nvls(sqlProperty.getProperty("generate.sql.handler"));
+ }
+
+ public static String getGenerateSqlSelect(){
+ return nvls(sqlProperty.getProperty("generate.sql.select"));
+ }
+
+ public static String getRemoteDbSchemaSql() {
+ return nvls(sqlProperty.getProperty("load.remoteDB.schema"));
+ }
+
+ public static String getRemoteDbSchemaSqlWithWhereClause() {
+ return nvls(sqlProperty.getProperty("load.remoteDB.schema.where"));
+ }
+
+ //ReportSchedule.java
+
+ public static String getLoadScheduleData(){
+ return nvls(sqlProperty.getProperty("load.schedule.data"));
+ }
+
+ public static String getLoadScheduleGetId(){
+ return nvls(sqlProperty.getProperty("load.schedule.getid"));
+ }
+
+ public static String getLoadScheduleUsers(){
+ return nvls(sqlProperty.getProperty("load.schedule.users"));
+ }
+
+ public static String getNewScheduleData(){
+ return nvls(sqlProperty.getProperty("new.schedule.data"));
+ }
+
+ public static String getNewReportData(){
+ return nvls(sqlProperty.getProperty("new.report.data"));
+ }
+
+ public static String getExecuteUpdate(){
+ return nvls(sqlProperty.getProperty("execute.update"));
+ }
+
+ public static String getExecuteUpdateUsers(){
+ return nvls(sqlProperty.getProperty("execute.update.users"));
+ }
+
+ public static String getExecuteUpdateRoles(){
+ return nvls(sqlProperty.getProperty("execute.update.roles"));
+ }
+
+ public static String getExecuteUpdateActivity(){
+ return nvls(sqlProperty.getProperty("execute.update.activity"));
+ }
+
+ public static String getDeleteScheduleData(){
+ return nvls(sqlProperty.getProperty("delete.schedule.data"));
+ }
+
+ public static String getDeleteScheduleDataUsers(){
+ return nvls(sqlProperty.getProperty("delete.schedule.data.users"));
+ }
+
+ public static String getDeleteScheduleDataId(){
+ return nvls(sqlProperty.getProperty("delete.schedule.data.id"));
+ }
+
+ public static String getLoadCondSql(){
+ return nvls(sqlProperty.getProperty("load.cond.sql"));
+ }
+
+ public static String getLoadCondSqlSelect(){
+ return nvls(sqlProperty.getProperty("load.cond.sql.select"));
+ }
+
+ public static String getPersistCondSqlUpdate(){
+ return nvls(sqlProperty.getProperty("persist.cond.sql.update"));
+ }
+
+ public static String getPersistCondSqlLarge(){
+ return nvls(sqlProperty.getProperty("persist.cond.sql.large"));
+ }
+
+ public static String getPersistCondSqlSet(){
+ return nvls(sqlProperty.getProperty("persist.cond.sql.set"));
+ }
+
+ //DataCache.java
+
+ public static String getTheDataViewActions(){
+ return nvls(sqlProperty.getProperty("get.data.view.actions"));
+ }
+
+ public static String getThePublicReportIdNames(){
+ return nvls(sqlProperty.getProperty("get.public.report.id.names"));
+ }
+
+ public static String getThePrivateAccessibleNamesA(){
+ return nvls(sqlProperty.getProperty("get.private.accessible.names.a"));
+ }
+ public static String getThePrivateAccessibleNamesIf(){
+ return nvls(sqlProperty.getProperty("get.private.accessible.names.if"));
+ }
+ public static String getThePrivateAccessibleNamesB(){
+ return nvls(sqlProperty.getProperty("get.private.accessible.names.b"));
+ }
+
+ public static String getTheGroupAccessibleNamesA(){
+ return nvls(sqlProperty.getProperty("get.group.accessible.names.a"));
+ }
+
+ public static String getTheGroupAccessibleNamesB(){
+ return nvls(sqlProperty.getProperty("get.group.accessible.names.b"));
+ }
+
+ public static String getTheReportTableSourcesA(){
+ return nvls(sqlProperty.getProperty("get.report.table.sources.a"));
+ }
+
+ public static String getTheReportTableSourcesWhere(){
+ return nvls(sqlProperty.getProperty("get.report.table.sources.where"));
+ }
+
+ public static String getTheReportTableSourcesIf(){
+ return nvls(sqlProperty.getProperty("get.report.table.sources.if"));
+ }
+
+ public static String getTheReportTableSourcesElse(){
+ return nvls(sqlProperty.getProperty("get.report.table.sources.else"));
+ }
+
+ public static String grabTheReportTableA(){
+ return nvls(sqlProperty.getProperty("grab.report.table.a"));
+ }
+
+ public static String grabTheReportTableIf(){
+ return nvls(sqlProperty.getProperty("grab.report.table.if"));
+ }
+
+ public static String grabTheReportTableElse(){
+ return nvls(sqlProperty.getProperty("grab.report.table.else"));
+ }
+
+ public static String grabTheReportTableB(){
+ return nvls(sqlProperty.getProperty("grab.report.table.b"));
+ }
+
+ public static String grabTheReportTableC(){
+ return nvls(sqlProperty.getProperty("grab.report.table.c"));
+ }
+
+ public static String getTheReportTableCrJoin(){
+ return nvls(sqlProperty.getProperty("get.report.table.crjoin"));
+ }
+
+ public static String getTheReportTableJoins(){
+ return nvls(sqlProperty.getProperty("get.report.table.joins"));
+ }
+
+ public static String getGenerateReportTableCol(){
+ return nvls(sqlProperty.getProperty("generate.report.table.col"));
+ }
+
+
+ public static String getGenerateDbUserSqlA(){
+ return nvls(sqlProperty.getProperty("generate.db.user.sql.a"));
+ }
+
+ public static String getGenerateDbUserSqlIf(){
+ return nvls(sqlProperty.getProperty("generate.db.user.sql.if"));
+ }
+
+ public static String getGenerateDbUserSqlElse(){
+ return nvls(sqlProperty.getProperty("generate.db.user.sql.else"));
+ }
+
+ public static String getGenerateDbUserSqlB(){
+ return nvls(sqlProperty.getProperty("generate.db.user.sql.b"));
+ }
+
+ public static String getGenerateDbUserSqlC(){
+ return nvls(sqlProperty.getProperty("generate.db.user.sql.c"));
+ }
+
+ public static String getGenerateDbUserSqlD(){
+ return nvls(sqlProperty.getProperty("generate.db.user.sql.d"));
+ }
+
+ //SearchHandler.java
+
+ public static String getLoadReportSearchResult(){
+ return nvls(sqlProperty.getProperty("load.report.search.result"));
+ }
+
+ public static String getLoadReportSearchRepIdSql(){
+ return nvls(sqlProperty.getProperty("load.report.search.rep_id_sql"));
+ }
+
+ public static String getLoadReportSearchInstr(){
+ return nvls(sqlProperty.getProperty("load.report.search.instr"));
+ }
+
+ public static String getLoadReportSearchResultUser(){
+ return nvls(sqlProperty.getProperty("load.report.search.result.user"));
+ }
+
+ public static String getLoadReportSearchResultPublic(){
+ return nvls(sqlProperty.getProperty("load.report.search.result.public"));
+ }
+
+ public static String getLoadReportSearchResultFav(){
+ return nvls(sqlProperty.getProperty("load.report.search.result.fav"));
+ }
+
+ public static String getLoadReportSearchResultSort(){
+ return nvls(sqlProperty.getProperty("load.report.search.result.sort"));
+ }
+
+ public static String getLoadFolderReportResult(){
+ return nvls(sqlProperty.getProperty("load.folder.report.result"));
+ }
+
+ public static String getLoadFolderReportResultSort(){
+ return nvls(sqlProperty.getProperty("load.folder.report..result.sort"));
+ }
+
+ //WizardProcessor.java
+
+ public static String getProcessFilterAddEdit(){
+ return nvls(sqlProperty.getProperty("process.filter.add.edit"));
+ }
+
+ //ReportDefinition.java
+
+ public static String getPersistReportAdhoc(){
+ return nvls(sqlProperty.getProperty("persist.report.adhoc"));
+ }
+
+ //Globals.java
+ public static String getInitializeRoles(){
+ return nvls(sqlProperty.getProperty("initialize.roles"));
+ }
+
+ public static String getInitializeVersion(){
+ return nvls(sqlProperty.getProperty("initialize.version"));
+ }
+
+ public static String getDBType(){
+ return nvls(raptorProperties.getProperty("db_type"), "oracle");
+ }
+
+ public static boolean isPostgreSQL(){
+ return getDBType().equals("postgresql");
+ }
+ public static boolean isMySQL(){
+ return getDBType().equals("mysql");
+ }
+ public static boolean isOracle(){
+ return getDBType().equals("oracle");
+ }
+
+ //scheduler
+ public static String getAvailableSchedules(){
+ return nvls(sqlProperty.getProperty("scheduler.available.schedules"));
+ }
+
+ public static String getCurrentDateString(){
+ return nvls(sqlProperty.getProperty("current.date.string"));
+ }
+
+ public static String getSchedulerUserEmails(){
+ return nvls(sqlProperty.getProperty("scheduler.user.emails"));
+ }
+
+ public static String getSqlConvertToRaw(){
+ return nvls(sqlProperty.getProperty("convert.to.raw"));
+ }
+
+ public static Properties getRaptorPdfProperties() {
+ return raptorPdfProperties;
+ }
+
+ public static void setRaptorPdfProperties(Properties raptorPdfProperties) {
+ Globals.raptorPdfProperties = raptorPdfProperties;
+ }
+
+ public static Properties getRaptorProperties() {
+ return raptorProperties;
+ }
+
+ public static void setRaptorProperties(Properties raptorProperties) {
+ Globals.raptorProperties = raptorProperties;
+ }
+
+ public static Properties getSqlProperty() {
+ return sqlProperty;
+ }
+
+ public static void setSqlProperty(Properties sqlProperty) {
+ Globals.sqlProperty = sqlProperty;
+ }
+
+ public static String getSequenceNextVal() {
+ return nvls(sqlProperty.getProperty("seq.next.val"));
+ }
+
+ public static String getRandomString() {
+ return nvls(sqlProperty.getProperty("seq.next.val"));
+ }
+
+ public static String getReportUserAccess(){
+ return nvls(sqlProperty.getProperty("report.user.access"));
+ }
+
+ public static String getAddUserAccess(){
+ return nvls(sqlProperty.getProperty("add.user.access"));
+ }
+
+ public static String getUpdateUserAccess(){
+ return nvls(sqlProperty.getProperty("update.user.access"));
+ }
+
+ public static String getRemoveUserAccess(){
+ return nvls(sqlProperty.getProperty("remove.user.access"));
+ }
+
+ public static String getAddRoleAccess(){
+ return nvls(sqlProperty.getProperty("add.role.access"));
+ }
+
+ public static String getUpdateRoleAccess(){
+ return nvls(sqlProperty.getProperty("update.role.access"));
+ }
+
+ public static String getRemoveRoleAccess(){
+ return nvls(sqlProperty.getProperty("remove.role.access"));
+ }
+
+ public static boolean isSystemInitialized() {
+ return systemInitialized;
+ }
+
+} // Globals
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system;
+
+import java.util.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+
+public interface IAppUtils {
+ void initializeAppUtils(ServletContext servletContext);
+
+ /** Returns ID of the user currently logged in */
+ String getUserID(HttpServletRequest request);
+
+ /** Obtains user name by ID */
+ String getUserName(HttpServletRequest request);
+ String getUserName(String userId);
+
+ /** Obtains user email by ID */
+ String getUserEmail(HttpServletRequest request);
+ String getUserEmail(String userId);
+
+ /** Obtains user login ID */
+ String getUserLoginId(HttpServletRequest request);
+ String getUserLoginId(String userId);
+
+ /** Obtains user back door log id */
+ String getUserBackdoorLoginId(HttpServletRequest request);
+
+ /** Obtains list of all users (in IdNameValue objects) */
+ Vector getAllUsers(String customizedQuery, String param, boolean isAdmin);
+
+ /** Obtains role name by ID */
+ String getRoleName(String roleId);
+
+ /** Obtains list of all roles (in IdNameValue objects) */
+ Vector getAllRoles(String customizedQuery, String param, boolean isAdmin);
+
+ /** Checks whether the user currently logged in has the specified role */
+ // boolean isUserInRole(HttpServletRequest request, String roleId);
+ /** Checks whether the specified user has the specified role */
+ boolean isUserInRole(HttpServletRequest request, String roleId) throws RaptorException ;
+
+ /**
+ * Returns Vector containing the IDs of all the roles to which the user
+ * currently logged in belongs
+ */
+ // Vector getUserRoles(HttpServletRequest request);
+ /**
+ * Returns Vector containing the IDs of all the roles to which the specified
+ * user belongs
+ */
+ Vector getUserRoles(HttpServletRequest request)throws RaptorException;
+
+ Vector getUserRoles(String userID)throws RaptorException;
+ /** Empties cached lists of app users and roles */
+ void resetUserCache();
+
+ /** Returns the ID of the super role (all powerful) */
+ String getSuperRoleID();
+
+ /** Returns Vector containing the IDs of all Admin roles */
+ Vector getAdminRoleIDs();
+
+ /** Returns Temp folder file path */
+ String getTempFolderPath();
+
+ /** Returns Upload folder file path */
+ String getUploadFolderPath();
+
+ /** Returns Temp folder web URL */
+ String getTempFolderURL();
+
+ /** Returns Upload folder web URL */
+ String getUploadFolderURL();
+
+ /** Returns SMTP server to be used for notifications */
+ String getSMTPServer()throws RaptorException ;
+
+ /** Returns Encrypted SMTP server to be used for notifications */
+ String getEncryptedSMTPServer()throws RaptorException ;
+
+ /**
+ * Returns email address used for the "From" field in the system
+ * notifications
+ */
+ String getDefaultEmailSender() throws RaptorException;
+
+ /** Returns the application error page */
+ String getErrorPage();
+
+ /** Returns the application error page with menu for fusion*/
+ String getErrorPageWMenu();
+
+ /** Returns path to the folder containing JSP pages */
+ String getJspContextPath();
+
+ /** Returns web URL of the folder containing the images */
+ String getImgFolderURL();
+
+ /** Returns web URL to the base raptor folder */
+ String getBaseFolderURL();
+
+ /** Returns the URL used for executing a report - system specific */
+ // String getReportExecuteActionURL();
+ /** Returns the URL used for displaying data record - system specific */
+ // String getDataViewActionURL();
+ /**
+ * Returns the parameter name of the ID value used for displaying data
+ * record - system specific
+ */
+ // String getDataViewActionParam();
+ /** Returns full web URL for direct access to execute a report */
+ String getDirectAccessURL();
+
+ /** Returns the URL of the controller servlet - system specific */
+ String getBaseActionURL();
+
+ /** Returns the base URL of the NG report - system specific */
+ String getBaseActionURLNG();
+
+ /** Returns the URL of the Report Run specifc to AngularJS */
+ String getDrillActionURL();
+
+ /** Returns the primary parameter name - system specific */
+ String getBaseActionParam();
+
+ /** Returns Vector containing menu IDs for quick links */
+ Vector getQuickLinksMenuIDs();
+
+ /** Obtains menu label by ID */
+ String getMenuLabel(String menuId);
+
+ /**
+ * SQL for loading the screen labels and restricting to active cols only for
+ * report columns; can return null => use straight data dictionary For
+ * PRISMS - based on "useFieldTable" config parameter
+ */
+ String getReportDbColsMaskSQL();
+
+ /**
+ * SQL for replacing lookup tables with id and name values; can return null =>
+ * do NOT replace lookups Returns SQL with columns - Table_name, Field_name,
+ * New_Lookup_Table_name, New_Lookup_Id_Field_name,
+ * New_Lookup_Name_Field_name For PRISMS - based on "useFieldTable" config
+ * parameter
+ */
+ String getReportDbLookupsSQL();
+
+ /** Obtains menu label by ID */
+ void processErrorNotification(HttpServletRequest request, RaptorException e);
+
+ /** Returns Excel template PATH web URL */
+ String getExcelTemplatePath();
+
+ String getFolderPathAdj();
+} // IAppUtils
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system;
+
+import java.sql.*;
+import java.util.*;
+import javax.servlet.*;
+
+import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+
+public interface IDbUtils {
+ void initializeDbUtils(ServletContext servletContext);
+
+ Connection getConnection() throws ReportSQLException ;
+
+ void clearConnection(Connection con) throws ReportSQLException ;
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system;
+
+import java.sql.*;
+import javax.servlet.*;
+
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+
+public interface RDbUtils {
+
+ void initializeDbUtils(ServletContext servletContext);
+
+ Connection getRemoteConnection(String dbKey)throws ReportSQLException;
+
+ void clearConnection(Connection con)throws ReportSQLException;
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class RemDbUtils /* implements IDbUtils */{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RemDbUtils.class);
+
+ public RemDbUtils() {
+ }
+
+ public static Connection getConnection(String dbKey) throws ReportSQLException {
+ return Globals.getRDbUtils().getRemoteConnection(dbKey);
+ } // getConnection
+
+ public static void clearConnection(Connection con) throws ReportSQLException {
+ try {
+ if ((con != null) && !con.isClosed())
+ Globals.getRDbUtils().clearConnection(con);
+ } catch (SQLException ex) { throw new ReportSQLException(ex.getMessage()); }
+
+ } // clearConnection
+
+ public static Connection startTransaction(String dbKey) throws RaptorException {
+ Connection con = null;
+ try {
+ con = getConnection(dbKey);
+ con.setAutoCommit(false);
+ } catch (SQLException ex) {
+ throw new RaptorRuntimeException (ex.getMessage(), ex.getCause());
+ } catch (Exception ex2 ) {
+ throw new RaptorException (ex2.getMessage(), ex2.getCause());
+ }
+ return con;
+ } // startTransaction
+
+ public static void commitTransaction(Connection con) throws RaptorException {
+ try {
+ con.commit();
+ } catch (SQLException ex) {
+ throw new RaptorRuntimeException (ex.getMessage(), ex.getCause());
+ } catch (Exception ex2 ) {
+ throw new RaptorException (ex2.getMessage(), ex2.getCause());
+ }
+ //clearConnection(con);
+ } // commitTransaction
+
+ public static void rollbackTransaction(Connection con) throws RaptorException {
+ try {
+ con.rollback();
+ clearConnection(con);
+ } catch (SQLException ex) {
+ throw new RaptorRuntimeException (ex.getMessage(), ex.getCause());
+ } catch (Exception ex2 ) {
+ throw new RaptorException (ex2.getMessage(), ex2.getCause());
+ }
+ } // rollbackTransaction
+
+// public static String executeCall(Connection con, String sql, boolean expectResult)
+// throws ReportSQLException, Exception {
+// String result = null;
+//
+// try {
+// if(con.isClosed()) con = getConnection();
+// Log.write("[SQL Call] " + sql, 4);
+// CallableStatement stmt = con.prepareCall(sql);
+// if (expectResult)
+// stmt.registerOutParameter(1, Types.CHAR);
+// stmt.executeUpdate();
+// if (expectResult)
+// result = stmt.getString(1);
+// stmt.close();
+// con.commit();
+// } catch (SQLException e) {
+// throw new ReportSQLException(e.getMessage(), sql);
+// } finally {
+// clearConnection(con);
+// }
+//
+// return result;
+// } // executeCall
+//
+// public static String executeCall(String sql, boolean expectResult)
+// throws ReportSQLException, Exception {
+// Connection con = null;
+// try {
+// con = getConnection();
+// String result = executeCall(con, sql, expectResult);
+// return result;
+// } catch (SQLException e) {
+// throw new ReportSQLException(e.getMessage(), sql);
+// }
+// } // executeCall
+//
+// public static int executeUpdate(Connection con, String sql) throws ReportSQLException, Exception {
+// try {
+// if(con.isClosed()) con = getConnection();
+// Statement stmt = con.createStatement();
+//
+// int rcode = -1;
+// try {
+// Log.write("[SQL Update] " + sql, 4);
+// rcode = stmt.executeUpdate(sql);
+// stmt.close();
+// con.commit();
+// } finally {
+// clearConnection(con);
+// }
+//
+// return rcode;
+// } catch (SQLException e) {
+// throw new ReportSQLException(e.getMessage(), sql);
+// } finally {
+// clearConnection(con);
+// }
+// } // executeUpdate
+//
+// public static int executeUpdate(String sql) throws ReportSQLException, Exception {
+// Connection con = null;
+// try {
+// con = getConnection();
+// int rcode = executeUpdate(con, sql);
+// return rcode;
+// } catch (SQLException e) {
+// throw new ReportSQLException(e.getMessage(), sql);
+// }
+// } // executeUpdate
+
+ public static DataSet executeQuery(Connection con, String sql, String dbKey) throws ReportSQLException, Exception {
+ return executeQuery(con, sql, Integer.MAX_VALUE,dbKey);
+ } // executeQuery
+
+ public static DataSet executeQuery(Connection con, String sql, int maxRowLimit, String dbKey)
+ throws ReportSQLException {
+ try {
+ if (con==null || con.isClosed()) con = getConnection(dbKey);
+ if(con==null) throw new ReportSQLException("Remote Connection not configured for "+ dbKey);
+ Statement stmt = con.createStatement();
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[SQL CALL FROM RAPTOR] [SQL] " + sql));
+ ResultSet rs = stmt.executeQuery(sql);
+ DataSet ds = new DataSet(rs, maxRowLimit);
+ if(rs!=null)
+ rs.close();
+ if(stmt!=null)
+ stmt.close();
+
+ return ds;
+ } catch (SQLException e) {
+ throw new ReportSQLException(e.getMessage(), sql, e.getCause());
+ }
+ } // executeQuery
+
+ public static DataSet executeQuery(String sql,String dbKey) throws ReportSQLException {
+ return executeQuery(sql, Integer.MAX_VALUE, dbKey);
+ } // executeQuery
+
+ public static DataSet executeQuery(String sql, int maxRowLimit, String dbKey) throws ReportSQLException{
+ Connection con = null;
+ try {
+ con = getConnection(dbKey);
+ return executeQuery(con, sql, maxRowLimit,dbKey);
+ } catch (ReportSQLException e) {
+ throw new ReportSQLException(e.getMessage(), sql, e.getCause());
+ } finally {
+ clearConnection(con);
+ }
+ } // executeQuery
+
+} // DbUtils
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion;
+
+import java.io.IOException;
+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_fusion.jar" command.
+ */
+public class AntBuild {
+
+ public static void main(String[] args) {
+ System.out.println("Jar (raptor_fusion.jar) Information: ");
+ readManifest();
+ }
+
+ public static void readManifest() {
+ try {
+ JarFile jar = new JarFile("./raptor_fusion.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("JDK Version " + " : " + attributeValue);
+ else if (attributeName.toString().equals("Ant-Version"))
+ System.out.println(attributeName.toString() + " : " + attributeValue);
+ else {
+ if(attributeName.toString().startsWith("Raptor"))
+ System.out.println(attributeName.toString() + " : " + attributeValue);
+ }
+ }
+
+ } catch (IOException e) {
+ System.err.println("Cannot read jar-file manifest: "
+ + e.getMessage());
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.analytics.config.ConfigLoader;
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.model.base.IdNameValue;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.system.IAppUtils;
+import org.onap.portalsdk.analytics.system.fusion.adapter.RaptorAdapter;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;;
+
+public class AppUtils extends org.onap.portalsdk.analytics.RaptorObject implements IAppUtils {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppUtils.class);
+
+ private static String tempFolderPath = "/artemis/PROJECT1/MSA/databank/WEB-INF/temp/";
+ private static String uploadFolderPath = "/artemis/PROJECT1/MSA/databank/WEB-INF/upload/";
+ private static String tempFolderURL = "temp/";
+ private static String uploadFolderURL = "upload/";
+ private static String SMTPServer = "todo.smtp.server.com";
+ private static String defaultEmailSender = "todo.email.sender.com";
+ private static String errorPage = "error_page";
+ private static String errorPageWMenu = "error_page_wmenu";
+ private static String jspContextPath = "raptor/";
+ private static String imgFolderURL = "raptor/images/";
+ private static String baseFolderURL = "raptor/";
+ //private static String reportExecuteActionURL = "dispatcher?action=raptor&r_action=report.run&c_master=";
+ //private static String dataViewActionURL = "dispatcher?action="; // dispatcher?action=ACTION_ID&c_master=REC_ID
+ //private static String dataViewActionParam = "c_master=";
+ private static String directAccessURL = "http://localhost:8082/databank/dispatcher?direct.access=raptor&r_action=report.run&show=";
+ private static String baseActionURL = "dispatcher?action="; // dispatcher?action=ACTION_ID&c_master=REC_ID or dispatcher?action=raptor&r_action=RAPTOR_ACTION_ID&c_master=REC_ID
+ private static String baseActionURLNG = "report#/"; // dispatcher?action=ACTION_ID&c_master=REC_ID or dispatcher?action=raptor&r_action=RAPTOR_ACTION_ID&c_master=REC_ID
+ private static String drillActionURL = "dispatcher?action="; // dispatcher?action=ACTION_ID&c_master=REC_ID or dispatcher?action=raptor&r_action=RAPTOR_ACTION_ID&c_master=REC_ID
+ private static String baseActionParam = "c_master=";
+ private static String superRoleID = "1";
+ private static Vector adminRoleIDs = new Vector();
+ private static Vector quickLinksMenuIDs = new Vector();
+
+ private static Properties raptorAppProperties;
+
+ private static String encryptedSMTPServer = "";
+ public AppUtils() {}
+
+ public void initializeAppUtils(ServletContext servletContext) {
+ try {
+ Properties appProperties = ConfigLoader.getProperties(servletContext, ConfigLoader.APP_PROPERTIES, Globals.getSystemType());
+ raptorAppProperties = appProperties;
+ tempFolderPath = appProperties.getProperty("temp_folder_path");
+ uploadFolderPath = appProperties.getProperty("upload_folder_path");
+ tempFolderURL = appProperties.getProperty("temp_folder_url");
+ uploadFolderURL = appProperties.getProperty("upload_folder_url");
+ SMTPServer = appProperties.getProperty("smtp_server");
+ encryptedSMTPServer = appProperties.getProperty("encrypted_smtp_server");
+ defaultEmailSender = appProperties.getProperty("default_email_sender");
+ errorPage = appProperties.getProperty("error_page");
+ jspContextPath = appProperties.getProperty("jsp_context_path");
+ imgFolderURL = appProperties.getProperty("img_folder_url");
+ baseFolderURL = appProperties.getProperty("base_folder_url");
+/* reportExecuteActionURL = appProperties.getProperty("report_execute_action_url");
+ dataViewActionURL = appProperties.getProperty("data_view_action_url");
+ dataViewActionParam = appProperties.getProperty("data_view_action_param");*/
+ directAccessURL = appProperties.getProperty("direct_access_url");
+ baseActionURL = appProperties.getProperty("base_action_url");
+ baseActionURLNG = appProperties.getProperty("base_action_url_ng");
+ drillActionURL = appProperties.getProperty("drill_action_url");
+ baseActionParam = appProperties.getProperty("base_action_param");
+ superRoleID = appProperties.getProperty("super_role_id");
+
+ adminRoleIDs.removeAllElements();
+ StringTokenizer st = new StringTokenizer(appProperties.getProperty("admin_role_ids"), ",");
+ while(st.hasMoreTokens())
+ adminRoleIDs.add(st.nextToken());
+
+ quickLinksMenuIDs.removeAllElements();
+ st = new StringTokenizer(appProperties.getProperty("quick_links_menu_ids"), ",");
+ while(st.hasMoreTokens())
+ quickLinksMenuIDs.add(st.nextToken());
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] AppUtils.initializeAppUtils: Unable to load properties ["+Globals.getSystemType()+"_"+ConfigLoader.APP_PROPERTIES+"]. Exception: "+e.getMessage()));
+ //throw new RuntimeException(e.getMessage());
+ }
+ } // initializeAppUtils
+
+ public static void getFullURL(HttpServletRequest req) {
+ String applicationBase = "";
+ if (applicationBase == null) {
+ applicationBase = req.getScheme() + "://" + req.getServerName() +
+ getPort(req) + req.getContextPath();
+ }
+ }
+
+ private static String getPort(HttpServletRequest req) {
+ if ("http".equalsIgnoreCase(req.getScheme()) && req.getServerPort() != 80 ||
+ "https".equalsIgnoreCase(req.getScheme()) && req.getServerPort() != 443 ) {
+ return (":" + req.getServerPort());
+ } else {
+ return "";
+ }
+ }
+ public String getUserID(HttpServletRequest request) {
+ String pdfAttachmentKey = org.onap.portalsdk.analytics.system.AppUtils.getRequestValue(request, "pdfAttachmentKey");
+ String report_email_sent_log_id = org.onap.portalsdk.analytics.system.AppUtils.getRequestValue(request, "log_id");
+ boolean isEmailAttachment = false;
+ if(pdfAttachmentKey != null && report_email_sent_log_id !=null)
+ isEmailAttachment = true;
+ if(isEmailAttachment) {
+ return RaptorAdapter.getUserID(org.onap.portalsdk.analytics.system.AppUtils.getRequestValue(request, "user_id"));
+ } else
+ return RaptorAdapter.getUserID(request);
+ } // getUserID
+
+ public Vector getAllUsers(String customizedQuery, String param, boolean isAdmin) {
+ Map map = RaptorAdapter.getAllUsers(customizedQuery, param, isAdmin);
+
+ Vector vector = new Vector(map.size());
+ for(Iterator iter=map.keySet().iterator(); iter.hasNext(); ) {
+ Long key = (Long) iter.next();
+ vector.add(new IdNameValue(""+key, (String) map.get(key)));
+ } // for
+
+ return vector;
+ } // getAllUsers
+
+ public String getRoleName(String roleId) {
+ return RaptorAdapter.getRoleName(roleId);
+ } // getRoleName
+
+ public Vector getAllRoles(String customizedQuery, String param, boolean isAdmin) {
+ Map map = RaptorAdapter.getAllRolesUsingCustomizedQuery(customizedQuery, param, isAdmin);
+
+ Vector vector = new Vector(map.size());
+ for(Iterator iter=map.keySet().iterator(); iter.hasNext(); ) {
+ Long key = (Long) iter.next();
+ vector.add(new IdNameValue(""+key, (String) map.get(key)));
+ } // for
+
+ return vector;
+ } // getAllRoles
+
+ public String getUserName(HttpServletRequest request) {
+ return RaptorAdapter.getUserName(request);
+ } // getUserName
+
+ public String getUserName(String userId) {
+ return RaptorAdapter.getUserName(userId);
+ } // getUserName
+
+ public String getUserEmail(String userId) {
+ return RaptorAdapter.getUserEmail(userId);
+ } // getUserEmail
+
+ public String getUserEmail(HttpServletRequest request) {
+ return RaptorAdapter.getUserEmail(request);
+ } // getUserEmail
+
+ public String getUserLoginId(HttpServletRequest request) {
+ return RaptorAdapter.getUserLoginId(request);
+ } // getUserLoginId
+
+ public String getUserLoginId(String userId) {
+ return RaptorAdapter.getUserLoginId(userId);
+ } // getUserLoginId
+
+ public String getUserBackdoorLoginId(HttpServletRequest request) {
+ String pdfAttachmentKey = org.onap.portalsdk.analytics.system.AppUtils.getRequestValue(request, "pdfAttachmentKey");
+ String report_email_sent_log_id = org.onap.portalsdk.analytics.system.AppUtils.getRequestValue(request, "log_id");
+ boolean isEmailAttachment = false;
+ if(pdfAttachmentKey != null && report_email_sent_log_id !=null)
+ isEmailAttachment = true;
+ if(isEmailAttachment) {
+ return RaptorAdapter.getUserBackdoorLoginId(org.onap.portalsdk.analytics.system.AppUtils.getRequestValue(request, "user_id"));
+ } else
+ return RaptorAdapter.getUserBackdoorLoginId(request);
+ } // getUserBackdoorLoginId
+
+ public boolean isUserInRole(HttpServletRequest request, String roleId) {
+ return RaptorAdapter.isCurrentUserInRole(request, roleId);
+ } // isUserInRole
+
+ public Vector getUserRoles(HttpServletRequest request) {
+// Map map = RaptorAdapter.getAllRoles(userId);
+ Set set = RaptorAdapter.getUserRoles(request);
+
+ Vector vector = new Vector(set.size());
+ for(Iterator iter=set.iterator(); iter.hasNext(); ) {
+ Long key = (Long) iter.next();
+ vector.add(""+key);
+ //vector.add(new IdNameValue(""+key, (String) map.get(key)));
+ } // for
+
+ return vector;
+ } // getUserRoles
+
+ public Vector getUserRoles(String userId) {
+ Set set = RaptorAdapter.getUserRoles(userId);
+
+ Vector vector = new Vector(set.size());
+ for(Iterator iter=set.iterator(); iter.hasNext(); ) {
+ Long key = (Long) iter.next();
+ vector.add(""+key);
+ //vector.add(new IdNameValue(""+key, (String) map.get(key)));
+ } // for
+
+ return vector;
+ //return null;
+ } // getUserRoles
+
+ public void resetUserCache() {
+ } // resetUserCache
+
+ public String getSuperRoleID(){
+ return superRoleID;
+ } // getSuperRoleID
+
+ public Vector getAdminRoleIDs(){
+ return adminRoleIDs;
+ } // getAdminRoleIDs
+
+
+ public String getTempFolderPath() {
+ return tempFolderPath;
+ } // getTempFolderPath
+
+ public String getUploadFolderPath() {
+ return uploadFolderPath;
+ } // getUploadFolderPath
+
+ public String getTempFolderURL() {
+ return tempFolderURL;
+ } // getTempFolderURL
+
+ public String getUploadFolderURL() {
+ return uploadFolderURL;
+ } // getUploadFolderURL
+
+ public String getSMTPServer() {
+ return SMTPServer;
+ } // getSMTPServer
+
+ public String getDefaultEmailSender() {
+ return defaultEmailSender;
+ } // getDefaultEmailSender
+
+ public String getErrorPage() {
+ return errorPage;
+ } // getErrorPage
+
+ public String getJspContextPath() {
+ return jspContextPath;
+ } // getJspContextPath
+
+ public String getImgFolderURL() {
+ return imgFolderURL;
+ } // getImgFolderURL
+
+ public String getBaseFolderURL() {
+ return baseFolderURL;
+ } // getBaseFolderURL
+
+/* public String getReportExecuteActionURL() {
+ return reportExecuteActionURL;
+ } // getReportExecuteActionURL
+
+ public String getDataViewActionURL() {
+ return dataViewActionURL;
+ } // getDataViewActionURL
+
+ public String getDataViewActionParam() {
+ return dataViewActionParam;
+ } // getDataViewActionParam
+*/
+ public String getDirectAccessURL() {
+ return directAccessURL.trim();
+ } // getDirectAccessURL
+
+ public String getBaseActionURL() {
+ return baseActionURL;
+ } // getBaseActionURL
+
+ public String getBaseActionURLNG() {
+ return baseActionURLNG;
+ } // getBaseActionURLNG
+
+ public String getDrillActionURL() {
+ return drillActionURL;
+ } // getBaseActionURL
+
+ public String getBaseActionParam() {
+ return baseActionParam;
+ } // getBaseActionParam
+
+ public Vector getQuickLinksMenuIDs(){
+ return quickLinksMenuIDs;
+ } // getQuickLinksMenuIDs
+
+ public String getMenuLabel(String menuId) {
+ //return menuId.substring(0, 1).toUpperCase()+menuId.substring(1).toLowerCase();
+ return menuId;
+ } // getMenuLabel
+
+ public String getReportDbColsMaskSQL() {
+ return null;
+/* Example:
+ return "SELECT f.table_name, UPPER(f.column_name) column_name, f.label "+
+ "FROM fields f WHERE f.active_yn = 'Y'"; */
+ } // getReportDbColsMaskSQL
+
+ public String getReportDbLookupsSQL() {
+ return null;
+/* Example:
+ return "SELECT DISTINCT f.table_name, UPPER(f.column_name) column_name, f.lookup_table, f.lookup_id_field, f.lookup_name_field "+
+ "FROM fields f WHERE f.active_yn = 'Y'"; */
+ } // getReportDbLookupsSQL
+
+ public void processErrorNotification(HttpServletRequest request, RaptorException e) {
+ //RaptorAdapter.processErrorNotification(request, e);
+} // processErrorNotification
+
+ public String getErrorPageWMenu() {
+ return errorPageWMenu;
+ }
+
+ public String getExcelTemplatePath() {
+ return nvls(raptorAppProperties.getProperty("excel_template_path"), "");
+ }
+ /**
+ * @return the encryptedSMTPServer
+ */
+ public String getEncryptedSMTPServer() {
+ return encryptedSMTPServer;
+ }
+
+ public String getFolderPathAdj(){
+ return nvls(raptorAppProperties.getProperty("folder_path_adj"), "");
+ }
+
+} // AppUtils
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion;
+
+import java.sql.*;
+import java.util.*;
+
+import javax.servlet.*;
+
+import org.onap.portalsdk.analytics.config.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.system.fusion.adapter.FusionAdapter;
+import org.onap.portalsdk.analytics.system.fusion.adapter.RaptorAdapter;
+import org.onap.portalsdk.analytics.system.fusion.adapter.SpringContext;
+import org.onap.portalsdk.analytics.util.*;
+import org.springframework.beans.factory.annotation.Autowired;
+
+
+
+public class DbUtils implements IDbUtils {
+
+ @Autowired
+ public RaptorAdapter raptorAdapter;
+ @Autowired
+ public FusionAdapter fusionAdapter;
+
+ public DbUtils() {}
+
+ public void initializeDbUtils(ServletContext servletContext) {
+ raptorAdapter = (RaptorAdapter)SpringContext.getApplicationContext().getBean("raptorAdapter");
+ } // initializeDbUtils
+
+ public Connection getConnection() {
+ return raptorAdapter.getConnection();
+ } // getConnection
+
+ public void clearConnection(Connection con) {
+ raptorAdapter.releaseConnection(con);
+ } // clearConnection
+
+ public RaptorAdapter getRaptorAdapter() {
+ return raptorAdapter;
+ }
+
+ public void setRaptorAdapter(RaptorAdapter raptorAdapter) {
+ this.raptorAdapter = raptorAdapter;
+ }
+
+ public FusionAdapter getFusionAdapter() {
+ return fusionAdapter;
+ }
+
+ public void setFusionAdapter(FusionAdapter fusionAdapter) {
+ this.fusionAdapter = fusionAdapter;
+ }
+
+
+
+
+
+} // DbUtils
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import javax.servlet.ServletContext;
+
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.system.RDbUtils;
+import org.onap.portalsdk.analytics.system.fusion.adapter.RaptorAdapter;
+import org.onap.portalsdk.analytics.system.fusion.adapter.SpringContext;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.Log;
+import org.springframework.beans.factory.annotation.Autowired;
+
+
+
+public class RemoteDbUtils implements RDbUtils{
+
+ private RaptorAdapter raptorAdapter;
+
+
+ public void initializeDbUtils(ServletContext servletContext) {
+ raptorAdapter = (RaptorAdapter)SpringContext.getApplicationContext().getBean("raptorAdapter");
+ } // initializeDbUtils
+
+
+ public Connection getRemoteConnection(String dbKey) {
+ return raptorAdapter.getConnection(dbKey);
+ }
+
+ public void clearConnection(Connection conn) {
+ raptorAdapter.releaseConnection(conn);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.adapter;
+
+import java.util.*;
+
+public class AdapterSessionFactoryContainer {
+
+ private LinkedHashMap sessionFactories;
+
+ public AdapterSessionFactoryContainer() {
+ }
+
+ public LinkedHashMap getSessionFactories() {
+ return sessionFactories;
+ }
+
+ public void setSessionFactories(LinkedHashMap sessionFactories) {
+ this.sessionFactories = sessionFactories;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.adapter;
+
+
+import java.io.Serializable;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.TimeZone;
+
+import org.onap.portalsdk.core.FusionObject;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.AppUtils;
+
+
+public class DateUtils implements Serializable, FusionObject{
+
+ public static final String US_PACIFIC = "US/Pacific";
+ public static final String US_MOUNTAIN = "US/Mountain";
+ public static final String US_CENTRAL = "US/Central";
+ public static final String US_EASTERN = "US/Eastern";
+ public static final String US_HAWAII = "US/Hawaii";
+ public static final String US_ALASKA = "US/Alaska";
+
+ //Arizona State has Mountain Time with no Daylight Savings
+ public static final String US_ARIZONA = "America/Phoenix";
+
+ private static final String DB_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
+ private static final String GET_CURRENT_DATE = "getCurrentDate";
+
+ private static DataAccessService dataAccessService;
+
+ public static DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ /**
+ * Parses a date value with given pattern,
+ * to return a Date Object
+ *
+ * @param dateValue
+ * @param inPattern
+ * @return Date Object
+ * @throws Exception
+ *
+ */
+ public static Date parseDate(String dateValue,String inPattern) throws Exception{
+ return parseDate(dateValue,inPattern,null);
+ }
+
+ /**
+ * Parses a date value with the given pattern for the specific TimeZone,
+ * to return a Date Object
+ *
+ * @param dateValue
+ * @param inPattern
+ * @param currentTimeZone
+ * @return Date Object
+ * @throws Exception
+ *
+ */
+ public static Date parseDate(String dateValue,String inPattern,
+ String currentTimeZone) throws Exception{
+ DateFormat df = new SimpleDateFormat(inPattern);
+ if(currentTimeZone !=null && !(currentTimeZone.trim().equals(""))){
+ df.setTimeZone(TimeZone.getTimeZone(currentTimeZone));
+ }
+ Date date = df.parse(dateValue);
+ return date;
+ }
+
+ /**
+ * Parses a date value with the given pattern for the specific User(in User TimeZone),
+ * to return a Date Object
+ *
+ * @param dateValue
+ * @param inPattern
+ * @param userId
+ * @return Date Object
+ * @throws Exception
+ *
+ */
+ public static Date parseUserDate(String dateValue, String inPattern, Long userId) throws Exception{
+ User user = (User)getDataAccessService().getDomainObject(User.class, userId, null);
+
+ String userTimeZone = null;
+ Long timezoneId = user.getTimeZoneId();
+
+ if (timezoneId != null) {
+ userTimeZone = AppUtils.getLookupValueByLabel(timezoneId.toString(), "fn_lu_timezone", "timezone_id", "timezone_value");
+ }
+
+ return parseDate(dateValue,inPattern,userTimeZone);
+ }
+
+ /**
+ * Formats a given date object to the desired pattern
+ *
+ * @param date
+ * @param outPattern
+ * @return Formatted date value
+ * @throws Exception
+ */
+ public static String formatDate(Date date,String outPattern)throws Exception{
+ return formatDate(date,outPattern,null);
+ }
+
+ /**
+ * Formats a date value with the given pattern into a date value with the desired pattern
+ *
+ * @param dateValue
+ * @param inPattern
+ * @param outPattern
+ * @return Formatted date value
+ * @throws Exception
+ *
+ */
+ public static String formatDate(String dateValue,String inPattern,
+ String outPattern) throws Exception{
+ return formatDate(dateValue,inPattern,null,outPattern,null);
+ }
+
+ /**
+ * Formats a given date object to the desired pattern for the TimeZone provided
+ * @param date
+ * @param outPattern
+ * @param requiredTimeZone
+ * @return Formatted date value
+ * @throws Exception
+ */
+ public static String formatDate(Date date,String outPattern,
+ String requiredTimeZone) throws Exception{
+ DateFormat df = new SimpleDateFormat(outPattern);
+ if(requiredTimeZone != null && !requiredTimeZone.trim().equals("")){
+ df.setTimeZone(TimeZone.getTimeZone(requiredTimeZone));
+ }
+ return df.format(date);
+ }
+
+ /**
+ * Formats a date value with the given pattern
+ * into a date value with the desired pattern for the TimeZone provided
+ *
+ * @param dateValue
+ * @param inPattern
+ * @param outPattern
+ * @param requiredTimeZone
+ * @return Formatted date value
+ * @throws Exception
+ *
+ */
+ public static String formatDate(String dateValue,String inPattern,
+ String outPattern,String requiredTimeZone) throws Exception{
+ return formatDate(dateValue,inPattern,null,outPattern,requiredTimeZone);
+ }
+
+ /**
+ * Formats a date value with the given pattern for a specific TimeZone,
+ * into a date value with the desired pattern for the TimeZone provided
+ *
+ * @param dateValue
+ * @param inPattern
+ * @param currentTimeZone
+ * @param outPattern
+ * @param requiredTimeZone
+ * @return Formatted date value
+ * @throws Exception
+ *
+ */
+ public static String formatDate(String dateValue,String inPattern,String currentTimeZone,
+ String outPattern,String requiredTimeZone) throws Exception{
+ Date date = parseDate(dateValue,inPattern,currentTimeZone);
+ return formatDate(date,outPattern,requiredTimeZone);
+ }
+
+ /**
+ * Formats a date value with the given pattern, for a specific User(in User TimeZone),
+ * into a date value with the desired pattern for the TimeZone provided
+ *
+ * @param dateValue
+ * @param inPattern
+ * @param userId
+ * @param outPattern
+ * @param requiredTimeZone
+ * @return Formatted date value
+ * @throws Exception
+ *
+ */
+ public static String formatUserDate(String dateValue,String inPattern, Long userId,String outPattern,String requiredTimeZone) throws Exception{
+ User user = (User)getDataAccessService().getDomainObject(User.class, userId, null);
+
+ String userTimeZone = null;
+ Long timezoneId = user.getTimeZoneId();
+
+ if (timezoneId != null) {
+ userTimeZone = AppUtils.getLookupValueByLabel(timezoneId.toString(), "fn_lu_timezone", "timezone_id", "timezone_value");
+ }
+
+ return formatDate(dateValue,inPattern,userTimeZone,outPattern,requiredTimeZone);
+ }
+
+ /**
+ * Formats a date value with a given pattern for a specific User(User TimeZone),
+ * into a date value with the desired pattern for Database TimeZone
+ *
+ * @param dateValue
+ * @param inPattern
+ * @param userId
+ * @param outPattern
+ * @return Formatted date value
+ * @throws Exception
+ *
+ */
+ public static String formatUserDateForDBTimeZone(String dateValue,String inPattern, Long userId,String outPattern) throws Exception{
+ User user = (User)getDataAccessService().getDomainObject(User.class, userId, null);
+
+ String userTimeZone = null;
+ Long timezoneId = user.getTimeZoneId();
+
+ /*if (timezoneId != null) {
+ userTimeZone = AppUtils.getLookupValueByLabel(timezoneId.toString(), "fn_lu_timezone", "timezone_id", "timezone_value");
+ }*/
+
+ String dbTimeZone = SystemProperties.getProperty(SystemProperties.DATABASE_TIME_ZONE);
+
+ return formatDate(dateValue,inPattern,userTimeZone,outPattern,dbTimeZone);
+ }
+
+ /**
+ * Get the current database Date/Time
+ * @return Date object
+ */
+ public static Date getCurrentDBDate()throws Exception{
+ String dbTimeZone = SystemProperties.getProperty(SystemProperties.DATABASE_TIME_ZONE);
+ List results = (List)getDataAccessService().executeNamedQuery(GET_CURRENT_DATE, null, null);
+ return parseDate(((Object[])results.get(0))[0]+" "+((Object[])results.get(0))[1],DB_DATE_FORMAT,dbTimeZone);
+ }
+
+ /**
+ * Get the current date value formatted for the User's TimeZone in the desired pattern
+ *
+ * @param outPattern
+ * @param userId
+ * @return Date value
+ * @throws Exception
+ */
+ public static String getCurrentDBDateForUser(String outPattern,Long userId)throws Exception{
+ User user = (User)getDataAccessService().getDomainObject(User.class, userId, null);
+
+ String userTimeZone = null;
+ Long timezoneId = user.getTimeZoneId();
+
+ /*if (timezoneId != null) {
+ userTimeZone = AppUtils.getLookupValueByLabel(timezoneId.toString(), "fn_lu_timezone", "timezone_id", "timezone_value");
+ }*/
+
+ Date dbDate = getCurrentDBDate();
+
+ return formatDate(dbDate,outPattern,userTimeZone);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.adapter;
+
+import java.sql.*;
+import java.util.*;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.servlet.*;
+
+import com.mchange.v2.c3p0.ComboPooledDataSource;
+
+import org.hibernate.SessionFactory;
+import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
+import org.hibernate.engine.spi.SessionFactoryImplementor;
+import org.hibernate.engine.spi.SessionImplementor;
+import org.onap.portalsdk.core.FusionObject;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+
+public class FusionAdapter implements FusionObject {
+
+ public static final String LOCAL_SESSION_FACTORY_KEY = "local";
+
+
+ private ComboPooledDataSource dataSource;
+ private Map<String,ComboPooledDataSource> dataSourceMap;
+
+ //private SessionFactory sessionFactory;
+ private ServletContext servletContext;
+
+ public FusionAdapter() {
+ }
+
+
+ public ServletContext getServletContext() {
+ return servletContext;
+ }
+
+ public void setServletContext(ServletContext servletContext) {
+ this.servletContext = servletContext;
+ }
+
+ /** Gets connection to the database **/
+ public Connection getConnection() {
+ Connection connection = null;
+ try {
+ connection = getDataSource().getConnection();
+ } catch(Exception ex) {
+ ex.printStackTrace();
+ }
+ return connection;
+ }
+
+
+ /** Gets connection to the database indicated via the session factory key **/
+ public synchronized Connection getConnection(String schemaId) {
+ Connection connection = null;
+ try {
+ connection = getDataSourceMap().get(schemaId).getConnection();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return connection;
+ }
+
+
+ /** Releases connection to the database **/
+ public void releaseConnection(Connection conn) {
+ try {
+ conn.close();
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ public ComboPooledDataSource getDataSource() {
+ return dataSource;
+ }
+
+
+ @Autowired
+ public void setDataSource(ComboPooledDataSource dataSource) {
+ this.dataSource = dataSource;
+ }
+
+ public Map<String,ComboPooledDataSource> getDataSourceMap() {
+ if(dataSourceMap==null)
+ dataSourceMap = (Map<String,ComboPooledDataSource>)SpringContext.getApplicationContext().getBean("dataSourceMap");
+
+ return dataSourceMap;
+ }
+
+ public void setdataSourceMap(Map<String,ComboPooledDataSource> dataSourceMap) {
+ this.dataSourceMap = dataSourceMap;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.adapter;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.onap.portalsdk.core.domain.support.DomainVo;
+
+/**
+ * <p>IdName.java</p>
+ * <p>Represents a id/name data object.</p>
+*/
+@Entity
+public class IdName extends DomainVo {
+
+ private String name;
+ private Long id;
+
+ public IdName() {}
+
+ @Id
+ @GeneratedValue
+ @Column(name = "ID", unique = true, nullable = false)
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int compareTo(Object obj){
+ String c1 = getName();
+ String c2 = ((IdName)obj).getName();
+
+ return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.adapter;
+
+
+public class Item {
+ private String _id;
+ private String _name;
+
+ public Item() {
+ }
+
+ public Item(String id, String name) {
+ this._id = id;
+ this._name = 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;
+ }
+
+ public String toString() {
+ return _name;
+ }
+}
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.adapter;
+
+
+import java.io.*;
+
+import org.onap.portalsdk.core.domain.FusionVo;
+import org.onap.portalsdk.core.domain.support.NameValueId;
+
+
+
+public class Lookup extends FusionVo implements Serializable {
+
+ private NameValueId nameValueId = new NameValueId();
+
+ public Lookup() {}
+
+ public Lookup(String label, String value) {
+ this();
+ setLabel(label);
+ setValue(value);
+ }
+
+ public String getValue() {
+ return getNameValueId().getVal();
+ }
+
+ public String getLabel() {
+ return getNameValueId().getLab();
+ }
+
+ public void setValue(String value) {
+ getNameValueId().setVal(value);
+ }
+
+ public void setLabel(String label) {
+ getNameValueId().setLab(label);
+ }
+
+ public NameValueId getNameValueId() {
+ return nameValueId;
+ }
+
+ public void setNameValueId(NameValueId nameValueId) {
+ this.nameValueId = nameValueId;
+ }
+
+ // required by ZK for to set the selectedItems of Listboxes (used heavily for <select>-style drop-downs)
+ public int hashCode() {
+ int hash = getValue().hashCode();
+ hash = hash + getLabel().hashCode();
+
+ return hash;
+ }
+
+ public boolean equals( Object obj ) {
+ boolean equivalent = false;
+
+ Lookup lookup = (Lookup)obj;
+ if( lookup.getValue().equals(getValue()) && lookup.getLabel().equals(getLabel())) {
+ equivalent = true;
+ }
+
+ return equivalent;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.adapter;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.core.domain.Menu;
+import org.onap.portalsdk.core.domain.MenuData;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.RoleFunction;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+@Service("raptorAdapter")
+public class RaptorAdapter extends FusionAdapter {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RaptorAdapter.class);
+
+ @Autowired
+ private static DataAccessService dataAccessService;
+
+ public static final int RAPTOR_USER_ID = 20000; // RAPTOR system user id (for auditing purposes)
+ public static final String RAPTOR_CONTROLLER_CLASSNAME = "org.onap.portalsdk.analytics.controller.Controller";
+ public static final String KEY_USER_ROLES_CACHE = "userRoles";
+
+ public void initializeRaptor() {
+ org.onap.portalsdk.analytics.config.ConfigLoader.setConfigFilesPath(SystemProperties.getProperty(SystemProperties.RAPTOR_CONFIG_FILE_PATH));
+ org.onap.portalsdk.analytics.system.Globals.initializeSystem(getServletContext());
+ }
+
+
+ /** Returns ID of the user currently logged in */
+ public static String getUserID(HttpServletRequest request) {
+ return String.valueOf(UserUtils.getUserId(request));
+ //return null;
+ }
+
+ public static String getUserID(String user_id) {
+ return user_id;
+ }
+
+
+ public static String getUserBackdoorLoginId(HttpServletRequest request) {
+ if(AppUtils.getRequestNvlValue(request, "login_id").length()>0) return AppUtils.getRequestNvlValue(request, "login_id");
+ return String.valueOf(UserUtils.getUserSession(request).getLoginId());
+ }
+
+ public static String getUserBackdoorLoginId(String user_id) {
+ return getUserLoginId(user_id);
+ }
+
+ /** Obtains user name by ID */
+ public static String getUserName(String userId) {
+ Map<String, Long> params = new HashMap<String, Long>();
+ params.put("user_id", new Long(userId));
+
+ List list = getDataAccessService().executeNamedQuery("getUserNameById", params, null);
+
+ String firstName = "";
+ String lastName = "";
+
+ if (list != null) {
+ if (!list.isEmpty()) {
+ Object[] user = (Object[]) list.get(0);
+ firstName = (String) user[0]; // firstName scalar
+ lastName = (String) user[1]; // lastName scalar
+ }
+ }
+
+ return lastName + ", " + firstName;
+ }
+
+ public static String getUserName(HttpServletRequest request) {
+ User user = UserUtils.getUserSession(request);
+ return user.getLastName() + ", " + user.getFirstName();
+ }
+
+ public static String getUserEmail(String userId) {
+ Map<String, Long> params = new HashMap<String, Long>();
+ params.put("user_id", new Long(userId));
+ List list = getDataAccessService().executeNamedQuery("getUserEmail", params, null);
+ String email = "";
+ if (list != null && !list.isEmpty())
+ email = (String) list.get(0);
+ return email;
+ }
+
+ public static String getUserEmail(HttpServletRequest request) {
+ User user = UserUtils.getUserSession(request);
+ return user.getEmail();
+ }
+
+ public static String getUserLoginId(String userId) {
+
+ String loginId = "";
+ try{
+ List list = getDataAccessService().getList(User.class, " where user_id = " + userId, null, null);
+ if (list != null) {
+ if (!list.isEmpty()) {
+ User user = (User)list.get(0);
+ loginId = user.getLoginId(); // firstName scalar
+ }
+ }
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.debugLogger, ("error while getting login id : Exception" + e.getMessage()));
+ }
+ return loginId;
+ }
+
+
+ public static String getUserLoginId(HttpServletRequest request) {
+ User user = UserUtils.getUserSession(request);
+ return user.getLoginId();
+ }
+
+ /** Obtains list of all users (in IdNameValue objects) */
+ public static Map<Long, String> getAllUsers(String customizedQuery, String param, boolean isAdmin) {
+ List users = null;
+ Map<Long, String> map = new LinkedHashMap<Long, String>();
+
+ if(customizedQuery.length()>0 && !isAdmin) {
+
+ users = getDataAccessService().executeSQLQuery(customizedQuery, IdName.class, null);
+
+ if (users != null) {
+ Iterator i = users.iterator();
+ while (i.hasNext()) {
+ IdName item = (IdName)i.next();
+ map.put(item.getId(), item.getName());
+ }
+ }
+
+ } else {
+ users = getDataAccessService().executeNamedQuery("getAllUsers", null, null);
+ if (users != null) {
+ Iterator i = users.iterator();
+ while (i.hasNext()) {
+ Object[] user = (Object[])i.next();
+ Long id = (Long)user[0]; // id scalar
+ String firstName = (String)user[1]; // firstName scalar
+ String lastName = (String)user[2]; // lastName scalar
+ map.put(id, lastName + ", " + firstName);
+ }
+ }
+ }
+ return map;
+ }
+
+ /** Obtains role name by ID */
+ public static String getRoleName(String roleId) {
+ Map<String, Long> params = new HashMap<String, Long>();
+ params.put("role_id", new Long(roleId));
+
+ List list = getDataAccessService().executeNamedQuery("getRoleNameById", params, null);
+
+ String roleName = "";
+
+ if (list != null) {
+ if (!list.isEmpty()) {
+ roleName = (String) list.get(0); // name scalar
+ }
+ }
+
+ return roleName;
+ }
+
+ /** Obtains list of all roles (in IdNameValue objects) */
+ public static Map<Long, String> getAllRolesUsingCustomizedQuery(String customizedQuery, String param, boolean isAdmin) {
+ List roles = null;
+
+ Map<Long, String> map = new LinkedHashMap<Long, String>();
+
+ if(customizedQuery.length()>0 && !isAdmin) {
+
+ roles = getDataAccessService().executeSQLQuery(customizedQuery, IdName.class, null);
+
+ if (roles != null) {
+ Iterator i = roles.iterator();
+ while (i.hasNext()) {
+ IdName item = (IdName)i.next();
+ map.put(item.getId(), item.getName());
+ }
+ }
+ } else {
+
+ roles = getDataAccessService().executeNamedQuery("getAllRoles", null, null);
+
+ if (roles != null) {
+ Iterator i = roles.iterator();
+ while (i.hasNext()) {
+ Object[] role = (Object[])i.next();
+ Long id = (Long)role[0]; // id scalar
+ String name = (String)role[1]; // firstName scalar
+ map.put(id, name);
+ }
+ }
+ }
+
+ return map;
+ }
+
+ public static Set getUserRoles(HttpServletRequest request) {
+ return UserUtils.getRoles(request).keySet();
+ }
+
+ public static Set getUserRoles(String userId) {
+ Set userRoles = new HashSet<Long>();
+// Map usersRolesMap = new LinkedHashMap<Long, Set>();
+// Map<String, Long> params = new HashMap<String, Long>();
+//
+// params.put("user_id", new Long(userId));
+//
+// List usersRolesList = getDataAccessService().executeNamedQuery("getAllUsersRoles", params, null);
+// Iterator i = usersRolesList.iterator();
+// while (i.hasNext()) {
+// Object[] userRole = (Object[]) i.next();
+//
+// Long roleId = (Long) userRole[1]; // role id scalar
+// userRoles.add(roleId);
+//
+// }
+ userRoles = getActiveUsersRoleIds(new Long(userId));
+
+
+ return userRoles;
+ }
+
+ /** this is used to get role for the current user. **/
+ public static synchronized boolean isCurrentUserInRole(HttpServletRequest request, String roleId) {
+ HttpSession session = request.getSession(false);
+ if(session!=null && session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME))!=null)
+ return UserUtils.hasRole(request, roleId);
+ else
+ return false;
+ }
+
+ /** Obtains menu label by ID */
+ public static String getMenuLabel(String menuId) {
+ return ((Menu) getDataAccessService().getDomainObject(MenuData.class, new Long(menuId), null)).getLabel();
+ }
+
+ public static String formatUserDateForDBTimeZone(String dateValue,String inPattern,
+ Long userId, String outPattern)throws Exception{
+ return DateUtils.formatUserDateForDBTimeZone(dateValue,inPattern,userId,outPattern);
+ }
+
+ public static String getCurrentDBDateForUser(String inPattern,Long userId)throws Exception{
+ return DateUtils.getCurrentDBDateForUser(inPattern, userId);
+ }
+
+ public static Set<Long> getActiveUsersRoleIds(Long userId) {
+ Set<Role> allActiveUserRoles = getActiveUserRoles(userId);
+ Iterator<Role> allActiveUserRolesIterator = allActiveUserRoles.iterator();
+ Set<Long> allActiveUserRoleIds = new TreeSet<Long>();
+ while(allActiveUserRolesIterator.hasNext()){
+ Role role = allActiveUserRolesIterator.next();
+ allActiveUserRoleIds.add(role.getId());
+ }
+
+ return allActiveUserRoleIds;
+ }
+
+ public static Set<Long> getActiveUserRoleIds(Long userId) {
+ Set<Role> allActiveUserRoles = getActiveUserRoles(userId);
+ Iterator<Role> allActiveUserRolesIterator = allActiveUserRoles.iterator();
+ Set<Long> allActiveUserRoleIds = new TreeSet<Long>();
+ while(allActiveUserRolesIterator.hasNext()){
+ Role role = allActiveUserRolesIterator.next();
+ allActiveUserRoleIds.add(role.getId());
+ }
+
+ return allActiveUserRoleIds;
+ }
+
+ public static Set<RoleFunction> getActiveRoleFunctions(Long userId) {
+ Set<Role> allActiveUserRoles = getActiveUserRoles(userId);
+ Iterator<Role> allActiveUserRolesIterator = allActiveUserRoles.iterator();
+ Set<RoleFunction> allActiveRoleFunctions = new TreeSet<RoleFunction>();
+ while(allActiveUserRolesIterator.hasNext()){
+ Role role = allActiveUserRolesIterator.next();
+ allActiveRoleFunctions.addAll(role.getRoleFunctions());
+ }
+
+ return allActiveRoleFunctions;
+ }
+
+ public static Set<Role> getActiveUserRoles(Long userId) {
+ User user = (User)getDataAccessService().getDomainObject(User.class,userId,null);
+ Set<Role> allActiveUserRoles = new TreeSet<Role>();
+ allActiveUserRoles.addAll(user.getRoles());
+ Iterator<Role> userRolesIterator = user.getRoles().iterator();
+ while(userRolesIterator.hasNext()){
+ getAllChildRoles( userRolesIterator.next(),allActiveUserRoles);
+ }
+
+ Iterator<Role> allActiveUserRolesIterator = allActiveUserRoles.iterator();
+ while(allActiveUserRolesIterator.hasNext()){
+ Role role = allActiveUserRolesIterator.next();
+ if(!role.getActive()){
+ allActiveUserRolesIterator.remove();
+ }
+ }
+
+ return allActiveUserRoles;
+ }
+
+ public static Set<Role> getAllChildRoles(Role role, Set<Role> allchildRoles) {
+ Set<Role> childRoles = role.getChildRoles();
+ allchildRoles.addAll(childRoles);
+ Iterator<Role> childRolesIterator = childRoles.iterator();
+ while (childRolesIterator.hasNext()) {
+ getAllChildRoles(childRolesIterator.next(),allchildRoles);
+ }
+ return allchildRoles;
+ }
+
+
+ public static DataAccessService getDataAccessService() {
+ return org.onap.portalsdk.core.web.support.AppUtils.getDataAccessService();
+ }
+
+
+ public static void setDataAccessService(DataAccessService dataAccessService) {
+ dataAccessService = dataAccessService;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.adapter;
+
+import org.springframework.beans.BeansException;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.stereotype.Component;
+
+@Component("springContext")
+public class SpringContext implements ApplicationContextAware {
+ private static ApplicationContext context;
+
+ public void setApplicationContext(ApplicationContext context) throws BeansException {
+ this.context = context;
+ }
+ public static ApplicationContext getApplicationContext() {
+ return context;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.controller;
+/**
+ * Raptor Blob Extract Servlet
+ *
+ */
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.sql.Blob;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.springframework.web.servlet.ModelAndView;;
+
+
+public class FileServletController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FileServletController.class);
+
+ private DataAccessService dataAccessService;
+
+ public ModelAndView handleRequestInternal(HttpServletRequest request,
+ HttpServletResponse response) throws Exception {
+ logger.debug(EELFLoggerDelegate.debugLogger, ("FileServletController:: f=" + request.getParameter("f")));
+
+ String fname = request.getParameter("f");
+
+ try {
+ Map params = new HashMap();
+ params.put("fname", fname);
+
+ logger.debug(EELFLoggerDelegate.debugLogger, ("executing query: select file_blob from cr_report_file_history where file_name = :"
+ + fname));
+
+ List<Object> fileFromDB = (List<Object>) getDataAccessService().executeNamedQuery("getFileWithName", params, null);
+
+ byte[] allBytesInBlob = null;
+
+ if (fileFromDB != null && fileFromDB.size() > 0) {
+
+ logger.debug(EELFLoggerDelegate.debugLogger, ("reading file blob from DB..."));
+ try {
+
+ /*for weblogic setup
+ * if(Globals.isWeblogicServer()) {
+ weblogic.jdbc.vendor.oracle.OracleThinBlob aBlob = (weblogic.jdbc.vendor.oracle.OracleThinBlob) ((org.hibernate.lob.SerializableBlob) fileFromDB
+ .get(0)).getWrappedBlob();
+ InputStream inBlob = ((java.sql.Blob) aBlob).getBinaryStream();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ byte[] buf = new byte[1024];
+ int n = 0;
+ while ((n=inBlob.read(buf))>=0) {
+ baos.write(buf, 0, n);
+ }
+ inBlob.close();
+ allBytesInBlob = baos.toByteArray();
+ } else { */
+ /* works in Hinernate3 [ oracle.sql.BLOB aBlob = (oracle.sql.BLOB) ((org.hibernate.lob.SerializableBlob) fileFromDB
+ .get(0)).getWrappedBlob();
+ allBytesInBlob = aBlob.getBytes(1, (int) aBlob.length()); ] */
+ // }
+
+ Object fileFromDBType = fileFromDB.get(0);
+ if(fileFromDBType instanceof byte[] ) // postgres
+ allBytesInBlob = (byte[]) fileFromDB.get(0);
+ else if (fileFromDBType instanceof Blob ) // oracle
+ allBytesInBlob = ((Blob) fileFromDB.get(0)).getBytes(1, (int) ((Blob) fileFromDB.get(0)).length());
+
+
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.debugLogger, ("An exception has occurred: " + e.getMessage()));
+ throw (e);
+ }
+
+ } else {
+ logger.error(EELFLoggerDelegate.debugLogger, ("ERROR: No BLOB returned from DB..."));
+ throw (new Exception("ERROR: No BLOB returned from DB..."));
+ }
+
+ serveFile(response, allBytesInBlob, fname);
+ return null;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.debugLogger, ("Exception occurred..." + e.getMessage()));
+ Map<String, Object> errView = new HashMap<String, Object>();
+ errView.put("error", "The requested resource was not found.");
+ //return new ModelAndView(getExceptionView(), "model", errView);
+ return null;
+ }
+
+ }
+
+ private void serveFile(HttpServletResponse response, File inFile)
+ throws Exception {
+ OutputStream os = null;
+ InputStream is = null;
+ try {
+ response.reset();
+ is = new BufferedInputStream(new FileInputStream(inFile));
+ os = new BufferedOutputStream(response.getOutputStream());
+ response.setContentLength((int) inFile.length());
+ response.setContentType("application/octet-stream");
+ response.setHeader("Content-disposition", "attachment; filename=\""
+ + inFile.getName() + "\"");
+ copyStream(is, os);
+ os.flush();
+ } catch (Exception ex) {
+ if (os == null)
+ throw new Exception("Could not open output stream for file ");
+ if (is == null)
+ throw new Exception("Could not open input stream for file ");
+ } finally {
+ if (os != null) {
+ os.close();
+ }
+ if (is != null)
+ is.close();
+ }
+ }
+
+ private void serveFile(HttpServletResponse response, byte[] outStream,
+ String name) throws Exception {
+ OutputStream os = null;
+ InputStream is = null;
+ try {
+ response.reset();
+ response.setContentLength((int) outStream.length);
+ response.setContentType("application/octet-stream");
+ response.setHeader("Content-disposition", "attachment; filename=\""
+ + name + "\"");
+ copyStream(response, outStream);
+ } catch (Exception ex) {
+ if (os == null)
+ throw new Exception("Could not open output stream for file ");
+ if (is == null)
+ throw new Exception("Could not open input stream for file ");
+ } finally {
+ if (os != null) {
+ os.close();
+ }
+ if (is != null)
+ is.close();
+ }
+ }
+
+ private int copyStream(InputStream in, OutputStream out) throws IOException {
+ int bytes, totalBytes = 0;
+
+ byte[] b = new byte[4096];
+
+ while ((bytes = in.read(b, 0, b.length)) != -1) {
+ totalBytes += bytes;
+ out.write(b, 0, bytes);
+ }
+ return totalBytes;
+ }
+
+ private int copyStream(HttpServletResponse response, byte[] outStream)
+ throws IOException {
+
+ OutputStream os = new BufferedOutputStream(response.getOutputStream());
+ os.write(outStream);
+ os.flush();
+ return outStream.length;
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.domain;
+
+
+import java.util.*;
+
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.domain.support.DomainVo;;
+
+/**
+ * <p>CR_Report.java</p>
+ * <p>Represents a RAPTOR report data object.</p>
+ *
+ * @author Sundar Ramalingam
+ * @version 1.0
+ */
+public class CR_Report extends DomainVo {
+
+ private String title;
+ private String descr;
+ private String public_yn;
+ //private String report_xml;
+ private Date createDate;
+ private Date maintDate;
+ private String menuId;
+ private String menuApproved_YN;
+ private User ownerId;
+ private Long folderId;
+ private String dashboard_type_YN;
+ private String dashboard_yn;
+ private User createId;
+ private User maintId;
+
+/*
+ //New Buttons
+ private String copyImagePath = "/static/fusion/raptor/img/cross-small.png" ;
+ private String editImagePath = "/static/fusion/raptor/img/pencil-small.png" ;
+ private String deleteImagePath = "/static/fusion/raptor/img/DeleteCross-16x16.png" ;
+ private String scheduleImagePath = "/static/fusion/raptor/img/Calendar-16x16.png" ;
+ private String runImagePath = "/static/fusion/raptor/img/tick-small.png" ;
+
+*/
+ //private Set reportAccess = new TreeSet();
+
+ public CR_Report() {}
+
+
+
+ /**
+ * @return the title
+ */
+ public String getTitle() {
+ return title;
+ }
+
+
+
+ /**
+ * @param title the title to set
+ */
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+
+
+ /**
+ * @return the descr
+ */
+ public String getDescr() {
+ return descr;
+ }
+
+
+
+ /**
+ * @param descr the descr to set
+ */
+ public void setDescr(String descr) {
+ this.descr = descr;
+ }
+
+
+
+ /**
+ * @return the public_yn
+ */
+ public String getPublic_yn() {
+ return public_yn;
+ }
+
+
+
+ /**
+ * @param public_yn the public_yn to set
+ */
+ public void setPublic_yn(String public_yn) {
+ this.public_yn = public_yn;
+ }
+
+
+ /**
+ * @return the createDate
+ */
+ public Date getCreateDate() {
+ return createDate;
+ }
+
+
+
+ /**
+ * @param createDate the createDate to set
+ */
+ public void setCreateDate(Date createDate) {
+ this.createDate = createDate;
+ }
+
+
+ /**
+ * @return the maintDate
+ */
+ public Date getMaintDate() {
+ return maintDate;
+ }
+
+
+
+ /**
+ * @param maintDate the maintDate to set
+ */
+ public void setMaintDate(Date maintDate) {
+ this.maintDate = maintDate;
+ }
+
+
+
+ /**
+ * @return the menuId
+ */
+ public String getMenuId() {
+ return menuId;
+ }
+
+
+
+ /**
+ * @param menuId the menuId to set
+ */
+ public void setMenuId(String menuId) {
+ this.menuId = menuId;
+ }
+
+
+
+ /**
+ * @return the menuApproved_YN
+ */
+ public String getMenuApproved_YN() {
+ return menuApproved_YN;
+ }
+
+
+
+ /**
+ * @param menuApproved_YN the menuApproved_YN to set
+ */
+ public void setMenuApproved_YN(String menuApproved_YN) {
+ this.menuApproved_YN = menuApproved_YN;
+ }
+
+
+
+
+ /**
+ * @return the folderId
+ */
+ public Long getFolderId() {
+ return folderId;
+ }
+
+
+
+ /**
+ * @param folderId the folderId to set
+ */
+ public void setFolderId(Long folderId) {
+ this.folderId = folderId;
+ }
+
+
+
+ /**
+ * @return the dashboard_type_YN
+ */
+ public String getDashboard_type_YN() {
+ return dashboard_type_YN;
+ }
+
+
+
+ /**
+ * @param dashboard_type_YN the dashboard_type_YN to set
+ */
+ public void setDashboard_type_YN(String dashboard_type_YN) {
+ this.dashboard_type_YN = dashboard_type_YN;
+ }
+
+
+
+ /**
+ * @return the dashboard_yn
+ */
+ public String getDashboard_yn() {
+ return dashboard_yn;
+ }
+
+
+
+ /**
+ * @param dashboard_yn the dashboard_yn to set
+ */
+ public void setDashboard_yn(String dashboard_yn) {
+ this.dashboard_yn = dashboard_yn;
+ }
+
+
+
+ /**
+ * @return the ownerId
+ */
+ public User getOwnerId() {
+ return ownerId;
+ }
+
+
+
+ /**
+ * @param ownerId the ownerId to set
+ */
+ public void setOwnerId(User ownerId) {
+ this.ownerId = ownerId;
+ }
+
+
+
+ /**
+ * @return the createId
+ */
+ public User getCreateId() {
+ return createId;
+ }
+
+
+
+ /**
+ * @param createId the createId to set
+ */
+ public void setCreateId(User createId) {
+ this.createId = createId;
+ }
+
+
+
+ /**
+ * @return the maintId
+ */
+ public User getMaintId() {
+ return maintId;
+ }
+
+
+
+ /**
+ * @param maintId the maintId to set
+ */
+ public void setMaintId(User maintId) {
+ this.maintId = maintId;
+ }
+
+
+
+ public int compareTo(Object obj){
+ String c1 = getTitle();
+ String c2 = ((CR_Report)obj).getTitle();
+
+ return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.domain;
+
+public class QuickLink {
+
+ private String reportURL;
+ private String reportName;
+ private String reportDescr;
+ private Boolean showDescr;
+
+ public String getReportURL() {
+ return reportURL;
+ }
+
+ public void setReportURL(String reportURL) {
+ this.reportURL = reportURL;
+ }
+
+ 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 Boolean getShowDescr() {
+ return showDescr;
+ }
+
+ public void setShowDescr(Boolean showDescr) {
+ this.showDescr = showDescr;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.domain;
+
+import java.util.Date;
+
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.core.domain.support.DomainVo;;
+
+public class RaptorSearch extends DomainVo {
+
+ private Long repId;
+ private String title;
+ private String descr;
+ private String ownerName;
+ private Date createDate;
+ private String canEdit;
+ private String readOnly;
+ private String schedule;
+ // private Long countRows;
+
+ /**
+ * @return the repId
+ */
+ public Long getRepId() {
+ return repId;
+ }
+
+ /**
+ * @param repId
+ * the repId to set
+ */
+ public void setRepId(Long repId) {
+ this.repId = repId;
+ }
+
+ /**
+ * @return the title
+ */
+ public String getTitle() {
+ return title;
+ }
+
+ /**
+ * @param title
+ * the title to set
+ */
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ /**
+ * @return the descr
+ */
+ public String getDescr() {
+ return descr;
+ }
+
+ /**
+ * @param descr
+ * the descr to set
+ */
+ public void setDescr(String descr) {
+ this.descr = descr;
+ }
+
+ /**
+ * @return the createDate
+ */
+ public Date getCreateDate() {
+ return createDate;
+ }
+
+ /**
+ * @param createDate
+ * the createDate to set
+ */
+ public void setCreateDate(Date createDate) {
+ this.createDate = createDate;
+ }
+
+ /**
+ * @return the ownerName
+ */
+ public String getOwnerName() {
+ return ownerName;
+ }
+
+ /**
+ * @param ownerName
+ * the ownerName to set
+ */
+ public void setOwnerName(String ownerName) {
+ this.ownerName = ownerName;
+ }
+
+ /**
+ * @return the schedule
+ */
+ public String getSchedule() {
+ return schedule;
+ }
+
+ /**
+ * @param schedule
+ * the schedule to set
+ */
+ public void setSchedule(String schedule) {
+ this.schedule = schedule;
+ }
+
+ /**
+ * @return the canEdit
+ */
+ public String getCanEdit() {
+ return canEdit;
+ }
+
+ /**
+ * @param canEdit
+ * the canEdit to set
+ */
+ public void setCanEdit(String canEdit) {
+ this.canEdit = canEdit;
+ }
+
+ /**
+ * @return the canDelete
+ */
+ public boolean canDelete() {
+ String s = getCanEdit();
+ if (s != null && s.length() > 0 && s.equals("Y")) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * @return the canCopy
+ */
+ public boolean canCopy() {
+ String s = getReadOnly();
+ if (returnTrueOrFalse(s)) {
+ return Globals.getCanCopyOnReadOnly() ? true : returnTrueOrFalse(getCanEdit());
+ }
+ return true;
+ }
+
+ /**
+ * @return the readOnly
+ */
+ public String getReadOnly() {
+ return readOnly;
+ }
+
+ /**
+ * @param readOnly
+ * the readOnly to set
+ */
+ public void setReadOnly(String readOnly) {
+ this.readOnly = readOnly;
+ }
+
+ private boolean returnTrueOrFalse(String s) {
+ if (s != null && s.length() > 0 && s.equals("Y")) {
+ return true;
+ }
+ return false;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.domain;
+
+import java.util.Date;
+
+public class ReportInfo {
+
+ private Long repId;
+ private String title;
+ private String createUser;
+ private String ownerName;
+ private Date createDate;
+ private Long lastAccessed = -1L;
+ private Long lastWeekAccess;
+ private Long lastMonthAccess;
+ private Long lastYearAccess;
+ private Long userAccessCount;
+ /**
+ * @return the repId
+ */
+ public Long getRepId() {
+ return repId;
+ }
+ /**
+ * @param repId the repId to set
+ */
+ public void setRepId(Long repId) {
+ this.repId = repId;
+ }
+ /**
+ * @return the title
+ */
+ public String getTitle() {
+ return title;
+ }
+ /**
+ * @param title the title to set
+ */
+ public void setTitle(String title) {
+ this.title = title;
+ }
+ /**
+ * @return the createUser
+ */
+ public String getCreateUser() {
+ return createUser;
+ }
+ /**
+ * @param createUser the createUser to set
+ */
+ public void setCreateUser(String createUser) {
+ this.createUser = createUser;
+ }
+ /**
+ * @return the ownerName
+ */
+ public String getOwnerName() {
+ return ownerName;
+ }
+ /**
+ * @param ownerName the ownerName to set
+ */
+ public void setOwnerName(String ownerName) {
+ this.ownerName = ownerName;
+ }
+ /**
+ * @return the createDate
+ */
+ public Date getCreateDate() {
+ return createDate;
+ }
+ /**
+ * @param createDate the createDate to set
+ */
+ public void setCreateDate(Date createDate) {
+ this.createDate = createDate;
+ }
+ /**
+ * @return the lastAccessed
+ */
+ public Long getLastAccessed() {
+ return lastAccessed;
+ }
+ /**
+ * @param lastAccessed the lastAccessed to set
+ */
+ public void setLastAccessed(Long lastAccessed) {
+ this.lastAccessed = lastAccessed;
+ }
+ /**
+ * @return the lastWeekAccess
+ */
+ public Long getLastWeekAccess() {
+ return lastWeekAccess;
+ }
+ /**
+ * @param lastWeekAccess the lastWeekAccess to set
+ */
+ public void setLastWeekAccess(Long lastWeekAccess) {
+ this.lastWeekAccess = lastWeekAccess;
+ }
+ /**
+ * @return the lastMonthAccess
+ */
+ public Long getLastMonthAccess() {
+ return lastMonthAccess;
+ }
+ /**
+ * @param lastMonthAccess the lastMonthAccess to set
+ */
+ public void setLastMonthAccess(Long lastMonthAccess) {
+ this.lastMonthAccess = lastMonthAccess;
+ }
+ /**
+ * @return the lastYearAccess
+ */
+ public Long getLastYearAccess() {
+ return lastYearAccess;
+ }
+ /**
+ * @param lastYearAccess the lastYearAccess to set
+ */
+ public void setLastYearAccess(Long lastYearAccess) {
+ this.lastYearAccess = lastYearAccess;
+ }
+ /**
+ * @return the userAccessCount
+ */
+ public Long getUserAccessCount() {
+ return userAccessCount;
+ }
+ /**
+ * @param userAccessCount the userAccessCount to set
+ */
+ public void setUserAccessCount(Long userAccessCount) {
+ this.userAccessCount = userAccessCount;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.service;
+
+import java.util.*;
+
+
+
+public interface RaptorService {
+ public void deleteReport(Long reportId);
+ public List getReportInfo(Map params);
+ public int getTotalSize();
+ public int executeCountQuery(Class entity, String query, Map params, String whereClause);
+ public List executeGridQuery(String query, Map params, Integer fromIndex, Integer toIndex);
+ public List executeGridQueryOrderByWithLimit(Class entity, String query, Map params, String _orderBy, boolean _asc, Integer fromIndex, Integer toIndex);
+ public List executeGridQuery(Class entity, String query, String whereClause, Map params, Integer fromIndex, Integer toIndex);
+ public List executeGridQueryOrderByWithLimit(Class entity, String query, String whereClause, Map params, String _orderBy, boolean _asc, Integer fromIndex, Integer toIndex);
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.service;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.math.BigDecimal;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.sql.DataSource;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.onap.portalsdk.analytics.system.fusion.domain.CR_Report;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.service.support.FusionService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.context.ApplicationContext;
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
+import org.springframework.orm.hibernate3.SessionFactoryUtils;
+import org.springframework.web.multipart.MultipartFile;
+
+public class RaptorServiceImpl extends FusionService implements RaptorService {
+
+ private DataAccessService dataAccessService;
+
+ private int totalSize;
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ private ApplicationContext applicationContext;
+
+ //raptorSearchAllReportsCount
+
+ public int executeCountQuery(Class entity, String query, Map params, String whereClause) {
+ List l = getDataAccessService().executeNamedCountQuery(entity, query, whereClause, params);
+ //List l = getDataAccessService().executeNamedQuery(query, params, null);
+ int searchCount = 0;
+ if(l != null) {
+ if (!l.isEmpty()) {
+ searchCount = (((Long) l.get(0))).intValue();
+ }
+ }
+ totalSize = searchCount;
+ return totalSize;
+ }
+
+ //raptorSearchAllReports
+ public List executeGridQuery(String query, Map params, Integer fromIndex, Integer toIndex) {
+ return getDataAccessService().executeNamedQuery(query, params, fromIndex, toIndex, null);
+ }
+
+ public List executeGridQueryOrderByWithLimit(Class entity, String query, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex) {
+ return getDataAccessService().executeNamedQueryWithOrderBy(entity, query, params, _orderBy, asc, fromIndex, toIndex, null);
+ }
+
+ //with where clause
+ public List executeGridQuery(Class entity, String query, String whereClause, Map params, Integer fromIndex, Integer toIndex) {
+ return getDataAccessService().executeNamedQuery(entity, query, whereClause, params, fromIndex, toIndex, null);
+ }
+
+ public List executeGridQueryOrderByWithLimit(Class entity, String query, String whereClause, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex) {
+ return getDataAccessService().executeNamedQueryWithOrderBy(entity, query, whereClause, params, _orderBy, asc, fromIndex, toIndex, null);
+ }
+
+ /*
+ public int getUserReportsCount(Map params) {
+ List l = getDataAccessService().executeNamedQuery("raptorSearchUserReportsCount", params, null);
+ int count = 0;
+ if(l != null) {
+ if (!l.isEmpty()) {
+ Object[] result = (Object[]) l.get(0);
+ count = ((Long)result[0]).intValue();
+ }
+ }
+ totalSize = count;
+ return totalSize;
+ }
+
+ public List getUserReports(Map params, Integer fromIndex, Integer toIndex) {
+ return getDataAccessService().executeNamedQuery("raptorSearchUserReports", params, fromIndex, toIndex, null);
+ }
+
+ public int getPublicReportsCount(Map params) {
+ List l = getDataAccessService().executeNamedQuery("raptorPublicUserReportsCount", params, null);
+ int count = 0;
+ if(l != null) {
+ if (!l.isEmpty()) {
+ Object[] result = (Object[]) l.get(0);
+ count = ((Long)result[0]).intValue();
+ }
+ }
+ totalSize = count;
+ return totalSize;
+ }
+
+ public List getPublicReports(Map params, Integer fromIndex, Integer toIndex) {
+ return getDataAccessService().executeNamedQuery("raptorPublicUserReports", params, fromIndex, toIndex, null);
+ }
+
+ public int getFavReportsCount(Map params) {
+ List l = getDataAccessService().executeNamedQuery("raptorSearchFavReportsCount", params, null);
+ int count = 0;
+ if(l != null) {
+ if (!l.isEmpty()) {
+ Object[] result = (Object[]) l.get(0);
+ count = ((Long)result[0]).intValue();
+ }
+ }
+ totalSize = count;
+ return totalSize;
+ }
+
+ public List getFavReports(Map params, Integer fromIndex, Integer toIndex) {
+ return getDataAccessService().executeNamedQuery("raptorSearchFavReports", params, fromIndex, toIndex, null);
+ }
+ */
+ public int getTotalSize() {
+ return totalSize;
+ }
+
+ public void deleteReport(Long reportId) {
+ getDataAccessService().deleteDomainObject(getDataAccessService().getDomainObject(CR_Report.class, reportId, null), null);
+ }
+
+ public List getReportInfo(Map params) {
+ return getDataAccessService().executeNamedQuery("raptorInfoQuery", params, null);
+ }
+
+/* public List executeGridQueryWithOrderBy(String query, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex) {
+ query = String.format(query, _orderBy, asc ? "ASC" : "DESC", fromIndex, toIndex);
+ DataSource ds = (DataSource)getApplicationContext().getBean(searchBean.getDatasourceName());
+ NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(ds);
+ }*/
+
+ /**
+ * @return the applicationContext
+ */
+ public ApplicationContext getApplicationContext() {
+ return applicationContext;
+ }
+
+ /**
+ * @param applicationContext the applicationContext to set
+ */
+ public void setApplicationContext(ApplicationContext applicationContext) {
+ this.applicationContext = applicationContext;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.web;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.lang.reflect.Method;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.portalsdk.analytics.controller.Action;
+import org.onap.portalsdk.analytics.controller.ErrorHandler;
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
+import org.onap.portalsdk.analytics.model.runtime.ErrorJSONRuntime;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+
+@Controller
+@RequestMapping("/")
+public class RaptorController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RaptorController.class);
+
+ @RequestMapping(value = { "/report" }, method = RequestMethod.GET)
+ public ModelAndView report(HttpServletRequest request) {
+ request.getSession().setAttribute("isEmbedded", false);
+ return new ModelAndView("report");
+ }
+
+ @RequestMapping(value = { "/reportDS1" }, method = RequestMethod.GET)
+ public ModelAndView reportDS1(HttpServletRequest request) {
+ request.getSession().setAttribute("isEmbedded", false);
+ return new ModelAndView("reportDS1");
+ }
+
+ @RequestMapping(value = { "/report_embedded" }, method = RequestMethod.GET)
+ public ModelAndView reportEmbedded(HttpServletRequest request) {
+ request.getSession().setAttribute("isEmbedded", true);
+ return new ModelAndView("report_embedded");
+ }
+
+ @RequestMapping(value = { "/report_sample" }, method = RequestMethod.GET)
+ public ModelAndView reportSample(HttpServletRequest request) {
+ return new ModelAndView("report_sample");
+ }
+
+ @RequestMapping(value = { "/report_import.htm" }, method = RequestMethod.GET)
+ public ModelAndView reportImport(HttpServletRequest request) throws IOException {
+ String viewName = "report_import";
+ Action action = null;
+ String actionKey = "report.import";
+ ServletContext servletContext = request.getSession().getServletContext();
+ if (!Globals.isSystemInitialized()) {
+ Globals.initializeSystem(servletContext);
+ }
+ 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()));
+ viewName = new ErrorHandler().processFatalError(request,
+ new RaptorRuntimeException("[Controller.processRequest]Invalid raptor action [" + actionKey
+ + "]. Exception: " + e.getMessage()));
+ }
+ return new ModelAndView(viewName, "model", null);
+ }
+
+ @RequestMapping(value = { "/report_wizard.htm" }, method = { RequestMethod.POST, RequestMethod.GET })
+ public ModelAndView reportWizard(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ String viewName = "";
+ String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action"));
+ actionKey = nvl(actionKey, "report.run");
+ Action action = null;
+ ServletContext servletContext = request.getSession().getServletContext();
+ if (!Globals.isSystemInitialized()) {
+ Globals.initializeSystem(servletContext);
+ }
+ 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()));
+ viewName = (new ErrorHandler()).processFatalError(request,
+ new RaptorRuntimeException("[Controller.processRequest]Invalid raptor action [" + actionKey
+ + "]. Exception: " + e.getMessage()));
+ ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
+ errorJSONRuntime.setErrormessage(e.toString());
+ errorJSONRuntime.setStacktrace(getStackTrace(e));
+ ObjectMapper mapper = new ObjectMapper();
+ 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();
+
+ }
+ }
+
+ 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();
+ viewName = (String) handlerMethod.invoke(handler, paramValues);
+ } catch (Exception e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action ["
+ + actionKey + "]. Exception: " + e.getMessage()));
+ viewName = (new ErrorHandler()).processFatalError(request,
+ new RaptorRuntimeException(
+ "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: "
+ + e.getMessage()));
+
+ ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
+ errorJSONRuntime.setErrormessage(e.toString());
+ errorJSONRuntime.setStacktrace(getStackTrace(e));
+ ObjectMapper mapper = new ObjectMapper();
+ 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 new ModelAndView(viewName, "model", null);
+ }
+
+ private String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ private String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+ public static String getStackTrace(Throwable aThrowable) {
+ Writer result = new StringWriter();
+ PrintWriter printWriter = new PrintWriter(result);
+ aThrowable.printStackTrace(printWriter);
+ return result.toString();
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.web;
+
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalsdk.analytics.controller.Action;
+import org.onap.portalsdk.analytics.controller.ErrorHandler;
+import org.onap.portalsdk.analytics.controller.WizardSequence;
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.model.DataCache;
+import org.onap.portalsdk.analytics.model.ReportHandler;
+import org.onap.portalsdk.analytics.model.base.IdNameValue;
+import org.onap.portalsdk.analytics.model.base.ReportUserRole;
+import org.onap.portalsdk.analytics.model.definition.ReportDefinition;
+import org.onap.portalsdk.analytics.model.definition.SecurityEntry;
+import org.onap.portalsdk.analytics.model.definition.wizard.ColumnEditJSON;
+import org.onap.portalsdk.analytics.model.definition.wizard.ColumnJSON;
+import org.onap.portalsdk.analytics.model.definition.wizard.DefinitionJSON;
+import org.onap.portalsdk.analytics.model.definition.wizard.FormEditJSON;
+import org.onap.portalsdk.analytics.model.definition.wizard.IdNameBooleanJSON;
+import org.onap.portalsdk.analytics.model.definition.wizard.ImportJSON;
+import org.onap.portalsdk.analytics.model.definition.wizard.MessageJSON;
+import org.onap.portalsdk.analytics.model.definition.wizard.NameBooleanJSON;
+import org.onap.portalsdk.analytics.model.definition.wizard.QueryJSON;
+import org.onap.portalsdk.analytics.model.definition.wizard.QueryResultJSON;
+import org.onap.portalsdk.analytics.model.definition.wizard.RaptorResponse;
+import org.onap.portalsdk.analytics.model.definition.wizard.SearchFieldJSON;
+import org.onap.portalsdk.analytics.model.pdf.PdfReportHandler;
+import org.onap.portalsdk.analytics.model.runtime.CategoryAxisJSON;
+import org.onap.portalsdk.analytics.model.runtime.ChartJSON;
+import org.onap.portalsdk.analytics.model.runtime.ErrorJSONRuntime;
+import org.onap.portalsdk.analytics.model.runtime.FormField;
+import org.onap.portalsdk.analytics.model.runtime.RangeAxisJSON;
+import org.onap.portalsdk.analytics.model.runtime.ReportFormFields;
+import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
+import org.onap.portalsdk.analytics.system.AppUtils;
+import org.onap.portalsdk.analytics.system.ConnectionUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+import org.onap.portalsdk.analytics.util.AppConstants;
+import org.onap.portalsdk.analytics.util.DataSet;
+import org.onap.portalsdk.analytics.util.Utils;
+import org.onap.portalsdk.analytics.util.XSSFilter;
+import org.onap.portalsdk.analytics.view.ReportData;
+import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
+import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
+import org.onap.portalsdk.analytics.xmlobj.ObjectFactory;
+import org.onap.portalsdk.analytics.xmlobj.PredefinedValueList;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+
+@Controller
+@RequestMapping("/")
+public class RaptorControllerAsync extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RaptorControllerAsync.class);
+
+ private String viewName;
+
+ @RequestMapping(value = { "/raptor.htm" }, method = RequestMethod.GET)
+ public void RaptorSearch(HttpServletRequest request, HttpServletResponse response)
+ throws IOException, RaptorException {
+
+ viewName = "";
+ String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action"));
+ actionKey = nvl(actionKey, "report.run");
+
+ HttpSession session = request.getSession();
+ User user = UserUtils.getUserSession(request);
+
+ if (actionKey.equals("report.download.excel2007.session") || actionKey.equals("report.download.csv.session")
+ || actionKey.equals("report.download.excel.session")
+ || actionKey.equals("report.download.pdf.session")) {
+ if (session != null && user != null) {
+ ServletContext servletContext = request.getSession().getServletContext();
+ if (!Globals.isSystemInitialized()) {
+ Globals.initializeSystem(servletContext);
+ }
+ ReportRuntime 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");
+ }
+
+ boolean isEmbedded = false;
+ Object temp = request.getSession().getAttribute("isEmbedded");
+ if (temp != null) {
+ isEmbedded = (boolean) temp;
+ }
+ if (isEmbedded) {
+ String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
+ if (rr == null)
+ rr = (ReportRuntime) ((HashMap) request.getSession()
+ .getAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP)).get(reportID);
+ if (rd == null)
+ rd = (ReportData) ((HashMap) request.getSession()
+ .getAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP)).get(reportID);
+ } else {
+ if (rr == null)
+ rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
+ if (rd == null)
+ rd = (ReportData) request.getSession().getAttribute(AppConstants.RI_REPORT_DATA);
+ }
+ String user_id = AppUtils.getUserID(request);
+ int downloadLimit = 0;
+ if (rr != null)
+ downloadLimit = (rr.getMaxRowsInExcelDownload() > 0) ? rr.getMaxRowsInExcelDownload()
+ : Globals.getDownloadLimit();
+ if (actionKey.equals("report.csv.download"))
+ downloadLimit = Globals.getCSVDownloadLimit();
+ String sql_whole = rr.getReportDataSQL(user_id, downloadLimit, request);
+ request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sql_whole);
+ try {
+ OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());
+
+ if (actionKey.equals("report.download.pdf.session")) {
+ new PdfReportHandler().createPdfFileContent(request, response, 3);
+ } else if (actionKey.equals("report.download.csv.session")) {
+ (new ReportHandler()).createCSVFileContent(out, rd, rr, request, response);
+ } else if (actionKey.equals("report.download.excel.session")) {
+ new ReportHandler().createExcelFileContent(out, rd, rr, request, response, user_id, 3); // 3
+ // whole
+ } else {
+
+ new ReportHandler().createExcel2007FileContent(out, rd, rr, request, response, user_id, 3); // 3
+ // whole
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [" + actionKey + "].", e);
+ }
+ } else {
+ response.sendRedirect("login.htm");
+ }
+ } else {
+ if (session != null && user != null) {
+ Action action = null;
+ ServletContext servletContext = request.getSession().getServletContext();
+ if (!Globals.isSystemInitialized()) {
+ Globals.initializeSystem(servletContext);
+ }
+ try {
+ action = Globals.getRaptorActionMapping().getAction(actionKey);
+ if (action == null)
+ throw new RaptorRuntimeException("Action not found");
+ } catch (RaptorException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [" + actionKey + "].", e);
+
+ viewName = (new ErrorHandler()).processFatalErrorJSON(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();
+ ;
+
+ viewName = (String) handlerMethod.invoke(handler, paramValues);
+ if (!actionKey.equals("chart.run"))
+ response.setContentType("application/json");
+ else
+ response.setContentType("text/html");
+
+ } catch (ClassNotFoundException e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action ["
+ + actionKey + "]. ClassNotFoundException: " + e.getMessage()));
+ viewName = (new ErrorHandler()).processFatalErrorJSON(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()));
+ viewName = (new ErrorHandler()).processFatalErrorJSON(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()));
+ viewName = (new ErrorHandler()).processFatalErrorJSON(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()));
+ viewName = (new ErrorHandler()).processFatalErrorJSON(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()));
+ viewName = (new ErrorHandler()).processFatalErrorJSON(request,
+ new RaptorRuntimeException(
+ "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: "
+ + e.getMessage()));
+ } finally {
+ PrintWriter out = response.getWriter();
+ out.write(viewName);
+ }
+ } else {
+ PrintWriter out = response.getWriter();
+ out.write("session has timed out for user");
+ }
+
+ }
+ }
+
+ @RequestMapping(value = "/report/wizard/list_columns", method = RequestMethod.GET, produces = "application/json")
+ public @ResponseBody ArrayList<ColumnJSON> listColumns(HttpServletRequest request, HttpServletResponse response)
+ throws IOException, RaptorException {
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ List<DataColumnType> reportColumnList = rdef.getAllColumns();
+ ArrayList<ColumnJSON> listJSON = new ArrayList<ColumnJSON>();
+ ColumnJSON columnJSON = new ColumnJSON();
+
+ for (DataColumnType reportColumnType : reportColumnList) {
+ columnJSON = new ColumnJSON();
+ columnJSON.setId(reportColumnType.getColId());
+ columnJSON.setName(reportColumnType.getColName());
+ listJSON.add(columnJSON);
+ }
+ return listJSON;
+ }
+
+ @RequestMapping(value = "/report/wizard/list_drilldown_reports", method = RequestMethod.GET, produces = "application/json")
+ public @ResponseBody ArrayList<ColumnJSON> list_drilldown_reports(HttpServletRequest request,
+ HttpServletResponse response) throws IOException, RaptorException {
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ Vector<IdNameValue> publicReportIdNames = DataCache.getPublicReportIdNames();
+ Vector groupReportIdNames = DataCache.getGroupAccessibleReportIdNames(AppUtils.getUserID(request),
+ AppUtils.getUserRoles(request));
+ Vector privateReportIdNames = DataCache.getPrivateAccessibleReportIdNames(AppUtils.getUserID(request),
+ AppUtils.getUserRoles(request));
+
+ ArrayList<ColumnJSON> listJSON = new ArrayList<ColumnJSON>();
+ ColumnJSON columnJSON = new ColumnJSON();
+
+ ServletContext servletContext = request.getSession().getServletContext();
+ if (!Globals.isSystemInitialized()) {
+ Globals.initializeSystem(servletContext);
+ }
+
+ for (int i = 0; i < publicReportIdNames.size(); i++) {
+ IdNameValue reportIdName = (IdNameValue) publicReportIdNames.get(i);
+ columnJSON = new ColumnJSON();
+ columnJSON.setId(reportIdName.getId());
+ columnJSON.setName("Public Report: " + reportIdName.getName());
+ if (!rdef.getReportID().equals(reportIdName.getId()))
+ listJSON.add(columnJSON);
+ }
+
+ for (int i = 0; i < groupReportIdNames.size(); i++) {
+ IdNameValue reportIdName = (IdNameValue) groupReportIdNames.get(i);
+ columnJSON = new ColumnJSON();
+ columnJSON.setId(reportIdName.getId());
+ columnJSON.setName("Group Report: " + reportIdName.getName());
+ if (!rdef.getReportID().equals(reportIdName.getId()))
+ listJSON.add(columnJSON);
+ }
+
+ for (int i = 0; i < privateReportIdNames.size(); i++) {
+ IdNameValue reportIdName = (IdNameValue) privateReportIdNames.get(i);
+ columnJSON = new ColumnJSON();
+ columnJSON.setId(reportIdName.getId());
+ columnJSON.setName("Private Report: " + reportIdName.getName());
+ if (!rdef.getReportID().equals(reportIdName.getId()))
+ listJSON.add(columnJSON);
+ }
+
+ return listJSON;
+ }
+
+ @RequestMapping(value = "/report/wizard/list_formfields", method = RequestMethod.GET, produces = "application/json")
+ public @ResponseBody ArrayList<SearchFieldJSON> listFormFields(HttpServletRequest request,
+ HttpServletResponse response) throws IOException, RaptorException {
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ ArrayList<SearchFieldJSON> listJSON = new ArrayList<SearchFieldJSON>();
+ SearchFieldJSON fieldJSON = new SearchFieldJSON();
+ if (rdef.getFormFieldList() != null) {
+ for (Iterator iter = rdef.getFormFieldList().getFormField().iterator(); iter.hasNext();) {
+ fieldJSON = new SearchFieldJSON();
+ FormFieldType fft = (FormFieldType) iter.next();
+ String fieldId = fft.getFieldId();
+ String fieldDisplay = fft.getFieldName();
+ fieldJSON.setId(fieldId);
+ fieldJSON.setName(fieldDisplay);
+ listJSON.add(fieldJSON);
+ }
+ }
+
+ return listJSON;
+ }
+
+ @RequestMapping(value = "/report/wizard/list_child_report_col/{reportID}", method = RequestMethod.GET, produces = "application/json")
+ public @ResponseBody ArrayList<ColumnJSON> listChildReportCols(@PathVariable("reportID") String reportID,
+ HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
+ ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, reportID, false);
+
+ List<DataColumnType> reportColumnList = ddRr.getAllColumns();
+ ArrayList<ColumnJSON> listJSON = new ArrayList<ColumnJSON>();
+ ColumnJSON columnJSON = new ColumnJSON();
+
+ for (DataColumnType reportColumnType : reportColumnList) {
+ columnJSON = new ColumnJSON();
+ columnJSON.setId(reportColumnType.getColId());
+ columnJSON.setName(reportColumnType.getColName());
+ listJSON.add(columnJSON);
+ }
+ return listJSON;
+ }
+
+ @RequestMapping(value = "/report/wizard/list_child_report_ff/{reportID}", method = RequestMethod.GET, produces = "application/json")
+ public @ResponseBody ArrayList<SearchFieldJSON> listChildReportFormFields(@PathVariable("reportID") String reportID,
+ HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
+ ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, reportID, false);
+ ArrayList<SearchFieldJSON> listJSON = new ArrayList<SearchFieldJSON>();
+ SearchFieldJSON fieldJSON = new SearchFieldJSON();
+
+ ReportFormFields ddReportFormFields = ddRr.getReportFormFields();
+ if (ddReportFormFields != null) {
+ for (ddReportFormFields.resetNext(); ddReportFormFields.hasNext();) {
+ FormField ff = ddReportFormFields.getNext();
+ if (!ff.getFieldType().equals(FormField.FFT_BLANK)) {
+ fieldJSON = new SearchFieldJSON();
+ fieldJSON.setId(ff.getFieldName());
+ fieldJSON.setName(ff.getFieldDisplayName());
+ listJSON.add(fieldJSON);
+ }
+ }
+ }
+ return listJSON;
+ }
+
+ @RequestMapping(value = "report/wizard/copy_report/{reportID}", method = RequestMethod.GET, produces = "application/json")
+ public @ResponseBody MessageJSON copyReport(@PathVariable("reportID") String reportID, HttpServletRequest request,
+ HttpServletResponse response) throws IOException, RaptorException {
+ MessageJSON messageJSON = new MessageJSON();
+ try {
+
+ ReportHandler rh = new ReportHandler();
+ ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
+ rdef.setAsCopy(request);
+ request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
+ messageJSON.setMessage("Success- Report Copied.");
+ messageJSON.setAnyStacktrace(rdef.getReportID() + " is Modified and added to session and DB.");
+
+ } catch (RaptorException e) {
+ request.setAttribute("error_extra_msg", "While copying report " + reportID);
+ messageJSON.setMessage("Failed - While copying report " + reportID);
+ messageJSON.setAnyStacktrace(getStackTrace(e));
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ ("[Controller.processRequest]Invalid raptor action [copyReport]. RaptorException: "
+ + e.getMessage()));
+ return messageJSON;
+ }
+
+ return messageJSON;
+ }
+
+ @RequestMapping(value = "report/wizard/import_report", method = RequestMethod.POST, consumes = "application/json")
+ public @ResponseBody MessageJSON importReport(@RequestBody ImportJSON importJSON, HttpServletRequest request,
+ HttpServletResponse response) throws IOException, RaptorException {
+ MessageJSON messageJSON = new MessageJSON();
+ try {
+ String reportXML = importJSON.getReportXML();
+
+ 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);
+
+ messageJSON.setMessage("Success- Report imported.");
+ messageJSON.setAnyStacktrace(rdef.getReportID() + " is Modified and added to session and DB.");
+
+ } catch (RaptorException e) {
+ request.setAttribute("error_extra_msg", "Unable to parse XML. Nested error: ");
+ messageJSON.setMessage("Unable to parse XML. Nested error: ");
+ messageJSON.setAnyStacktrace(getStackTrace(e));
+
+ return messageJSON;
+ }
+
+ return messageJSON;
+
+ }
+
+ @RequestMapping(value = "report/wizard/save_formfield_tab_data", method = RequestMethod.POST)
+ public @ResponseBody MessageJSON saveFFTabWiseData(@RequestBody FormEditJSON formEditJSON,
+ HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
+ ReportDefinition rdef = null;
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+
+ MessageJSON messageJSON = new MessageJSON();
+ try {
+ if (rdef != null) {
+
+ String fieldId = formEditJSON.getFieldId();
+
+ if (rdef.getFormFieldList() != null) {
+ for (FormFieldType fft : rdef.getFormFieldList().getFormField()) {
+ if (fft.getFieldId().equals(fieldId)) {
+ fft.setFieldName(formEditJSON.getFieldName());
+ fft.setFieldType(formEditJSON.getFieldType());
+ fft.setVisible(formEditJSON.isVisible() ? "Y" : "N");
+ fft.setDefaultValue(formEditJSON.getDefaultValue());
+ fft.setFieldDefaultSQL(formEditJSON.getFieldDefaultSQL());
+ fft.setFieldSQL(formEditJSON.getFieldSQL());
+ fft.setValidationType(formEditJSON.getValidationType());
+
+ // clear predefined value
+ if (fft.getPredefinedValueList() != null) {
+ for (Iterator<String> iter = fft.getPredefinedValueList().getPredefinedValue()
+ .iterator(); iter.hasNext();)
+ iter.remove();
+ }
+
+ List<IdNameBooleanJSON> predefList = formEditJSON.getPredefinedValueList();
+ if (predefList != null && predefList.size() > 0) {
+ for (IdNameBooleanJSON item : predefList) {
+ PredefinedValueList predefinedValueList = new ObjectFactory()
+ .createPredefinedValueList();
+ fft.setPredefinedValueList(predefinedValueList);
+ fft.getPredefinedValueList().getPredefinedValue().add(item.getId());
+ }
+ }
+
+ }
+ }
+ }
+
+ persistReportDefinition(request, rdef);
+ messageJSON.setMessage("Success formfield Details of given report is saved in session.");
+ messageJSON.setAnyStacktrace(rdef.getReportID() + " is Modified and added to session and DB.");
+
+ } else {
+ messageJSON.setMessage("Report Definition is not in session");
+ messageJSON.setAnyStacktrace("Report Definition is not in session");
+
+ }
+ } catch (Exception ex) {
+ messageJSON.setMessage("Error occured while formfield details Tab");
+ messageJSON.setAnyStacktrace(getStackTrace(ex));
+ return messageJSON;
+ }
+
+ return messageJSON;
+ }
+
+ @RequestMapping(value = "report/wizard/save_col_tab_data", method = RequestMethod.POST)
+ public @ResponseBody MessageJSON saveColTabWiseData(@RequestBody ColumnEditJSON columnEditJSON,
+ HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
+ ReportDefinition rdef = null;
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+
+ MessageJSON messageJSON = new MessageJSON();
+
+ try {
+ if (rdef != null) {
+ String colId = columnEditJSON.getColId();
+ List<DataColumnType> reportColumnList = rdef.getAllColumns();
+
+ for (DataColumnType reportColumnType : reportColumnList) {
+ // columnJSON = new ColumnJSON();
+ if (reportColumnType.getColId().equals(colId)) {
+ reportColumnType.setColName(columnEditJSON.getColName());
+ reportColumnType.setDisplayAlignment(columnEditJSON.getDisplayAlignment());
+ reportColumnType.setDisplayHeaderAlignment(columnEditJSON.getDisplayHeaderAlignment());
+ reportColumnType.setIsSortable(columnEditJSON.isSortable());
+ reportColumnType.setVisible(columnEditJSON.isVisible());
+ reportColumnType.setDrillDownURL(columnEditJSON.getDrilldownURL());
+ reportColumnType.setDrillDownParams(columnEditJSON.getDrilldownParams());
+ reportColumnType.setDrillDownType(columnEditJSON.getDrilldownType());
+
+ }
+
+ }
+ persistReportDefinition(request, rdef);
+ messageJSON.setMessage("Success Column Details of given report is saved in session.");
+ messageJSON.setAnyStacktrace(rdef.getReportID() + " is Modified and added to session and DB.");
+
+ } else {
+ messageJSON.setMessage("Report Definition is not in session");
+ messageJSON.setAnyStacktrace("");
+
+ }
+ } catch (Exception ex) {
+ messageJSON.setMessage("Error occured while saving column details Tab");
+ messageJSON.setAnyStacktrace(getStackTrace(ex));
+
+ return messageJSON;
+ }
+
+ return messageJSON;
+ }
+
+ @RequestMapping(value = "report/wizard/save_def_tab_data/{id}", method = RequestMethod.POST)
+ public @ResponseBody MessageJSON saveDefTabWiseData(@PathVariable("id") String id,
+ @RequestBody DefinitionJSON definitionJSON, HttpServletRequest request, HttpServletResponse response)
+ throws IOException, RaptorException {
+ ReportDefinition rdef = null;
+ ReportRuntime rr = null;
+ boolean newReport = false;
+ MessageJSON messageJSON = new MessageJSON();
+
+ try {
+ if (id.equals("InSession")) {
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ newReport = false;
+
+ } else if (id.equals("Create")) {
+ removeVariablesFromSession(request);
+ rdef = (new ReportHandler()).loadReportDefinition(request, "-1");
+ newReport = true;
+ System.out.println("&&&&&&&&&&&&&&&&&&&&&& CHECK Report Type "
+ + (AppUtils.nvl(rdef.getReportType()).length() <= 0));
+ if (AppUtils.nvl(rdef.getReportType()).length() <= 0) {
+ rdef.setReportType(AppConstants.RT_LINEAR);
+ System.out.println("&&&&&&&&&&&&&&&&&&&&&& ADDED Report Type in session ");
+ }
+
+ } else if (AppUtils.nvl(id).length() > 0) {
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
+
+ if (rdef != null && !rdef.getReportID().equals(id)) {
+ request.getSession().removeAttribute(AppConstants.SI_REPORT_DEFINITION);
+ removeVariablesFromSession(request);
+ rdef = (new ReportHandler()).loadReportDefinition(request, id);
+ } else if (rr != null && !rr.getReportID().equals(id)) {
+ request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
+ removeVariablesFromSession(request);
+ rdef = (new ReportHandler()).loadReportDefinition(request, id);
+ } else if (rdef == null) {
+ rdef = (new ReportHandler()).loadReportDefinition(request, id);
+ }
+ newReport = false;
+
+ } else {
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ newReport = true;
+ }
+ // }
+
+ if (rdef != null) {
+ String reportName = definitionJSON.getReportName();
+ String errorString = "";
+ if (AppUtils.nvl(reportName).length() <= 0)
+ errorString = "ReportName cannot be null;";
+ rdef.setReportName(reportName);
+
+ String reportDescr = definitionJSON.getReportDescr();
+ rdef.setReportDescr(reportDescr);
+
+ String formHelpText = definitionJSON.getFormHelpText();
+ rdef.setFormHelpText(formHelpText);
+
+ Integer pageSize = definitionJSON.getPageSize();
+ rdef.setPageSize(pageSize);
+
+ List<IdNameBooleanJSON> menuIds = definitionJSON.getDisplayArea();
+ for (IdNameBooleanJSON menuId : menuIds) {
+ if (menuId.isSelected()) {
+ rdef.setMenuID(menuId.getName());
+ }
+
+ }
+
+ Boolean hideFormFieldsAfterRun = definitionJSON.getHideFormFieldsAfterRun();
+ rdef.setHideFormFieldAfterRun(hideFormFieldsAfterRun);
+ Integer maxRowsInExcelCSVDownload = definitionJSON.getMaxRowsInExcelCSVDownload();
+ rdef.setMaxRowsInExcelDownload(maxRowsInExcelCSVDownload);
+ Integer frozenColumns = definitionJSON.getFrozenColumns();
+ rdef.setFrozenColumns(frozenColumns);
+ String dataGridAlign = definitionJSON.getDataGridAlign();
+ rdef.setDataGridAlign(dataGridAlign);
+ String emptyMessage = definitionJSON.getEmptyMessage();
+ rdef.setEmptyMessage(emptyMessage);
+ String dataContainerHeight = definitionJSON.getDataContainerHeight();
+ rdef.setDataContainerHeight(dataContainerHeight);
+ String dataContainerWidth = definitionJSON.getDataContainerWidth();
+ rdef.setDataContainerWidth(dataContainerWidth);
+ boolean runtimeColSortDisabled = definitionJSON.getRuntimeColSortDisabled();
+ rdef.setRuntimeColSortDisabled(runtimeColSortDisabled);
+ Integer numFormCols = definitionJSON.getNumFormCols();
+ rdef.setNumFormCols(Integer.toString(numFormCols));
+ String reportTitle = definitionJSON.getReportTitle();
+ rdef.setReportTitle(reportTitle);
+ String reportSubTitle = definitionJSON.getReportSubTitle();
+ rdef.setReportSubTitle(reportSubTitle);
+
+ List<NameBooleanJSON> displayOptions = definitionJSON.getDisplayOptions();
+ StringBuffer displayOptionStr = new StringBuffer("NNNNNNN");
+ for (NameBooleanJSON displayOption : displayOptions) {
+ if (displayOption.isSelected()) {
+ if (displayOption.getName().equals("HideFormFields")) {
+ displayOptionStr.setCharAt(0, 'Y');
+ } else if (displayOption.getName().equals("HideChart")) {
+ displayOptionStr.setCharAt(1, 'Y');
+ } else if (displayOption.getName().equals("HideReportData")) {
+ displayOptionStr.setCharAt(2, 'Y');
+ } else if (displayOption.getName().equals("HideExcel")) {
+ displayOptionStr.setCharAt(5, 'Y');
+ } else if (displayOption.getName().equals("HidePdf")) {
+ displayOptionStr.setCharAt(6, 'Y');
+ }
+ }
+
+ }
+
+ rdef.setDisplayOptions(displayOptionStr.toString());
+ }
+ if (id.equals("Create")) {
+ rdef.persistReport(request);
+ } else
+ persistReportDefinition(request, rdef);
+ messageJSON.setMessage("Success Definition of given report is saved in session.");
+ messageJSON.setAnyStacktrace((newReport ? " New Report info is added to Session "
+ : rdef.getReportID() + " is Modified and added to session and DB."));
+
+ } catch (Exception ex) {
+ messageJSON.setMessage("Error occured while saving definition Tab");
+ messageJSON.setAnyStacktrace(getStackTrace(ex));
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveTabWiseData].", ex);
+ return messageJSON;
+ }
+
+ return messageJSON;
+ }
+
+ @RequestMapping(value = { "/report/wizard/retrieve_form_tab_wise_data/{id}",
+ "/report/wizard/retrieve_form_tab_wise_data/{id}/{action}" }, method = RequestMethod.GET)
+ public @ResponseBody FormEditJSON retrieveFormTabWiseData(@PathVariable Map<String, String> pathVariables,
+ HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
+ ReportDefinition rdef = null;
+ String id = "";
+ String action = "";
+ String detailId = "";
+ FormEditJSON wizardJSON = new FormEditJSON();
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+
+ if (pathVariables.containsKey("id")) {
+ id = pathVariables.get("id");
+ }
+ if (pathVariables.containsKey("action")) {
+ action = pathVariables.get("action");
+ }
+
+ ServletContext servletContext = request.getSession().getServletContext();
+ if (!Globals.isSystemInitialized()) {
+ Globals.initializeSystem(servletContext);
+ }
+ wizardJSON.setTabId("FormEdit");
+ wizardJSON.setTabName("Form Edit");
+ FormFieldType currField = null;
+ try {
+ if (id.equals("add")) {
+
+ currField = rdef.addFormFieldType(new ObjectFactory(), "", "", "", "", "", "", "", "", null, null, "",
+ "");
+ wizardJSON.setFieldId(currField.getFieldId());
+ wizardJSON.setFieldName(currField.getFieldName());
+ wizardJSON.setFieldType(currField.getFieldType());
+ wizardJSON.setVisible(AppUtils.nvls(currField.getVisible(), "Y").toUpperCase().startsWith("Y"));
+ wizardJSON.setDefaultValue(currField.getDefaultValue());
+ wizardJSON.setFieldDefaultSQL(currField.getFieldDefaultSQL());
+ wizardJSON.setFieldSQL(currField.getFieldSQL());
+ wizardJSON.setValidationType(currField.getValidationType());
+ persistReportDefinition(request, rdef);
+
+ } else if (action.equals("delete")) {
+ rdef.deleteFormField(id);
+ persistReportDefinition(request, rdef);
+ wizardJSON.setMessage("Formfield " + detailId + " Deleted");
+ }
+ if (rdef.getFormFieldList() != null) {
+ for (FormFieldType fft : rdef.getFormFieldList().getFormField()) {
+ if (fft.getFieldId().equals(id)) {
+ wizardJSON.setFieldId(fft.getFieldId());
+ wizardJSON.setFieldName(fft.getFieldName());
+ wizardJSON.setFieldType(fft.getFieldType());
+ wizardJSON.setVisible(fft.getVisible().toUpperCase().startsWith("Y"));
+ wizardJSON.setDefaultValue(fft.getDefaultValue());
+ wizardJSON.setFieldDefaultSQL(fft.getFieldDefaultSQL());
+ wizardJSON.setFieldSQL(fft.getFieldSQL());
+ wizardJSON.setValidationType(fft.getValidationType());
+
+ PredefinedValueList preDefined = fft.getPredefinedValueList();
+
+ if (preDefined != null) {
+ List<IdNameBooleanJSON> preDefinedList = new ArrayList<IdNameBooleanJSON>();
+ IdNameBooleanJSON idNameBooleanJSON = new IdNameBooleanJSON();
+
+ for (String v : preDefined.getPredefinedValue()) {
+ idNameBooleanJSON = new IdNameBooleanJSON();
+ idNameBooleanJSON.setId(v);
+ idNameBooleanJSON.setName(v);
+ preDefinedList.add(idNameBooleanJSON);
+ }
+ wizardJSON.setPredefinedValueList(preDefinedList);
+ }
+ }
+ }
+ }
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveFormTabWiseData].", ex);
+ ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
+ errorJSONRuntime.setErrormessage("Error occured while retreiving formedit definition Tab");
+ errorJSONRuntime.setStacktrace(getStackTrace(ex));
+ wizardJSON.setErrorMessage("Error occured while retreiving formedit definition Tab");
+ wizardJSON.setErrorStackTrace(getStackTrace(ex));
+
+ }
+
+ return wizardJSON;
+ }
+
+ @RequestMapping(value = { "/report/wizard/retrieve_col_tab_wise_data/{id}" }, method = RequestMethod.GET)
+ public @ResponseBody ColumnEditJSON retrieveColTabWiseData(@PathVariable Map<String, String> pathVariables,
+ HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
+ ReportDefinition rdef = null;
+ String id = "";
+ ColumnEditJSON wizardJSON = new ColumnEditJSON();
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+
+ if (pathVariables.containsKey("id")) {
+ id = pathVariables.get("id");
+ }
+ ServletContext servletContext = request.getSession().getServletContext();
+ if (!Globals.isSystemInitialized()) {
+ Globals.initializeSystem(servletContext);
+ }
+ if (rdef != null) {
+ wizardJSON.setTabId("ColEdit");
+ wizardJSON.setTabName("Column Edit");
+
+ List<DataColumnType> reportColumnList = rdef.getAllColumns();
+
+ for (DataColumnType reportColumnType : reportColumnList) {
+ if (reportColumnType.getColId().equals(id)) {
+ wizardJSON.setColId(reportColumnType.getColId());
+ wizardJSON.setColName(reportColumnType.getColName());
+ wizardJSON.setDisplayAlignment(reportColumnType.getDisplayAlignment());
+ wizardJSON.setDisplayHeaderAlignment(reportColumnType.getDisplayHeaderAlignment());
+ wizardJSON.setSortable(
+ reportColumnType.isIsSortable() == null ? false : reportColumnType.isIsSortable());
+ wizardJSON.setVisible(reportColumnType.isVisible());
+ wizardJSON.setDrilldownURL(
+ reportColumnType.getDrillDownURL() == null ? "" : reportColumnType.getDrillDownURL());
+ wizardJSON.setDrilldownParams(
+ reportColumnType.getDrillDownParams() == null ? "" : reportColumnType.getDrillDownParams());
+ wizardJSON.setDrilldownType(
+ reportColumnType.getDrillDownType() == null ? "" : reportColumnType.getDrillDownType());
+
+ }
+ }
+ } else {
+ wizardJSON.setErrorMessage("Report is not in session");
+ }
+
+ return wizardJSON;
+ }
+
+ @RequestMapping(value = { "/report/wizard/retrieve_sql_tab_wise_data/{id}",
+ "/report/wizard/retrieve_sql_tab_wise_data/" }, method = RequestMethod.GET)
+ public @ResponseBody QueryJSON retrieveSqlTabWiseData(@PathVariable Map<String, String> pathVariables,
+ HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
+ ReportDefinition rdef = null;
+ ReportRuntime rr = null;
+ String id = "";
+ String detailId = "";
+ QueryJSON wizardJSON = new QueryJSON();
+
+ if (pathVariables.containsKey("id")) {
+ id = pathVariables.get("id");
+ }
+ if (pathVariables.containsKey("detailId")) {
+ detailId = pathVariables.get("detailId");
+ }
+ ServletContext servletContext = request.getSession().getServletContext();
+ if (!Globals.isSystemInitialized()) {
+ Globals.initializeSystem(servletContext);
+ }
+ if (id.equals("InSession") || AppUtils.nvl(id).length() <= 0) {
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ } else if (AppUtils.nvl(id).length() > 0) {
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
+
+ if (rdef != null && !rdef.getReportID().equals(id)) {
+ request.getSession().removeAttribute(AppConstants.SI_REPORT_DEFINITION);
+ removeVariablesFromSession(request);
+ rdef = (new ReportHandler()).loadReportDefinition(request, id);
+ } else if (rr != null && !rr.getReportID().equals(id)) {
+ request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
+ removeVariablesFromSession(request);
+ rdef = (new ReportHandler()).loadReportDefinition(request, id);
+ } else if (rdef == null) {
+ rdef = (new ReportHandler()).loadReportDefinition(request, id);
+ }
+ }
+
+ if (rdef != null) {
+
+ wizardJSON.setTabId("Sql");
+ wizardJSON.setTabName("Sql");
+ wizardJSON.setQuery(rdef.getReportSQL());
+ }
+ return wizardJSON;
+ }
+
+ @RequestMapping(value = { "/report/wizard/security/retrieveReportUserList" }, method = RequestMethod.GET)
+ public @ResponseBody List<SecurityEntry> getReportUserList(HttpServletRequest request)
+ throws IOException, RaptorException {
+ List<SecurityEntry> reportUserList = new ArrayList<SecurityEntry>();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ Vector reportUsers = rdef.getReportUsers(request);
+ for(Iterator iter=reportUsers.iterator(); iter.hasNext();) {
+ SecurityEntry rUser = (SecurityEntry) iter.next();
+ reportUserList.add(rUser);
+ }
+ return reportUserList;
+ };
+
+ @RequestMapping(value = { "/report/wizard/security/retrieveReportRoleList" }, method = RequestMethod.GET)
+ public @ResponseBody List<IdNameValue> getReportRoleList(HttpServletRequest request)
+ throws IOException, RaptorException {
+ List<IdNameValue> reportRoleList = new ArrayList<IdNameValue>();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ Vector reportRoles = rdef.getReportRoles(request);
+ Vector remainingRoles = Utils.getRolesNotInList(reportRoles,request);
+ for(int i=0; i<remainingRoles.size(); i++) {
+ IdNameValue role = (IdNameValue) remainingRoles.get(i);
+ reportRoleList.add(role);
+ }
+ return reportRoleList;
+ };
+
+ @RequestMapping(value = { "/report/wizard/security/retrieveReportUserList_query" }, method = RequestMethod.GET)
+ public @ResponseBody List<Map<String, String>> getReportUserListQuery(HttpServletRequest request)
+ throws IOException, RaptorException {
+ List<Map<String, String>> reportUserList = new ArrayList();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ String reportId = rdef.getReportID();
+ Map<String, Object> params = new HashMap<String, Object>();
+ params.put("report_id", new Long(reportId));
+ List<ReportUserRole> queriedUserList = getDataAccessService().executeNamedQuery("getReportSecurityUsers", params, null);
+ for (int i=0; i<queriedUserList.size();i++){
+ Map<String, String> reportUser = new HashMap<String, String>();
+ Object tmp = queriedUserList.get(i);
+ reportUser.put("rep_id", queriedUserList.get(i).toString());
+ reportUser.put("order_no", queriedUserList.get(i).getOrderNo().toString());
+ reportUser.put("user_id", queriedUserList.get(i).getUserId().toString());
+ reportUser.put("role_id", queriedUserList.get(i).getRoleId().toString());
+ reportUser.put("read_only_yn", queriedUserList.get(i).getReadOnlyYn());
+ reportUserList.add(reportUser);
+ }
+ return reportUserList;
+ };
+
+
+
+ @RequestMapping(value = "/report/security/addReportUser", method = RequestMethod.POST)
+ public @ResponseBody Map<String,String> addSelectedReportUser(
+ @RequestBody String userIdToAdd, HttpServletRequest request, HttpServletResponse response)
+ throws IOException, RaptorException {
+ Map<String, String> JsonResponse = new HashMap<String, String>();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ try {
+ JsonResponse.put("status","success");
+ JsonResponse.put("userId",userIdToAdd);
+ String action = "Add User";
+ rdef.getReportSecurity().addUserAccess(userIdToAdd, "Y");
+ WizardSequence ws = rdef.getWizardSequence();
+ ws.performAction(action,rdef);
+ return JsonResponse;
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
+ return null;
+ }
+ }
+
+ @RequestMapping(value = "/report/security/removeReportUser", method = RequestMethod.POST)
+ public @ResponseBody Map<String,String> removeSelectedReportUser(
+ @RequestBody String userIdToRemove, HttpServletRequest request, HttpServletResponse response)
+ throws IOException, RaptorException {
+ Map<String, String> JsonResponse = new HashMap<String, String>();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ try {
+ JsonResponse.put("status","success");
+ JsonResponse.put("userId",userIdToRemove);
+ String action = "Delete User";
+ rdef.getReportSecurity().removeUserAccess(userIdToRemove);
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ WizardSequence ws = rdef.getWizardSequence();
+ ws.performAction(action,rdef);
+ return JsonResponse;
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
+ return null;
+ }
+ }
+
+ @RequestMapping(value = "/report/security/addReportRole", method = RequestMethod.POST)
+ public @ResponseBody Map<String,String> addSelectedReportRole(
+ @RequestBody String roleIdToAdd, HttpServletRequest request, HttpServletResponse response)
+ throws IOException, RaptorException {
+ Map<String, String> JsonResponse = new HashMap<String, String>();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ try {
+ JsonResponse.put("status","success");
+ JsonResponse.put("roleId",roleIdToAdd);
+ String action = "Add Role";
+ rdef.getReportSecurity().addRoleAccess(roleIdToAdd, "Y");
+ WizardSequence ws = rdef.getWizardSequence();
+ ws.performAction(action,rdef);
+ return JsonResponse;
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
+ return null;
+ }
+ }
+
+ @RequestMapping(value = "/report/security/removeReportRole", method = RequestMethod.POST)
+ public @ResponseBody Map<String,String> removeSelectedReportRole(
+ @RequestBody String roleIdToRemove, HttpServletRequest request, HttpServletResponse response)
+ throws IOException, RaptorException {
+ Map<String, String> JsonResponse = new HashMap<String, String>();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ try {
+ JsonResponse.put("status","success");
+ JsonResponse.put("roleId",roleIdToRemove);
+ String action = "Delete Role";
+ rdef.getReportSecurity().removeRoleAccess(roleIdToRemove);
+ WizardSequence ws = rdef.getWizardSequence();
+ ws.performAction(action,rdef);
+ return JsonResponse;
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
+ return null;
+ }
+ }
+
+ @RequestMapping(value = "/report/security/updateReportSecurityInfo", method = RequestMethod.POST)
+ public @ResponseBody Map<String,String> updateReportSecurityInfo(
+ @RequestBody Map<String,String> securityInfo, HttpServletRequest request, HttpServletResponse response)
+ throws IOException, RaptorException {
+
+ Map<String, String> JsonResponse = new HashMap<String, String>();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ try {
+ JsonResponse.put("status","success");
+ String OwnerUserId = securityInfo.get("userId");
+ String isPublic = securityInfo.get("isPublic");
+ boolean rPublic = isPublic.equals("true");
+ rdef.getReportSecurity().setOwnerID(OwnerUserId);
+ rdef.setPublic(rPublic);
+ persistReportDefinition(request, rdef);
+ return JsonResponse;
+
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
+ return null;
+ }
+ }
+
+ @RequestMapping(value = "/report/security/toggleUserEditAccess/{userID}", method = RequestMethod.POST)
+ public @ResponseBody Map<String,String> toggleUserEditAccess(
+ @PathVariable("userID") String userId,
+ @RequestBody String readOnly, HttpServletRequest request, HttpServletResponse response)
+ throws IOException, RaptorException {
+ Map<String, String> JsonResponse = new HashMap<String, String>();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ try {
+ String action ="";
+ JsonResponse.put("status","success");
+ if (readOnly.equals("N")) {
+ action = "Grant User Access";
+ } else {
+ action = "Revoke User Access";
+ }
+ rdef.getReportSecurity().updateUserAccess(userId, readOnly);
+ WizardSequence ws = rdef.getWizardSequence();
+ ws.performAction(action,rdef);
+
+ return JsonResponse;
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
+ return null;
+ }
+ };
+
+ @RequestMapping(value = "/report/security/toggleRoleEditAccess/{roleID}", method = RequestMethod.POST)
+ public @ResponseBody Map<String,String> toggleRoleEditAccess(
+ @PathVariable("roleID") String roleId,
+ @RequestBody String readOnly, HttpServletRequest request, HttpServletResponse response)
+ throws IOException, RaptorException {
+ Map<String, String> JsonResponse = new HashMap<String, String>();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ try {
+ String action ="";
+ JsonResponse.put("status","success");
+ if (readOnly.equals("N")) {
+ action = "Grant Role Access";
+ } else {
+ action = "Revoke Role Access";
+ }
+ rdef.getReportSecurity().updateRoleAccess(roleId, readOnly);
+ WizardSequence ws = rdef.getWizardSequence();
+ ws.performAction(action,rdef);
+
+ return JsonResponse;
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
+ return null;
+ }
+ };
+
+ @RequestMapping(value = { "/report/wizard/security/retrieveReportOwner" }, method = RequestMethod.GET)
+ public @ResponseBody List<IdNameValue> getReportOwnerInList(HttpServletRequest request)
+ throws IOException, RaptorException {
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+
+ List<IdNameValue> UserList = new ArrayList<IdNameValue>();
+ List excludeValues = new java.util.ArrayList();
+ HttpSession session = request.getSession();
+ String query = Globals.getCustomizedScheduleQueryForUsers();
+ session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
+ String userId = AppUtils.getUserID(request);
+ session.setAttribute("LOGGED_USERID", userId);
+ 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 allUsers = AppUtils.getAllUsers(query, param, isAdmin);
+ Vector result = new Vector(allUsers.size());
+
+ for (Iterator iter = allUsers.iterator(); iter.hasNext();) {
+ IdNameValue value = (IdNameValue) iter.next();
+
+ boolean exclude = false;
+ for (Iterator iterE = excludeValues.iterator(); iterE.hasNext();)
+ if (((IdNameValue) iterE.next()).getId().equals(value.getId())) {
+ exclude = true;
+ break;
+ } // if
+
+ if (!exclude)
+ UserList.add(value);
+ } // for
+ return UserList;
+ }
+
+
+ @RequestMapping(value = { "/report/wizard/security/getReportSecurityInfo" }, method = RequestMethod.GET)
+ public @ResponseBody Map<String,String> getReportSecurityInfo(HttpServletRequest request)
+ throws IOException, RaptorException {
+ Map<String, String> securityInfoMap = new HashMap<String,String>();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ String isPublic = Boolean.toString(rdef.isPublic());
+ String createUser = AppUtils.getUserName(rdef.getCreateID());
+ String createDate = rdef.getCreateDate();
+ String updateUser = AppUtils.getUserName(rdef.getUpdateID());
+ String updateDate = rdef.getUpdateDate();
+ String ownerId = rdef.getOwnerID();
+
+ securityInfoMap.put("isPublic",isPublic);
+ securityInfoMap.put("createdUser",createUser);
+ securityInfoMap.put("createdDate",createDate);
+ securityInfoMap.put("updateUser",updateUser);
+ securityInfoMap.put("updatedDate",updateDate);
+ securityInfoMap.put("ownerId",ownerId);
+
+ return securityInfoMap;
+ }
+
+ @RequestMapping(value = { "/report/wizard/security/getReportSecurityUsers" }, method = RequestMethod.GET)
+ public @ResponseBody List<SecurityEntry> getReportSecurityUsers(HttpServletRequest request)
+ throws IOException, RaptorException {
+
+ List<SecurityEntry> reportUserMapList = new ArrayList<SecurityEntry>();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ Vector reportUsers = rdef.getReportUsers(request);
+ int iCount = 0;
+
+ for(Iterator iter=reportUsers.iterator(); iter.hasNext(); iCount++) {
+ Map<String, String> reportUserMap = new HashMap<String,String>();
+ SecurityEntry rUser = (SecurityEntry) iter.next();
+ reportUserMapList.add(rUser);
+ }
+
+ return reportUserMapList;
+ }
+
+
+ @RequestMapping(value = { "/report/wizard/security/getReportSecurityRoles" }, method = RequestMethod.GET)
+ public @ResponseBody List<SecurityEntry> getReportSecurityRoles(HttpServletRequest request)
+ throws IOException, RaptorException {
+
+ List<SecurityEntry> reportRoleList = new ArrayList<SecurityEntry>();
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ Vector reportRoles = rdef.getReportRoles(request);
+ int iCount = 0;
+
+ for(Iterator iter=reportRoles.iterator(); iter.hasNext(); iCount++) {
+ SecurityEntry rRole = (SecurityEntry) iter.next();
+ reportRoleList.add(rRole);
+ }
+
+ return reportRoleList;
+ }
+
+
+ @RequestMapping(value = { "/report/wizard/retrieve_def_tab_wise_data/{id}",
+ "/report/wizard/retrieve_def_tab_wise_data/{id}/{detailId}" }, method = RequestMethod.GET)
+ public @ResponseBody DefinitionJSON retrieveDefTabWiseData(@PathVariable Map<String, String> pathVariables,
+ HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
+ ReportDefinition rdef = null;
+ ReportRuntime rr = null;
+ boolean newReport = false;
+ String tabId = "Def";
+ String id = "";
+
+ if (pathVariables.containsKey("id")) {
+ id = pathVariables.get("id");
+ }
+ String detailId = "";
+ if (pathVariables.containsKey("detailId")) {
+ detailId = pathVariables.get("detailId");
+ }
+
+ ServletContext servletContext = request.getSession().getServletContext();
+ if (!Globals.isSystemInitialized()) {
+ Globals.initializeSystem(servletContext);
+ }
+
+ if (tabId.equals("Def") && id.equals("InSession")) {
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ newReport = false;
+
+ } else if (tabId.equals("Def") && id.equals("Create")) {
+ removeVariablesFromSession(request);
+ rdef = (new ReportHandler()).loadReportDefinition(request, "-1");
+ rdef.setReportType(AppConstants.RT_LINEAR);
+ newReport = true;
+
+ } else if (tabId.equals("Def") && AppUtils.nvl(id).length() > 0) {
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
+
+ if (rdef != null && !rdef.getReportID().equals(id)) {
+ request.getSession().removeAttribute(AppConstants.SI_REPORT_DEFINITION);
+ removeVariablesFromSession(request);
+ rdef = (new ReportHandler()).loadReportDefinition(request, id);
+ request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
+ } else if (rr != null && !rr.getReportID().equals(id)) {
+ request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
+ removeVariablesFromSession(request);
+ rdef = (new ReportHandler()).loadReportDefinition(request, id);
+ request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
+ } else if (rdef == null) {
+ rdef = (new ReportHandler()).loadReportDefinition(request, id);
+ request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
+ }
+ newReport = false;
+
+ } else {
+ rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ }
+ DefinitionJSON wizardJSON = new DefinitionJSON();
+ if (tabId.equals("Def")) {
+ wizardJSON.setTabId("Def");
+ wizardJSON.setTabName("Definition");
+
+ wizardJSON.setReportId((rdef != null) ? rdef.getReportID() + "" : "");
+ wizardJSON.setReportName((rdef != null) ? rdef.getReportName() : "");
+ wizardJSON.setReportDescr((rdef != null) ? rdef.getReportDescr() : "");
+ wizardJSON.setReportType((rdef != null) ? rdef.getReportType() : AppConstants.RT_LINEAR);
+ wizardJSON.setDbInfo((rdef != null) ? rdef.getDBInfo() : "");
+ wizardJSON.setFormHelpText((rdef != null) ? rdef.getFormHelpText() : "");
+ wizardJSON.setPageSize((rdef != null) ? rdef.getPageSize() : 50);
+ List<IdNameBooleanJSON> displayArea = new ArrayList<IdNameBooleanJSON>();
+ IdNameBooleanJSON idNameJSON = new IdNameBooleanJSON();
+ String qMenu = "";
+ for (int i = 0; i < AppUtils.getQuickLinksMenuIDs().size(); i++) {
+ idNameJSON = new IdNameBooleanJSON();
+ qMenu = (String) AppUtils.getQuickLinksMenuIDs().get(i);
+ idNameJSON.setId(qMenu);
+ idNameJSON.setName(qMenu);
+ if (rdef != null && (rdef.getMenuID().equals(qMenu))) {
+ idNameJSON.setSelected(true);
+ }
+ displayArea.add(idNameJSON);
+ }
+ wizardJSON.setDisplayArea(displayArea);
+ wizardJSON.setHideFormFieldsAfterRun((rdef != null) ? rdef.isHideFormFieldAfterRun() : false);
+ wizardJSON.setMaxRowsInExcelCSVDownload((rdef != null) ? rdef.getMaxRowsInExcelDownload() : 500);
+ wizardJSON.setFrozenColumns((rdef != null) ? rdef.getFrozenColumns() : 0);
+ wizardJSON.setDataGridAlign((rdef != null) ? rdef.getDataGridAlign() : "left");
+ wizardJSON.setEmptyMessage((rdef != null) ? rdef.getEmptyMessage() : "No records found");
+ wizardJSON.setDataContainerHeight((rdef != null) ? rdef.getDataContainerHeight() : "600");
+ wizardJSON.setDataContainerWidth((rdef != null) ? rdef.getDataContainerWidth() : "900");
+ List<NameBooleanJSON> displayOptions = new ArrayList<NameBooleanJSON>();
+ NameBooleanJSON nameBooleanJSON = new NameBooleanJSON();
+ nameBooleanJSON.setName("HideFormFields");
+ nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideForm() : false);
+ displayOptions.add(nameBooleanJSON);
+
+ nameBooleanJSON = new NameBooleanJSON();
+ nameBooleanJSON.setName("HideChart");
+ nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideChart() : false);
+ displayOptions.add(nameBooleanJSON);
+
+ nameBooleanJSON = new NameBooleanJSON();
+ nameBooleanJSON.setName("HideReportData");
+ nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideData() : false);
+ displayOptions.add(nameBooleanJSON);
+
+ nameBooleanJSON = new NameBooleanJSON();
+ nameBooleanJSON.setName("HideExcel");
+ nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideExcelIcons() : false);
+ displayOptions.add(nameBooleanJSON);
+
+ nameBooleanJSON = new NameBooleanJSON();
+ nameBooleanJSON.setName("HidePdf");
+ nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHidePDFIcons() : false);
+ displayOptions.add(nameBooleanJSON);
+
+ wizardJSON.setDisplayOptions(displayOptions);
+
+ wizardJSON.setRuntimeColSortDisabled((rdef != null) ? rdef.isRuntimeColSortDisabled() : false);
+ wizardJSON.setNumFormCols((rdef != null) ? rdef.getNumFormColsAsInt() : 1);
+ wizardJSON.setReportTitle((rdef != null) ? rdef.getReportTitle() : "");
+ wizardJSON.setReportSubTitle((rdef != null) ? rdef.getReportSubTitle() : "");
+
+ }
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+
+ return wizardJSON;
+
+ }
+
+ @RequestMapping(value = "/report/wizard/retrieve_data/{validate}", method = RequestMethod.POST)
+ public @ResponseBody RaptorResponse retrieveDataForGivenQuery(@PathVariable("validate") boolean validate,
+ @RequestBody QueryJSON queryJSON, HttpServletRequest request, HttpServletResponse response)
+ throws IOException, RaptorException {
+ RaptorResponse raptorResponse = new RaptorResponse();
+ String sql = queryJSON.getQuery();
+ String jsonInString = "";
+
+ ServletContext servletContext = request.getSession().getServletContext();
+ if (!Globals.isSystemInitialized()) {
+ Globals.initializeSystem(servletContext);
+ }
+
+ ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
+ if (rdef == null) {
+ ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
+ errorJSONRuntime.setErrormessage("Report Definition is not in session;");
+ errorJSONRuntime.setStacktrace("");
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+
+ try {
+ jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
+ raptorResponse.data().put("elements", jsonInString);
+ return raptorResponse;
+ } catch (Exception ex1) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex1);
+ }
+ } else {
+ if (!sql.trim().toUpperCase().startsWith("SELECT")) {
+ ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
+ errorJSONRuntime.setErrormessage("Invalid statement - the SQL must start with the keyword SELECT");
+ errorJSONRuntime.setStacktrace("SQL Error");
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+
+ try {
+ jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
+ raptorResponse.data().put("elements", jsonInString);
+ return raptorResponse;
+
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
+ }
+ } else {
+ DataSet ds = null;
+ String remoteDb = request.getParameter("remoteDbPrefix");
+ // comment below two lines to test
+ String remoteDbPrefix = (remoteDb != null && !remoteDb.equalsIgnoreCase("null")) ? remoteDb
+ : rdef.getDBInfo();
+ String userId = AppUtils.getUserID(request);
+ // String userId = "1";
+ sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId);
+ sql = Utils.replaceInString(sql, "[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++) {
+ 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));
+ try {
+
+ response.setContentType("application/json");
+ ds = ConnectionUtils.getDataSet(sql, "local", true);
+
+ QueryResultJSON queryResultJSON = new QueryResultJSON();
+ queryResultJSON.setQuery(queryJSON.getQuery());
+ String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
+ rdef.parseReportSQL(query);
+ queryResultJSON.setQuery(query);
+
+ int numColumns = ds.getColumnCount();
+ queryResultJSON.setTotalRows(ds.getRowCount());
+
+ int count = 0;
+ Map<String, String> dvJSON = null;
+ ArrayList<String> colList = new ArrayList<String>();
+ ArrayList<Map<String, String>> reportDataRows = new ArrayList<Map<String, String>>();
+ if (!ds.isEmpty()) {
+ count = 0;
+
+ for (int i = 0; i < ds.getColumnCount(); i++) {
+ colList.add(ds.getColumnName(i));
+ }
+ queryResultJSON.setReportDataColumns(colList);
+ if (queryResultJSON.getTotalRows() > 0) {
+ count = 0;
+ dvJSON = new HashMap<String, String>();
+ for (int r = 0; r < Math.min(ds.getRowCount(), 100); r++) {
+ dvJSON = new HashMap<String, String>();
+ for (int c = 0; c < ds.getColumnCount(); c++) {
+ try {
+ dvJSON.put(ds.getColumnName(c), ds.getString(r, c));
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].",
+ ex);
+ }
+ }
+ reportDataRows.add(dvJSON);
+
+ }
+ }
+
+ }
+ queryResultJSON.setReportDataRows(reportDataRows);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ if (validate) {
+ query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
+ request.setAttribute("sqlValidated", "N");
+ rdef.parseReportSQL(query);
+ request.setAttribute("sqlValidated", "Y");
+ persistReportDefinition(request, rdef);
+
+ }
+ try {
+ jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(queryResultJSON);
+ raptorResponse.data().put("elements", jsonInString);
+ return raptorResponse;
+
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery]. RaptorException: ",
+ ex);
+ }
+ } catch (ReportSQLException ex) {
+ ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
+ if (sql.contains("[")) {
+ errorJSONRuntime.setErrormessage(
+ "Formfield information is present in the query, hence couldn't execute");
+ errorJSONRuntime
+ .setStacktrace("Formfield information is present in the query, hence couldn't execute");
+ if (validate) {
+ String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
+ request.setAttribute("sqlValidated", "N");
+ rdef.parseReportSQL(query);
+ request.setAttribute("sqlValidated", "Y");
+ persistReportDefinition(request, rdef);
+
+ }
+
+ } else {
+ errorJSONRuntime.setErrormessage(ex.getMessage());
+ errorJSONRuntime.setStacktrace(getStackTrace(ex));
+ }
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+
+ try {
+ jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
+ raptorResponse.data().put("elements", jsonInString);
+ return raptorResponse;
+
+ } catch (Exception ex1) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex1);
+ }
+ }
+ if (validate) {
+ String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
+ request.setAttribute("sqlValidated", "N");
+ rdef.parseReportSQL(query);
+ request.setAttribute("sqlValidated", "Y");
+ persistReportDefinition(request, rdef);
+
+ }
+
+ }
+ }
+ raptorResponse.data().put("elements", jsonInString);
+ return raptorResponse;
+
+ }
+
+ @RequestMapping(value = "save_chart", method = RequestMethod.POST)
+ public void reportChartReceive(@RequestBody ChartJSON chartJSON, HttpServletRequest request,
+ HttpServletResponse response) throws IOException {
+ ReportRuntime reportRuntime;
+ reportRuntime = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); // changing
+ // session
+ // to
+ // request
+ String reportID = request.getParameter("c_master");
+ if (reportRuntime == null && AppUtils.nvl(reportID).length() > 0) {
+ try {
+ ReportHandler rh = new ReportHandler();
+ reportRuntime = rh.loadReportRuntime(request, reportID);
+ } catch (RaptorException ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [reportChartReceive].", ex);
+ }
+ }
+
+ if (reportRuntime != null) {
+ String chartType = chartJSON.getChartType();
+ reportRuntime.setChartType(chartJSON.getChartType());
+ reportRuntime.setChartAnimate(chartJSON.isAnimation());
+ reportRuntime.setChartWidth(chartJSON.getWidth());
+ reportRuntime.setChartHeight(chartJSON.getHeight());
+ reportRuntime.setShowChartTitle(chartJSON.isShowTitle());
+
+ String domainAxis = null;
+ domainAxis = chartJSON.getDomainAxis();
+
+ List<DataColumnType> reportCols = reportRuntime.getAllColumns();
+
+ for (Iterator<DataColumnType> iter = reportCols.iterator(); iter.hasNext();) {
+ DataColumnType dct = (DataColumnType) iter.next();
+ if (dct.getColId().equals(domainAxis)) {
+ dct.setColOnChart(AppConstants.GC_LEGEND);
+ } else {
+ dct.setColOnChart(null);
+ }
+ }
+
+ CategoryAxisJSON categoryAxisJSON = chartJSON.getCategoryAxisJSON();
+ String categoryAxis = null;
+
+ categoryAxis = (categoryAxisJSON != null ? categoryAxisJSON.getValue() : "");
+
+ reportCols = reportRuntime.getAllColumns();
+
+ for (Iterator<DataColumnType> iter = reportCols.iterator(); iter.hasNext();) {
+ DataColumnType dct = (DataColumnType) iter.next();
+ if (dct.getColId().equals(categoryAxis)) {
+ dct.setChartSeries(true);
+ } else {
+ dct.setChartSeries(false);
+ }
+ }
+
+ ArrayList<RangeAxisJSON> rangeAxisList = chartJSON.getRangeAxisList();
+ int r = 0;
+ HashSet<String> removeRangeAxisMap = new HashSet<>();
+ for(RangeAxisJSON rangeAxis:chartJSON.getRangeAxisRemoveList()){
+ removeRangeAxisMap.add(rangeAxis.getRangeAxis());
+ }
+ for (int i = 0; i < rangeAxisList.size(); i++) {
+ RangeAxisJSON rangeAxisJSON = rangeAxisList.get(i);
+ String rangeAxis = rangeAxisJSON.getRangeAxis();
+ String rangeYAxis = AppUtils.nvl(rangeAxisJSON.getRangeYAxis());
+ String rangeChartGroup = AppUtils.nvl(rangeAxisJSON.getRangeChartGroup());
+ String rangeColor = AppUtils.nvl(rangeAxisJSON.getRangeColor());
+ String rangeLineType = AppUtils.nvl(rangeAxisJSON.getRangeLineType());
+
+ rangefor: for (Iterator<DataColumnType> iterator = reportCols.iterator(); iterator.hasNext();) {
+ DataColumnType dct = (DataColumnType) iterator.next();
+ if (dct.getColId().equals(rangeAxis)) {
+ if(removeRangeAxisMap.contains(rangeAxis))
+ dct.setChartSeq(-1); // if we set it to -1, means this range axis will not be included
+ else
+ dct.setChartSeq(++r);
+ dct.setColOnChart("0");
+ dct.setYAxis(rangeYAxis); // +"|"+dct.getColId());
+ dct.setChartGroup(rangeChartGroup); // +"|"+dct.getColId());
+ dct.setChartColor(rangeColor);
+ dct.setChartLineType(rangeLineType);
+
+ if (chartType.equals(AppConstants.GT_ANNOTATION_CHART)
+ || chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS)) {
+ if (rangeAxisJSON.isShowAsArea()) {
+ dct.setIsRangeAxisFilled(true);
+ } else {
+ dct.setIsRangeAxisFilled(false);
+ }
+ }
+ break rangefor;
+ }
+ }
+
+ }
+
+ reportRuntime.setChartLeftAxisLabel(chartJSON.getPrimaryAxisLabel());
+ reportRuntime.setChartRightAxisLabel(chartJSON.getSecondaryAxisLabel());
+
+ reportRuntime.setRangeAxisLowerLimit(chartJSON.getMinRange());
+ reportRuntime.setRangeAxisUpperLimit(chartJSON.getMaxRange());
+
+ if (chartType.equals(AppConstants.GT_ANNOTATION_CHART)
+ || chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS)) {
+ if (chartJSON.getFlexTimeSeriesChartOptions() != null) {
+ reportRuntime.setZoomIn(chartJSON.getFlexTimeSeriesChartOptions().getZoomIn());
+ reportRuntime.setTimeAxisType(chartJSON.getFlexTimeSeriesChartOptions().getTimeAxisType());
+ }
+
+ }
+
+ if (chartType.equals(AppConstants.GT_TIME_SERIES)) {
+ if (chartJSON.getTimeSeriesChartOptions() != null) {
+ reportRuntime.setTimeSeriesRender(chartJSON.getTimeSeriesChartOptions().getLineChartRenderer());
+ reportRuntime.setShowXAxisLabel(chartJSON.getTimeSeriesChartOptions().isShowXAxisLabel());
+ reportRuntime.setAddXAxisTickers(chartJSON.getTimeSeriesChartOptions().isAddXAxisTicker());
+ reportRuntime.setTimeAxis(chartJSON.getTimeSeriesChartOptions().isNonTimeAxis());
+ reportRuntime.setMultiSeries(chartJSON.getTimeSeriesChartOptions().isMultiSeries());
+ }
+
+ }
+
+ if (chartType.equals(AppConstants.GT_BAR_3D)) {
+ if (chartJSON.getBarChartOptions() != null) {
+ reportRuntime.setChartOrientation(
+ chartJSON.getBarChartOptions().isVerticalOrientation() ? "vertical" : "horizontal");
+ reportRuntime.setChartStacked(chartJSON.getBarChartOptions().isStackedChart());
+ reportRuntime.setBarControls(chartJSON.getBarChartOptions().isDisplayBarControls());
+ reportRuntime.setXAxisDateType(chartJSON.getBarChartOptions().isxAxisDateType());
+ reportRuntime.setLessXaxisTickers(chartJSON.getBarChartOptions().isMinimizeXAxisTickers());
+ reportRuntime.setTimeAxis(chartJSON.getBarChartOptions().isTimeAxis());
+ reportRuntime.setLogScale(chartJSON.getBarChartOptions().isyAxisLogScale());
+ }
+ }
+
+ reportRuntime.setLegendLabelAngle(chartJSON.getCommonChartOptions().getLegendLabelAngle());
+ reportRuntime.setLegendPosition(chartJSON.getCommonChartOptions().getLegendPosition());
+ reportRuntime.setChartLegendDisplay(chartJSON.getCommonChartOptions().isHideLegend() ? "Y" : "N");
+ reportRuntime.setAnimateAnimatedChart(chartJSON.getCommonChartOptions().isAnimateAnimatedChart());
+
+ reportRuntime.setTopMargin(chartJSON.getCommonChartOptions().getTopMargin());
+ reportRuntime.setBottomMargin(chartJSON.getCommonChartOptions().getBottomMargin());
+ reportRuntime.setLeftMargin(chartJSON.getCommonChartOptions().getLeftMargin());
+ reportRuntime.setRightMargin(chartJSON.getCommonChartOptions().getRightMargin());
+
+ for (Iterator<DataColumnType> iterator = reportCols.iterator(); iterator.hasNext();) {
+ DataColumnType dct = (DataColumnType) iterator.next();
+ if (!(AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)
+ || (dct.getChartSeq() != null && dct.getChartSeq() > 0) || dct.isChartSeries())) {
+ dct.setChartSeq(-1);
+ dct.setChartColor(null);
+ dct.setColOnChart(null);
+ dct.setCreateInNewChart(false);
+ dct.setChartGroup(null);
+ dct.setYAxis(null);
+ }
+ }
+
+ try {
+ reportRuntime.persistLinearReport(request);
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "[Controller.processRequest]Invalid raptor action [reportChartReceive].", ex);
+ }
+ }
+
+ }
+
+ public String getViewName() {
+ return viewName;
+ }
+
+ public void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+ public String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ public String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+ public static String getStackTrace(Throwable aThrowable) {
+ Writer result = new StringWriter();
+ PrintWriter printWriter = new PrintWriter(result);
+ aThrowable.printStackTrace(printWriter);
+ return result.toString();
+ }
+
+ 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
+
+ // Remove from session
+ 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<String> enum1 = session.getAttributeNames();
+ String attributeName = "";
+ while (enum1.hasMoreElements()) {
+ attributeName = enum1.nextElement();
+ if (attributeName.startsWith("parent_")) {
+ session.removeAttribute(attributeName);
+ }
+ }
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.system.fusion.web;
+
+
+import java.util.*;
+
+import javax.servlet.http.*;
+
+import org.onap.portalsdk.analytics.system.fusion.domain.CR_Report;
+import org.onap.portalsdk.analytics.system.fusion.service.RaptorService;
+import org.springframework.web.bind.*;
+import org.springframework.web.servlet.*;
+
+
+public class ReportsSearchListController {
+
+ private RaptorService raptorService = null;
+
+ /**
+ * @return the raptorService
+ */
+ public RaptorService getRaptorService() {
+ return raptorService;
+ }
+
+ /**
+ * @param raptorService the raptorService to set
+ */
+ public void setRaptorService(RaptorService raptorService) {
+ this.raptorService = raptorService;
+ }
+
+ public ModelAndView handleRequestInternal(HttpServletRequest request,
+ HttpServletResponse response) {
+
+ /*List items = null;
+ int reportId = ServletRequestUtils.getIntParameter(request, "report_id", 0);
+ String task = ServletRequestUtils.getStringParameter(request, "task", TASK_GET);
+
+ HashMap additionalParams = new HashMap();
+ additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request);
+
+ if (reportId != 0 && task.equals(TASK_DELETE)) { // delete the selected record
+ getRaptorService().deleteReport(new Long(reportId));
+ }
+
+ items = getRaptorService().getReports();
+
+ Map model = new HashMap();
+ model.put("items", items);
+
+ return new ModelAndView(getViewName(), "model", model);
+ */
+ //return new ModelAndView(getViewName(), "model", null);
+ System.out.println("Fill with proper code");
+ return null;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.util;
+
+import java.awt.Color;
+
+import org.onap.portalsdk.analytics.model.base.*;
+
+/**<HR/>
+ * This class is part of <B><I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I></B><BR/>
+ * <HR/>
+ *
+ * --------------------------------------------------------------------------------------------------<BR/>
+ * <B>AppConstants.java</B> - This class holds almost all shareable constants for RAPTOR.
+ * --------------------------------------------------------------------------------------------------<BR/>
+ *
+ *
+ * <U>Change Log</U><BR/><BR/>
+ *
+ * 27-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Added PUBLIC constant for SearchHandler</LI></UL>
+ * 14-Jul-2009 : Version 8.4 (Sundar); <UL><LI> New constants related to Dashboard is added.</LI></UL>
+ * 29-Jun-2009 : Version 8.4 (Sundar); <UL><LI> New constants related to Compare To Prev Year Chart is added.</LI></UL>
+ * 22-Jun-2009 : Version 8.4 (Sundar); <UL><LI> 3 new constants related to Pareto Chart, Multiple Time
+ * Series and Time difference Chart.</LI></UL>
+ *
+ */
+
+public class AppConstants {
+ // Session attribute IDs
+ public final static String SI_BACKUP_FOR_REP_ID = "backup_for_report_id";
+ public final static String SI_DASHBOARD_REP_ID = "dashboard_report_id";
+ public final static String SI_DASHBOARD_REPORTRUNTIME_MAP = "dashboardReportRuntimeMap";
+ public final static String SI_DASHBOARD_REPORTDATA_MAP = "dashboardReportDataMap";
+ public final static String SI_DASHBOARD_CHARTDATA_MAP = "dashboardChartDataMap";
+ public final static String SI_DASHBOARD_DISPLAYTYPE_MAP = "dashboardDisplayTypeMap";
+ public final static String SI_DASHBOARD_REPORTRUNTIME = "dashboardRuntime";
+ public final static String EMBEDDED_REPORTRUNTIME_MAP = "embeddedReportRuntimeMap";
+ public final static String EMBEDDED_REPORTDATA_MAP = "embeddedReportDataMap";
+
+ public final static String DRILLDOWN_INDEX = "drilldown_index";
+ public final static String FORM_DRILLDOWN_INDEX = "form_drilldown_index";
+
+ public final static String DRILLDOWN_REPORTS_LIST = "drilldownReportsList";
+
+ public final static String SI_REPORT_RUN_BACKUP = "report_runtime_backup";
+
+ public final static String SI_REPORT_RUNTIME = "report_runtime";
+
+ public final static String SI_FORMFIELD_INFO = "formfield_info";
+
+ public final static String SI_FORMFIELD_DOWNLOAD_INFO = "formfield_download_info";
+
+ public final static String SI_REPORT_DEFINITION = "report_definition";
+
+ public final static String SI_DATA_SIZE_FOR_TEXTFIELD_POPUP = "dataSizeForPopUp";
+
+ public final static String SI_MAP_OBJECT = "novamap";
+
+ public final static String SI_MAP = "raptorMap";
+
+ // Added for Adhoc Scheduling
+ public final static String SI_REPORT_SCHEDULE = "report_schedule";
+
+ public final static String SI_COLUMN_LOOKUP = "column_lookup";
+
+ // Request attribute IDs
+ public final static String RI_ACTION = "r_action";
+
+ public final static String RI_JAVASCRIPT_ITEM_ID = "javascriptItemId";
+
+ // added for form field chaining in schedule tab
+ public final static String SCHEDULE_ACTION = "N";
+
+ public final static String RI_REFRESH = "refresh";
+
+ public final static String RI_EXCEPTION = "c_exception";
+
+ public final static String RI_ERROR_LIST = "c_error_list";
+
+ public final static String RI_REPORT_ID = "c_master"; // should be
+ // reportID not
+ // c_master
+ public final static String RI_DASHBOARD_ID = "c_dashboard";
+
+ public final static String RI_DETAIL_ID = "c_detail"; // should be
+ // detailID not
+ // c_detail
+
+ public final static String RI_REPORT_DATA = "report_data";
+
+ public final static String RI_REPORT_DATA_WHOLE = "report_data_whole";
+
+ public final static String RI_REPORT_SQL_WHOLE = "report_sql_whole";
+
+ public final static String RI_CHART_DATA = "chart_data";
+
+ public final static String RI_CHART_FORECAST_DATA = "chart_forecast_data";
+
+ public final static String RI_CHART_TOTAL_COL = "chart_total"; // to show sub-totals
+
+ public final static String RI_CHART_COLOR = "chart_color"; // to specify colors
+
+ public final static String RI_CHART_INCLUDE = "chart_include"; //
+
+ public final static String RI_CHART_MARKER_START = "chart_marker_start"; //marker line
+
+ public final static String RI_CHART_MARKER_END = "chart_marker_end"; //marker line
+
+ public final static String RI_CHART_MARKER_TEXT_LEFT = "chart_marker_text_left"; //marker line
+
+ public final static String RI_CHART_MARKER_TEXT_RIGHT = "chart_marker_text_right"; //marker line
+
+ public final static String RI_ANOMALY_TEXT = "anomaly_text"; //marker line
+
+ public final static String RI_JAVASCRIPT = "javascriptElement";
+
+ public final static String RI_PAGE_TITLE = "title";
+
+ public final static String RI_PAGE_SUBTITLE = "subtitle";
+
+ public final static String RI_NEXT_PAGE = "r_page";
+
+ public final static String RI_PAGE_SIZE = "r_page_size";
+
+ public final static String RI_RECORD_NO = "r_record";
+
+ public final static String RI_NEXT_PAGE_SET = "r_page_set";
+
+ public final static String RI_DATA_SIZE = "r_data_size";
+
+ public final static String RI_SORT_ORDER = "sort_order";
+
+ public final static String RI_USER_REPORTS = "user_reports";
+
+ public final static String RI_PUBLIC_REPORTS = "public_reports";
+
+ public final static String RI_FAVORITE_REPORTS = "favorite_reports";
+
+ public final static String RI_F_REPORT_ID = "f_report_id";
+
+ public final static String RI_F_REPORT_NAME = "f_report_name";
+
+ public final static String RI_F_REPORT_CREATE_DATE = "f_report_create_date";
+
+ public final static String RI_F_PUBLIC = "f_public";
+
+ public final static String RI_F_OWNER_ID = "f_owner_id";
+
+ public final static String RI_SEARCH_RESULT = "search_result";
+
+ public final static String RI_JS_TARGET_FIELD = "js_target_field";
+
+ public final static String RI_FIELD_NAME = "field_name";
+
+ public final static String RI_COLUMN_ID = "column_id";
+
+ public final static String RI_ARG_TYPE = "arg_type";
+
+ public final static String RI_VIEW_ACTION = "view_action";
+
+ public final static String RI_SOURCE_PAGE = "source_page";
+
+ public final static String RI_GO_TO_STEP = "go_to_step";
+
+ public final static String RI_WIZARD_ACTION = "wizard_action";
+
+ public final static String RI_FORMATTED_SQL = "formatted_sql";
+
+ public final static String RI_DATA_SET = "data_set";
+
+ public final static String RI_FORM_FIELDS = "form_fields";
+
+ public final static String RI_DISPLAY_CONTENT = "display_content";
+
+ public final static String RI_SHOW_BACK_BTN = "show_back_btn";
+
+ public final static String RI_GO_BACK = "go_back";
+
+ public final static String RI_RESET_PARAMS = "reset_params";
+
+ public final static String RI_RESET_ACTION = "reset_action";
+
+ public final static String RI_VISUAL_ACTION = "v_action";
+
+ public final static String RI_SEARCH_STRING = "search_string";
+
+ public final static String RI_CONTAIN_FLAG = "contain_flag";
+
+ public final static String RI_TABLE_NAME = "table_name";
+
+ public final static String RI_DISPLAY_CHART = "display_chart";
+
+ public final static String RI_CHK_FIELD_SQL = "check_field_sql";
+
+ public final static String RI_EDIT_LINK = "edit_link";
+
+ public final static String RI_SCHEDULE_LINK = "schedule_link";
+
+ public final static String RI_LIST_CATEGORY = "raptor_list_category";
+
+ public final static String RI_SCHEDULE_ID = "c_schedule"; // should be
+ // reportID not
+ // c_master
+ public final static String RI_TEXTFIELD_POP = "forTextFieldPopUp"; // should be
+
+
+ // Visualization actions
+ public final static String VA_SHOW = "Show";
+
+ public final static String VA_HIDE = "Hide";
+
+ public final static String VA_SORT = "Sort";
+
+ public final static String HIDDEN = "Hidden";
+
+ // Wizard steps
+ public final static String WS_DEFINITION = "Definition";
+
+ public final static String WS_TABLES = "Tables";
+
+ public final static String WS_SQL = "SQL";
+
+ public final static String WS_COLUMNS = "Columns";
+
+ public final static String WS_FORM_FIELDS = "Form Fields";
+
+ public final static String WS_FILTERS = "Filters";
+
+ public final static String WS_JAVASCRIPT = "Javascript";
+
+ public final static String WS_SORTING = "Sorting";
+
+ public final static String WS_CHART = "Chart";
+
+ public final static String WS_USER_ACCESS = "Security";
+
+ public final static String WS_DATA_FORECASTING = "Forecasting";
+
+ public final static String WS_SCHEDULE = "Schedule";
+
+ public final static String WS_REPORT_LOG = "Log";
+
+ public final static String WS_RUN = "Run";
+
+ /*****for report map******/
+ public final static String WS_MAP = "Map";
+
+
+
+ // Wizard sub-steps
+ public final static String WSS_ADD = "Add";
+
+ public final static String WSS_ADD_MULTI = "Add Multiple";
+
+ public final static String WSS_ORDER_ALL = "Re-order All";
+
+ public final static String WSS_EDIT = "Edit";
+
+ public final static String WSS_DELETE = "Delete";
+
+ public final static String WSS_ADD_BLANK = "Add Blank";
+
+ public final static String WSS_INFO_BAR = "Display parameters";
+
+ // Wizard actions
+ public final static String WA_NEXT = "Next";
+
+ public final static String WA_BACK = "Back";
+
+ public final static String WA_ADD = "Add";
+
+ public final static String WA_ADD_MULTI = "Add Multiple";
+
+ public final static String WA_ORDER_ALL = "Re-order All";
+
+ public final static String WA_EDIT = "Edit";
+
+ public final static String WA_MODIFY = "Modify";
+
+ public final static String WA_DELETE = "Delete";
+
+ public final static String WA_SAVE = "Save";
+
+ public final static String WA_MOVE_UP = "Move Up";
+
+ public final static String WA_MOVE_DOWN = "Move Down";
+
+ public final static String WA_ADD_USER = "Add User";
+
+ public final static String WA_DELETE_USER = "Delete User";
+
+ public final static String WA_GRANT_USER = "Grant User Access";
+
+ public final static String WA_REVOKE_USER = "Revoke User Access";
+
+ public final static String WA_ADD_ROLE = "Add Role";
+
+ public final static String WA_DELETE_ROLE = "Delete Role";
+
+ public final static String WA_GRANT_ROLE = "Grant Role Access";
+
+ public final static String WA_REVOKE_ROLE = "Revoke Role Access";
+
+ public final static String WA_VALIDATE = "Validate";
+
+ // File types
+ public final static String FT_ZIP = ".zip";
+ public final static String FT_TXT = ".txt";
+ public final static String FT_DAT = ".dat";
+ public final static String FT_CSV = ".csv";
+ public final static String FT_XLS = ".xls";
+ public final static String FT_XLS_ALL = "_all.xls";
+
+ public final static String FT_CSV_ALL = "_all.csv";
+
+
+ public final static String FT_XML = ".xml";
+
+ public final static String FT_SQL = ".sql";
+ public final static String FT_COLUMNS = ".head";
+
+ public final static String FILE_PREFIX = "cr_";
+
+ // Chart types
+ public final static String GT_BAR_3D = "BarChart3D";
+
+ public final static String GT_HORIZ_BAR = "HorizontalBarChart";
+
+ public final static String GT_STACKED_HORIZ_BAR = "HorizontalStackedBarChart";
+
+ public final static String GT_STACKED_VERT_BAR = "VerticalStackedBarChart";
+
+ public final static String GT_STACKED_HORIZ_BAR_LINES = "HorizontalStackedBarLinesChart";
+
+ public final static String GT_STACKED_VERT_BAR_LINES = "VerticalStackedBarLinesChart";
+
+ public final static String GT_VERT_BAR = "VerticalBarChart";
+
+ public final static String GT_TOTAL_BAR = "TotalBarChart";
+
+ public final static String GT_PIE_3D = "Pie3DChart";
+
+ public final static String GT_PIE = "PieChart";
+
+ public final static String GT_PIE_MULTIPLE = "MultiplePieChart";
+
+ public final static String GT_TIME_SERIES = "TimeSeriesChart";
+
+ public final static String GT_LINE = "LineChart";
+
+ public final static String GT_SCATTER = "ScatterPlotChart";
+
+ public final static String GT_HIERARCHICAL = "HierarchicalChart";
+
+ public final static String GT_HIERARCHICAL_SUNBURST = "HierarchicalSunBurstChart";
+
+ public final static String GT_REGRESSION = "RegressionPlotChart";
+
+ public final static String GT_BAR_LINES = "BarLinesChart";
+
+ public final static String GT_MULTI_SERIES_CHART = "MultiSeriesChart";
+
+ public final static String GT_PARETO_CHART = "ParetoChart";
+
+ public final static String GT_MULTIPLE_TIMESERIES_CHART = "MultipleTimeSeriesChart";
+
+ public final static String GT_TIME_DIFFERENCE_CHART = "TimeDifferenceChart";
+
+ public final static String GT_COMPARE_PREVYEAR_CHART = "CompareToPrevYear";
+
+ public final static String GT_ANNOTATION_CHART = "AnnotationChart";
+
+ public final static String GT_FLEX_TIME_CHARTS = "FlexTimeChart";
+
+ // Non-standard chart types
+
+ public final static String GT_STACK_BAR = "StackedBarChart";
+
+ public static Color GREEN_COLOR = new Color(0, 128, 0);
+
+ // chart filter
+ public final static int CHART_ALL_COLUMNS = 0;
+ public final static int CHART_WITHOUT_NEWCHART_COLUMNS = 1;
+ public final static int CHART_NEWCHART_COLUMNS = 2;
+
+ // chart colors
+ public static Color[] CHART_SERIES_COLORS = { Color.black, GREEN_COLOR, Color.red,
+ Color.blue, Color.magenta, Color.orange, Color.cyan, Color.pink, Color.yellow };
+
+ // Chart columns
+ public final static String GC_LEGEND = "LEGEND";
+
+ /* Datamining Constants */
+ public final static String DM_DATE_ATTR = "DM_DATE_ATTR";
+ public final static String DM_FORECASTING_ATTR = "DM_FORECAST_ATTR";
+ public final static String DM_GAUSSIAN_CLASSIFIER = "GAUSSIAN";
+ public final static String DM_SVM_CLASSIFIER = "SVM";
+
+ // Schedule recurrence
+
+ public final static String SR_ONETIME = "ONE_TIME";
+ public final static String SR_HOURLY = "HOURLY";
+
+ public final static String SR_DAILY = "DAILY";
+
+ public final static String SR_DAILY_MO_FR = "DAILY_MO_FR";
+
+ public final static String SR_WEEKLY = "WEEKLY";
+
+ public final static String SR_MONTHLY = "MONTHLY";
+
+ // User access type
+ public final static String UA_READ = "read";
+
+ public final static String UA_WRITE = "write";
+
+ public final static String UA_DELETE = "delete";
+
+ // Semaphore Type
+ public static final String ST_ROW = "ROW";
+
+ public static final String ST_CELL = "CELL";
+
+ // Sort Order
+ public static final String SO_ASC = "ASC";
+
+ public static final String SO_DESC = "DESC";
+
+ // Report Log Action
+ public static final String RLA_CREATE = "Report Created";
+
+ public static final String RLA_UPDATE = "Report Updated";
+
+ public static final String RLA_DELETE = "Report Deleted"; // Not used
+
+ public static final String RLA_RUN = "Report Run";
+
+ public static final String RLA_EXECUTION_TIME = "Report Execution Time";
+
+ public static final String RLA_SCHEDULED_DOWNLOAD_EXCEL = "Scheduled and Generated in Excel";
+
+ public static final String RLA_SCHEDULED_DOWNLOAD_PDF = "Scheduled and Generated in PDF";
+
+ public static final String RLA_DOWNLOAD_EXCEL = "Generated in Excel";
+
+ public static final String RLA_DOWNLOAD_PAGE_EXCEL = "Generated in Excel for the current Page";
+
+ public static final String RLA_DOWNLOAD_EXCELX = "Generated in Excel 2007";
+
+ public static final String RLA_SCHEDULED_DOWNLOAD_EXCELX = "Scheduled and Generated in Excel 2007";
+
+ public static final String RLA_DOWNLOAD_PDF = "Generated in PDF";
+
+ public static final String RLA_DOWNLOAD_CSV = "Generated in CSV";
+
+ public static final String RLA_DOWNLOAD_TEXT = "Generated in TEXT";
+
+ public static final String RLA_ERROR = "Error Occurred";
+
+ public static final String RLA_FROM_LOG = "From Log List";
+
+ // Drill-down extra date columns extension
+ public static final String DD_COL_EXTENSION = "_dde";
+
+ // Column "don't attempt to parse as date" flag - currently placed in the
+ // comment
+ public static final String CF_NO_PARSE_DATE = "NO_PARSE_DATE";
+
+ /**
+ * *************** Transferred from CustomReportWrapper
+ * *********************
+ */
+
+ // Default Oracle date format
+ public static final String DEFAULT_DATE_FORMAT = "%m/%d/%Y";
+
+ // Java date formats
+ public static final String JAVA_DATE_FORMAT_MMDDYYYY = "MM/dd/yyyy";
+
+ public static final String JAVA_DATE_FORMAT_MMDDYYYY_HR = "MM/dd/yyyy hh aaa" ; //01-SEP-2013 00 AM
+
+ public static final String JAVA_DATE_FORMAT_MMYYYY = "MM/yyyy";
+
+ public static final String JAVA_DATE_FORMAT_DDMONYYYY = "dd-MMM-yyyy";
+
+ public static final String JAVA_DATE_FORMAT_DDMONYYYY_HR = "dd-MMM-yyyy hh aaa" ; //01-SEP-2013 00 AM
+
+ public static final String JAVA_DATE_FORMAT_MONTHDDYYYY = "MMMMMMMM dd, yyyy";
+
+ public static final String JAVA_DATE_FORMAT_MONTHYYYY = "MMMMMMMM, yyyy";
+
+ // Filter predefined values
+ public static final String FILTER_MAX_VALUE = "[MAX_VALUE]"; // Max value
+ // in that
+ // database
+ // column
+
+ public static final String FILTER_MIN_VALUE = "[MIN_VALUE]"; // Min value
+ // in that
+ // database
+ // column
+
+ // Column type constants
+ public static final String CT_CHAR = "VARCHAR2";
+
+ public static final String CT_NUMBER = "NUMBER";
+
+ public static final String CT_DATE = "DATE";
+
+ public static final String CT_HYPERLINK = "HYPERLINK";
+
+ public static final String CT_TIMESTAMP = "TIMESTAMP";
+
+ // Filter argument type constants
+ public static final String AT_FORMULA = "FORMULA"; // Exact expression -
+ // can be anything as
+ // long as fits in the
+ // SQL statement
+
+ public static final String AT_VALUE = "VALUE"; // Constant value - example
+ // 35 or Amsterdam or
+ // 11/25/2004
+
+ public static final String AT_LIST = "LIST"; // List of constant value -
+ // must include formatting -
+ // like 'a','b' or
+ // TO_DATE('11/11/2001','MM/DD/YYYY'),TO_DATE('02/11/2001','MM/DD/YYYY')
+
+ public static final String AT_COLUMN = "COLUMN"; // Column id of one of
+ // the columns in the
+ // report
+
+ public static final String AT_FORM = "FORM"; // To be inserted in a form
+ // before running the report
+
+ // Report type constants
+ public static final String RT_LINEAR = "Linear";
+
+ public static final String RT_CROSSTAB = "Cross-Tab";
+
+ public static final String RT_DASHBOARD = "Dashboard";
+ public static final String RT_HIVE = "Hive";
+
+ // Report definition type constants
+ public static final String RD_VISUAL = "Visual";
+
+ public static final String RD_SQL_BASED = "SQL-based";
+
+ public static final String RD_SQL_BASED_DATAMIN = "SQL-based_Datamining";
+
+ // Column cross-tab position
+ public static final String CV_ROW = "ROW";
+
+ public static final String CV_COLUMN = "COLUMN";
+
+ public static final String CV_VALUE = "VALUE";
+
+ // Outer join type constants
+ public static final String OJ_CURRENT = "CURRENT"; // cur_table (+) =
+ // join_table
+
+ public static final String OJ_JOINED = "JOINED"; // cur_table =
+ // join_table (+)
+
+ // List of Available Total Functions
+ public static final String TOTAL_SUM_ID = "SUM(";
+
+ public static IdNameList TOTAL_FUNCTIONS = new IdNameList();
+
+ public static final String DB_LOCAL = "local";
+
+ public static final String DB_DEV = "dev";
+
+ public static final String DB_PROD = "prod";
+
+ public static final String SHELL_SCRIPT_NAME = "dwnldflatfile.sh";
+
+ public static final String SCHEDULE_SHELL_SCRIPT_NAME = "dwnldflatfileschedule.sh";
+
+ public static final String SHELL_QUERY_DIR = "query/";
+
+ public static final String SHELL_SCRIPTS_DIR = "scripts/";
+
+ public static final String SHELL_DATA_DIR = "data/";
+
+ public static final int WEB_VERSION = 0;
+
+ public static final int IPHONE_VERSION = 1;
+
+ public static final String MYSQL = "mysql";
+ public static final String ORACLE = "oracle";
+ public static final String POSTGRESQL = "postgresql";
+
+ // COLORS to be used in Excel
+ public static String Aqua = "#00FFFF";
+ public static String Black = "#000000";
+ public static String Blue = "#0000FF";
+ public static String Fuchsia = "#FF00FF";
+ public static String Gray = "#808080";
+ public static String Green = "#008000";
+ public static String Lime = "#00FF00";
+ public static String Maroon = "#800000";
+ public static String Navy = "#000080";
+ public static String Olive = "#808000";
+ public static String Orange = "#FF9900";
+ public static String Purple = "#800080";
+ public static String Red = "#FF0000";
+ public static String Silver = "#C0C0C0";
+ public static String Teal = "#008080";
+ public static String White = "#FFFFFF";
+ public static String Yellow = "#FFFF00";
+ // End
+ public static void initializeAppConstants() {
+ // Initialize TOTAL_FUNCTIONS
+ if (TOTAL_FUNCTIONS.getCount() == 0) {
+ TOTAL_FUNCTIONS.addValue(TOTAL_SUM_ID, "Sum");
+ TOTAL_FUNCTIONS.addValue("MAX(", "Max");
+ TOTAL_FUNCTIONS.addValue("MIN(", "Min");
+ TOTAL_FUNCTIONS.addValue("COUNT(ALL ", "Count All");
+ TOTAL_FUNCTIONS.addValue("COUNT(DISTINCT ", "Count Distinct");
+ TOTAL_FUNCTIONS.addValue("AVG(ALL ", "Average All");
+ TOTAL_FUNCTIONS.addValue("AVG(DISTINCT ", "Average Distinct");
+ TOTAL_FUNCTIONS.addValue("VARIANCE(ALL ", "Variance All");
+ TOTAL_FUNCTIONS.addValue("VARIANCE(DISTINCT ", "Variance Distinct");
+ TOTAL_FUNCTIONS.addValue("STDDEV(ALL ", "Standard Deviation All");
+ TOTAL_FUNCTIONS.addValue("STDDEV(DISTINCT ", "Standard Deviation Distinct");
+ TOTAL_FUNCTIONS.addValue("AVG(ALL +STDDEV(ALL ",
+ "Average + Standard Deviation All");
+ TOTAL_FUNCTIONS.addValue("AVG(ALL +2*STDDEV(ALL ",
+ "Average + 2 * Standard Deviation All");
+ TOTAL_FUNCTIONS.addValue("AVG(ALL -STDDEV(ALL ",
+ "Average - Standard Deviation All");
+ TOTAL_FUNCTIONS.addValue("AVG(ALL -2*STDDEV(ALL ",
+ "Average - 2 * Standard Deviation All");
+ } // if
+
+ // ...
+ } // initializeAppConstants
+
+} // AppConstants
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.util;
+
+import java.io.Serializable;
+import java.sql.*;
+import java.util.*;
+
+import org.onap.portalsdk.analytics.system.Globals;
+
+public class DataSet extends Vector implements Serializable {
+ private Vector columnNames = null;
+
+ private Vector columnTypes = null;
+
+ public DataSet(ResultSet rs) throws SQLException {
+ this(rs, Integer.MAX_VALUE);
+ } // DataSet
+
+ public DataSet(ResultSet rs, int maxRowLimit) throws SQLException {
+ ResultSetMetaData rsmd = rs.getMetaData();
+ int mb = 1024*1024;
+ Runtime runtime = Runtime.getRuntime();
+
+ int colCount = rsmd.getColumnCount();
+ columnNames = new Vector(colCount);
+ columnTypes = new Vector(colCount);
+ for (int i = 1; i <= colCount; i++) {
+ columnNames.add(rsmd.getColumnLabel(i)); // getColumnLabel ??
+ columnTypes.add(rsmd.getColumnTypeName(i));
+ } // for
+
+ while (rs.next() && size() < maxRowLimit) {
+// if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*(Globals.getMemoryThreshold()*2)/100) ) {
+// System.out.println("freeMemory " + runtime.freeMemory());
+// System.out.println("Max Memory " + runtime.maxMemory());
+// System.out.println("If Logic " + (runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*(Globals.getMemoryThreshold()*2)/100)));
+// break;
+// }
+
+ Vector v = new Vector(colCount);
+ for (int i = 1; i <= colCount; i++)
+ v.add(rs.getString(i));
+ add(v);
+ } // while
+
+ if(rs!=null)
+ rs.close();
+ } // DataSet
+
+ public DataSet() {
+ columnNames = new Vector();
+ columnTypes = new Vector();
+ } // DataSet
+
+ public void insertRow(int rowIdx) {
+ if (rowIdx > size())
+ rowIdx = size();
+
+ Vector v = new Vector(columnNames.size());
+ for (int i = 0; i < columnNames.size(); i++)
+ v.add("");
+ add(rowIdx, v);
+ } // insertRow
+
+ public void insertColumn(int colIdx, String colName) {
+ insertColumn(colIdx, colName, "VARCHAR2");
+ } // insertColumn
+
+ public void insertColumn(int colIdx, String colName, String colType) {
+ if (colIdx > columnNames.size())
+ colIdx = columnNames.size();
+
+ columnNames.add(colIdx, colName);
+ columnTypes.add(colIdx, colType);
+
+ for (int i = 0; i < size(); i++)
+ ((Vector) get(i)).add(colIdx, "");
+ } // insertColumn
+
+ public void setValue(int rowIdx, int colIdx, String value) {
+ ((Vector) get(rowIdx)).set(colIdx, value);
+ } // setValue
+
+ public void setValue(int rowIdx, String colName, String value) {
+ ((Vector) get(rowIdx)).set(getColumnIndex(colName), value);
+ } // setValue
+
+ public void setString(int rowIdx, int colIdx, String value) {
+ setValue(rowIdx, colIdx, value);
+ } // setString
+
+ public void setString(int rowIdx, String colName, String value) {
+ setValue(rowIdx, colName, value);
+ } // setString
+
+ public int getRowCount() {
+ return size();
+ } // getRowCount()
+
+ public int getColumnCount() {
+ return columnNames.size();
+ } // getColumnCount
+
+ public String getColumnName(int colIdx) {
+ return ((String) columnNames.get(colIdx));
+ } // getColumnName
+
+ public String getColumnType(int colIdx) {
+ return ((String) columnTypes.get(colIdx));
+ } // getColumnType
+
+ public String getColumnType(String colName) {
+ return getColumnType(getColumnIndex(colName));
+ } // getColumnType
+
+ public int getColumnIndex(String colName) {
+ for (int i = 0; i < columnNames.size(); i++)
+ if (colName.equalsIgnoreCase((String) columnNames.get(i)))
+ return i;
+
+ return -1;
+ } // getColumnIndex
+
+ public String getString(int rowIdx, int colIdx) {
+ return nvl((String) ((Vector) get(rowIdx)).get(colIdx));
+ } // getString
+
+ public String getString(int rowIdx, String colName) {
+ return getString(rowIdx, getColumnIndex(colName));
+ } // getString
+
+ public int getInt(int rowIdx, int colIdx) {
+ return Integer.parseInt(getString(rowIdx, colIdx));
+ } // getString
+
+ public int getInt(int rowIdx, String colName) {
+ return getInt(rowIdx, getColumnIndex(colName));
+ } // getString
+
+ public String getItem(int rowIdx, int colIdx) {
+ return getString(rowIdx, colIdx);
+ } // getItem
+
+ public String getItem(int rowIdx, String colName) {
+ return getString(rowIdx, colName);
+ } // getItem
+
+ /** *********************************************************************** */
+
+ private String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ private String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+} // DataSet
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.util;
+
+
+import java.util.HashMap;
+
+import org.apache.poi.hssf.util.HSSFColor;
+
+public class ExcelColorDef {
+
+ public static HashMap colors = new HashMap();
+
+ public static void initializeExcelColorDef() {
+ colors.put("#00FFFF",new Short(HSSFColor.AQUA.index));
+ colors.put("#000000",new Short(HSSFColor.BLACK.index));
+ colors.put("#0000FF",new Short(HSSFColor.BLUE.index));
+ colors.put("#FF00FF",new Short(HSSFColor.PINK.index));
+ colors.put("#808080",new Short(HSSFColor.GREY_40_PERCENT.index));
+ colors.put("#008000",new Short(HSSFColor.BRIGHT_GREEN.index));
+ colors.put("#00FF00",new Short(HSSFColor.LIME.index));
+ colors.put("#800000",new Short(HSSFColor.MAROON.index));
+ colors.put("#000080",new Short(HSSFColor.ROYAL_BLUE.index));
+ colors.put("#808000",new Short(HSSFColor.OLIVE_GREEN.index));
+ colors.put("#FF9900",new Short(HSSFColor.ORANGE.index));
+ colors.put("#800080",new Short(HSSFColor.VIOLET.index));
+ colors.put("#FF0000",new Short(HSSFColor.RED.index));
+ colors.put("#C0C0C0",new Short(HSSFColor.CORAL.index));
+ colors.put("#008080",new Short(HSSFColor.TEAL.index));
+ colors.put("#FFFFFF",new Short(HSSFColor.WHITE.index));
+ colors.put("#FFFF00",new Short(HSSFColor.YELLOW.index));
+
+ }
+
+ public static short getExcelColor( String color) {
+ if ((colors != null) && (colors.containsKey(color))) {
+ return ((Short) colors.get(color)).shortValue();
+ }
+
+ return new Short(HSSFColor.WHITE.index).shortValue();
+ }
+
+ public static void main(String[] args) {
+ // TODO Auto-generated method stub
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.util;
+
+import java.io.*;
+
+import org.onap.portalsdk.analytics.RaptorObject;
+
+public class HtmlStripper extends RaptorObject// this function can be accessed publicly
+{
+
+ String filename;
+ final char TXT_END_TAG = '>';
+ final char TXT_START_TAG = '<';
+
+ public String stripSpecialCharacters (String s) {
+ s = nvl(s);
+ StringBuffer sbuf = new StringBuffer();
+ int c;
+ int prev_char = 0;
+ boolean inText = true;
+ for (int i = 0; i < s.length(); i++) {
+ // while c is not last character
+ c = s.charAt(i);
+ //System.out.println("444 Character " + (char)c + " int " + c);
+ if ((char) c == TXT_END_TAG) {
+ // if char == '>' text following
+ // it and not HTML tag
+ inText = true;
+ } else if ((char) c == TXT_START_TAG) {
+ // if char == '<' tag is
+ // following not text
+ inText = false;
+ } /*else if ((char)c == '\n') {
+ System.out.println("new line " + (char)c + " int " + c);
+ inText = false;
+ }*/ /*else if ((char) c == '&') {
+ // if char == '&' chars following
+ // are not text
+ inText = false;
+ }*/
+ else if (inText) {
+ // if text write char to "text.txt"
+ //System.out.println("444444 Adding " + (char)c + " int " + c);
+ if (c >= 32 && c <= 122) {
+ if(c==32 || (c>32 && c<=47) || ( c>=58 && c<=64 )) {
+ if (c == 45) {
+ prev_char = 0;
+ sbuf.append((char) 45);
+ }
+ else if(prev_char != 95) {
+ prev_char = 95;
+ sbuf.append((char) 95);
+ }
+ }
+ else {
+ prev_char=0;
+ sbuf.append((char) c);
+ }
+ }
+ }
+ }
+ //System.out.println("\n\nFinished processing: " + s + "\n\n");
+ //System.out.println("\n\nThe processed String : " + sbuf.toString() + "\n\n");
+ return sbuf.toString();
+ }
+
+ public String stripHtml(String s) {
+
+ //System.out.println("Starting to process: " + s + "\n\n"); // prints
+ s = nvl(s);
+ StringBuffer sbuf = new StringBuffer();
+ int c;
+ boolean inText = true;
+ for (int i = 0; i < s.length(); i++) {
+ // while c is not last character
+ c = s.charAt(i);
+ if ((char) c == TXT_END_TAG) {
+ // if char == '>' text following
+ // it and not HTML tag
+ inText = true;
+ } else if ((char) c == TXT_START_TAG) {
+ // if char == '<' tag is
+ // following not text
+ inText = false;
+ } /*else if ((char)c == '\n') {
+ System.out.println("new line " + (char)c + " int " + c);
+ inText = false;
+ }*/ /*else if ((char) c == '&') {
+ // if char == '&' chars following
+ // are not text
+ inText = false;
+ }*/
+ else if (inText) {
+ // if text write char to "text.txt"
+ if (c >= 32 && c <= 122) {
+ sbuf.append((char) c);
+ }
+ }
+ }
+ //System.out.println("\n\nFinished processing: " + s + "\n\n");
+ //System.out.println("\n\nThe processed String : " + sbuf.toString() + "\n\n");
+ int pos = 0 ;
+ while(sbuf.indexOf(" ")!=-1) {
+ pos = sbuf.indexOf(" ");
+ sbuf.replace(pos, pos+6, " ");
+ }
+
+ return sbuf.toString();
+ }
+
+
+ public String stripCSVHtml (String s) {
+ String s1 = stripHtml(s);
+ //s1 = Utils.replaceInString(s1, "\"", "\"\"");
+ s1 = s1.replaceAll("\"", "\"\"");
+ return s1;
+ }
+
+ public static void main(String[] args) {
+
+ String st = " Import: report name hello $ # " ;
+ System.out.println("hello " + new HtmlStripper().stripSpecialCharacters(st));
+ StringBuffer strBuf = new StringBuffer("");
+ strBuf.append("<table class=\"mTAB\" border=\"0\" width=\"60%\">\n<tr class=\"rowalt1\">\n");
+ strBuf.append(" <td>Charge To Account</td> <td>ABBZ2</td>\n");
+ strBuf.append("</tr>\n");
+ strBuf.append("<tr class=\"rowalt2\">");
+ strBuf.append("<td>dateMonth</td> <td> 04/30/2008 </td>");
+ strBuf.append("</tr>");
+ strBuf.append("<tr class=\"rowalt1\">");
+ strBuf.append("<td>Generated Date/Time</td> <td> 05/30/2008 06:15:16 PM GMT </td>");
+ strBuf.append("</tr>");
+ strBuf.append("<tr class=\"rowalt2\">");
+ strBuf.append("<td>Login Id:</td> <td> sundar </td>");
+ strBuf.append("</tr>");
+ strBuf.append("</table>");
+ new HtmlStripper().stripHtml(strBuf.toString());
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.util;
+
+public class Log {
+
+ public Log() {
+ }
+
+ public static void write(String info) {
+ System.out.println(info);
+ } // write
+
+ public static void write(String info, int debugLevel) {
+ if (debugLevel <= org.onap.portalsdk.analytics.system.Globals.getDebugLevel())
+ write(info);
+ } // write
+
+ public static void writeError(String info) {
+ System.err.println(info);
+ } // writeError
+
+} // Log
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.util;
+
+import java.util.HashMap;
+
+import org.onap.portalsdk.analytics.system.DbUtils;
+import org.onap.portalsdk.analytics.system.Globals;
+
+public class RemDbInfo {
+ private HashMap remDbMap = null;
+ private HashMap remDbTypeMap = null;
+
+ public RemDbInfo() throws Exception {
+ if (remDbMap == null) {
+ load();
+ }
+ }
+
+ public void load() throws Exception {
+ remDbMap = new HashMap();
+ remDbTypeMap = new HashMap();
+ try {
+ //String query = " SELECT a.SCHEMA_ID, a.SCHEMA_DESC, DATASOURCE_TYPE, rownum id FROM SCHEMA_INFO a " +
+ // " where schema_id = 'local' union " +
+ // " SELECT a.SCHEMA_ID, a.SCHEMA_DESC, DATASOURCE_TYPE, (rownum+1) id FROM SCHEMA_INFO a " +
+ // " where schema_id <> 'local' order by id ";
+ String query = Globals.getRemoteDbSchemaSql();
+ DataSet ds = null;
+ Globals.getDbUtils();
+ ds = DbUtils.executeQuery(query);
+
+ String prefix = "", desc = "", dbType = "";
+
+ if(ds.getRowCount() > 0) {
+ for (int i = 0; i < ds.getRowCount(); i++) {
+ prefix = ds.getItem(i, 0);
+ desc = ds.getItem(i, 1);
+ dbType = ds.getItem(i, 2);
+
+ remDbMap.put(prefix, desc);
+ remDbTypeMap.put(prefix, dbType);
+ }
+ } else {
+ remDbMap.put("local", "local");
+ remDbTypeMap.put("local", Globals.getDBType());
+ }
+ }
+ catch (Exception e) {}
+
+ }
+
+ public String getDesc(String prefix) {
+ if ((remDbMap != null) && (remDbMap.containsKey(prefix))) {
+ return (String) remDbMap.get(prefix);
+ }
+
+ return "";
+ }
+
+ public String getDBType(String prefix) {
+ if ((remDbTypeMap != null) && (remDbTypeMap.containsKey(prefix))) {
+ return (String) remDbTypeMap.get(prefix);
+ }
+
+ return "";
+ }
+
+ public HashMap getDbHash() {
+ return remDbMap;
+ }
+
+ public HashMap getDbTypeHash() {
+ return remDbTypeMap;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.util;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class SQLCorrector {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SQLCorrector.class);
+
+ public String fixSQL(StringBuffer sql) {
+
+ int pos = 0;
+ //int pos_f_select_from = 0;
+ int pos_f_select_to = 0;
+ int pos_s_select_from = 0;
+ int pos_s_select_to = 0;
+ int pos_dup_select = 0;
+ int pos_dup_select1 = 0;
+ int pos_f_format = 0;
+ int pos_t_format = 0;
+ int pos_alias_format = 0;
+ int pos_alias = 0;
+ String format = "";
+ String alias = null;
+ String sql2 = Utils.replaceInString(sql.toString(), "\n", " ");
+ sql2 = Utils.replaceInString(sql2, "\t", " ");
+ sql = new StringBuffer(sql2);
+ if (sql.indexOf("FROM", 2) != -1) {
+ pos = sql.indexOf("FROM", 2);
+ pos_f_select_to = sql.indexOf("FROM", 2);
+ if (sql.indexOf("SELECT", pos)!=-1) {
+ pos = sql.indexOf("SELECT", pos);
+ pos_s_select_from = pos;
+ pos_dup_select1 = pos;
+ //System.out.println(pos);
+ if (sql.indexOf("FROM", pos)!=-1) {
+ pos = sql.indexOf("FROM", pos);
+ pos_dup_select = sql.lastIndexOf("SELECT",pos);
+ while(pos_dup_select > pos_dup_select1) {
+ pos_dup_select1 = pos_dup_select;
+ pos = sql.indexOf("FROM", pos + 2);
+ pos_dup_select = sql.lastIndexOf("SELECT",pos);
+ }
+ pos_s_select_to = pos;
+
+ }
+ }
+ }
+
+ String o_sql = sql.substring(0, pos_f_select_to-1);
+ String i_sql = sql.substring(pos_s_select_from, pos_s_select_to-1);
+ o_sql = o_sql.toUpperCase();
+ i_sql = i_sql.toUpperCase();
+ String outer_sql = o_sql.substring(o_sql.indexOf("SELECT")+7);
+ String inner_sql = i_sql.substring(i_sql.indexOf("SELECT")+7);
+ logger.debug(EELFLoggerDelegate.debugLogger, ("|"+inner_sql+"|"));
+ String outer_cols[] = outer_sql.split(",");
+ //inner_sql = inner_sql.replaceAll(", '", ",'");
+
+ String inner_cols[] = inner_sql.split(", ");
+ inner_cols = removeExtraSpace(inner_cols);
+ logger.debug(EELFLoggerDelegate.debugLogger, ("*******OuterCols ********"));
+ printArray(outer_cols);
+ logger.debug(EELFLoggerDelegate.debugLogger, ("\n*******InnerCols********"));
+ printArray(inner_cols);
+ logger.debug(EELFLoggerDelegate.debugLogger, ("\n********Replacing Elements*****"));
+ ArrayList elements = findSum(outer_cols);
+ logger.debug(EELFLoggerDelegate.debugLogger, ("In Fix SQL " + elements.size()));
+ printArrayList(elements);
+ HashMap elementFormatMap = matchAndGetFormatInInnerCol(elements, inner_cols);
+ ArrayList outerReplacedCols = replaceOuterCols(elementFormatMap, outer_cols);
+ String finalSql = generateSQL(outerReplacedCols, sql.toString());
+ return finalSql;
+ }
+ /**
+ * @param args
+ */
+ public static void main(String[] args) {
+
+ SQLCorrector s = new SQLCorrector();
+ StringBuffer strBuf = new StringBuffer();
+ strBuf.append("SELECT NULL TOTAL_BILLMONTH, NULL TOTAL_ACCOUNTNUMBER, NULL TOTAL_SECTORCODE, NULL TOTAL_BUSINESS_UNIT_CODE, NULL TOTAL_BILLINGSITEID, NULL TOTAL_SITEADDRESS, NULL TOTAL_SITECITY, NULL TOTAL_SITESTATE, NULL TOTAL_VENDORNAME, NULL TOTAL_INVOICENUMBER, NULL TOTAL_INVOICEDATE, NULL TOTAL_SERVICEDESCRIPTION, SUM(INVOICEAMOUNT) TOTAL_INVOICEAMOUNT FROM (SELECT '2006/09/16 - 2006/10/15' BillMonth, account_number AccountNumber, (select distinct sector_code FROM billing_site where business_unit_code = BU) SectorCode, BU||' - '||(select distinct business_unit_name FROM billing_site where business_unit_code = BU) Business_Unit_Code, Site_ID BillingSiteID, site_address1 SiteAddress, site_city SiteCity, site_state SiteState, Vendor_Site_Name VendorName, invoice_number InvoiceNumber, to_char(invoice_date,'YYYY/MM/DD') InvoiceDate, billing_service_description ServiceDescription, to_char(payment_amount,'9,999,999.99') InvoiceAmount");
+ strBuf.append(" FROM cis_gm_passthrough ");
+ strBuf.append(" where ");
+ strBuf.append(" BU = decode(upper('ALL'), 'ALL', BU, substr('ALL', 1, 3)) ");
+ strBuf.append(" and BU in (SELECT distinct business_unit_code FROM billing_site where ");
+ strBuf.append(" sector_code = decode('ALL', 'ALL', sector_code, 'ALL') ");
+ strBuf.append(" and CHECK_USER_SECURITY(10, 'BUSINESS_UNIT_CODE', business_unit_code)='Y') ");
+ strBuf.append(" and to_char(bill_cycle_start_date, 'YYYY/MM/DD') = substr('2006/09/16 - 2006/10/15', 1, 10) ");
+ strBuf.append(" and to_char(bill_cycle_end_date, 'YYYY/MM/DD') = substr('2006/09/16 - 2006/10/15', 14, 10)");
+ strBuf.append(" order by business_unit_code, sitecity, sitestate, invoicedate, servicedescription ) totalSQL ");
+ String sql = strBuf.toString();
+ String fix_sql = s.fixSQL(new StringBuffer(sql.toUpperCase()));
+ logger.debug(EELFLoggerDelegate.debugLogger, (fix_sql));
+ // TODO Auto-generated method stub
+
+ }
+
+ private String[] removeExtraSpace (String[] inner_cols) {
+ String [] fixed_cols = new String[inner_cols.length];
+ for (int i = 0; i < inner_cols.length; i++) {
+ fixed_cols[i] = inner_cols[i].replaceAll(", '", ",'");
+ }
+ return fixed_cols;
+ }
+
+ private void printArray (String[] arr) {
+ logger.debug(EELFLoggerDelegate.debugLogger, (""));
+ for (int i = 0; i < arr.length; i++) {
+ System.out.print(arr[i].trim());
+ if(i<arr.length-1)
+ logger.debug(EELFLoggerDelegate.debugLogger, (","));
+ }
+ }
+
+ private void printArrayList (ArrayList arrList) {
+ logger.debug(EELFLoggerDelegate.debugLogger, (" ArrayList "));
+ for (int i = 0; i < arrList.size(); i++) {
+ System.out.print(arrList.get(i));
+ if(i<arrList.size()-1)
+ logger.debug(EELFLoggerDelegate.debugLogger, (","));
+ }
+ }
+
+ private ArrayList findSum (String[] arr ) {
+ CharSequence inputString = null;
+ Pattern pattern = null;
+ Matcher matcher = null;
+ ArrayList elements = new ArrayList();
+ boolean b = false;
+ for (int i = 0; i < arr.length; i++) {
+ //System.out.print(arr[i].trim());
+ inputString = arr[i].trim();
+ //debugLogger.debug(inputString);
+ //String keyPattern = "/SUM(|AVG|COUNT|STDDEV/";
+ String keyPattern = "SUM\\(|AVG\\(|COUNT\\(|STDDEV\\(|VARIANCE\\(|SUM \\(|AVG \\(|COUNT \\(|STDDEV \\(|VARIANCE \\(";
+ pattern = Pattern.compile(keyPattern);
+ matcher = pattern.matcher(inputString);
+ b = matcher.find();
+ //debugLogger.debug(b);
+ if(b) {
+ elements.add(arr[i].trim());
+ }
+ }
+ //debugLogger.debug("In Find Sum " + elements.size());
+ return elements;
+
+ }
+
+
+ private HashMap matchAndGetFormatInInnerCol(ArrayList arrList, String[] inner_cols) {
+ HashMap elementFormat = new HashMap();
+ String totalElement = null;
+ String extractedElement = null;
+ String format = null;
+ int pos = 0;
+ //debugLogger.debug("arrList.size() " + arrList.size());
+ for (int i = 0; i < arrList.size(); i++) {
+ totalElement = (String) arrList.get(i);
+ //debugLogger.debug("\nTotalElement " + totalElement);
+ extractedElement = totalElement.substring(totalElement.indexOf("(")+1, totalElement.indexOf(")") );
+ for (int j = 0; j < inner_cols.length; j++) {
+ //debugLogger.debug("Format " + inner_cols[j] + " " + extractedElement);
+ if(inner_cols[j].lastIndexOf(extractedElement)!=-1) {
+ if(inner_cols[j].indexOf("999")!=-1 && inner_cols[j].indexOf("TO_CHAR")!=-1) {
+ pos = inner_cols[j].indexOf("TO_CHAR");
+ pos = inner_cols[j].lastIndexOf(",'");
+ if(pos == -1)
+ pos = inner_cols[j].lastIndexOf(", '");
+ //debugLogger.debug("Format before " + inner_cols[j] + "\n*** " + pos+ " " + (inner_cols[j].substring(pos+2, inner_cols[j].indexOf("'", pos+2))));
+ format = inner_cols[j].substring(pos+2, inner_cols[j].indexOf("'", pos+2));
+ }
+ }
+ }
+ if(format!=null) {
+ //debugLogger.debug("Match and Get Format In Inner " + totalElement + " " + format);
+ elementFormat.put(totalElement, format);
+
+ }
+ format = null;
+ }
+
+ return elementFormat;
+ }
+
+ private ArrayList replaceOuterCols (HashMap hashMap, String[] outer_cols) {
+ Set mapSet = hashMap.entrySet();
+ String element = "", value = "";
+ ArrayList finalElements = new ArrayList();
+ Map.Entry me;
+ int flag=0;
+ for (int i = 0; i < outer_cols.length; i++) {
+ flag = 0;
+ for (Iterator iter = mapSet.iterator(); iter.hasNext();) {
+ me=(Map.Entry)iter.next();
+ element = (String) me.getKey();
+ value = (String) me.getValue();
+ //debugLogger.debug("Replace Map entry " + element + " " + value);
+ //debugLogger.debug("Replace " + outer_cols[i] + " " + element);
+ if(outer_cols[i].trim().equals(element.trim())) {
+ flag = 1;
+ //debugLogger.debug("I am here " + element + " " + value );
+ finalElements.add(addFormat(element,value));
+ }
+ }
+ if(flag == 0)
+ finalElements.add(outer_cols[i]);
+ }
+ return finalElements;
+ }
+
+ private String addFormat (String element, String value) {
+ StringBuffer elementBuf = new StringBuffer (element);
+ StringBuffer finalElement = new StringBuffer("");
+ String extractedElement = elementBuf.substring(elementBuf.indexOf("(")+1,elementBuf.indexOf(")"));
+ String alias = elementBuf.substring(elementBuf.lastIndexOf(" ")+1);
+ String operation = elementBuf.substring(0,elementBuf.indexOf("("));
+ //debugLogger.debug("Add Format " + alias + " "+ extractedElement);
+ finalElement.append("TO_CHAR (")
+ .append(operation)
+ .append("(TO_NUMBER (")
+ .append(extractedElement)
+ .append(",'" + value +"'")
+ .append(")),'"+value + "') ")
+ .append(alias);
+/* elementBuf.insert(0, "TO_CHAR (");
+ elementBuf.insert(elementBuf.lastIndexOf(")")+1,value+"')");
+ debugLogger.debug("FORMAT " + element);
+ debugLogger.debug("FORMAT BUF " + elementBuf.toString());
+ debugLogger.debug("Format " + finalElement.toString());
+*/
+ //debugLogger.debug("Final Element " + finalElement.toString());
+ return finalElement.toString();
+ }
+
+ private String generateSQL( ArrayList outerSql, String sql) {
+
+ StringBuffer finalSql = new StringBuffer("SELECT ") ;
+
+ for (int i = 0; i < outerSql.size(); i++) {
+ finalSql.append(outerSql.get(i));
+ if ( i < outerSql.size()-1 )
+ finalSql.append(",");
+ }
+ finalSql.append(" "+sql.substring(sql.indexOf("FROM")));
+ logger.debug(EELFLoggerDelegate.debugLogger, (" ---" + finalSql.toString()));
+ return finalSql.toString();
+ }
+
+
+/* public String fixCrosstabSQL1(StringBuffer sql) {
+ int pos = 0;
+ int pos_f_format = 0;
+ int pos_t_format = 0;
+ int pos_alias = 0;
+ String format = "";
+ String alias = null;
+ if(sql.indexOf("SELECT", 7)!= -1) {
+ pos = sql.indexOf("SELECT", 7);
+ if(sql.indexOf("TO_CHAR", pos)!= -1){
+ pos = sql.indexOf("TO_CHAR", pos);
+ debugLogger.debug("pos" + pos);
+ if(sql.indexOf("999",pos)!= -1) {
+ pos = sql.indexOf("999",pos);
+ pos_f_format = sql.lastIndexOf(", '", pos);
+ debugLogger.debug("pos_f_format" + pos_f_format);
+ if(pos_f_format == -1 || (pos - pos_f_format > 10)) {
+ pos_f_format = sql.lastIndexOf(",'", pos);
+ pos_f_format -= 1;
+ }
+ pos = pos_f_format;
+ if(sql.indexOf("')", pos)!= -1) {
+ pos_t_format = sql.indexOf("')", pos);
+ debugLogger.debug("pos_t - " + pos_t_format + " " + pos);
+ if(pos_t_format == -1 || (pos_t_format - pos > 20)) {
+ pos_t_format = sql.indexOf("' )", pos);
+ pos_t_format += 3;
+ }
+ else if (pos_t_format != -1)
+ pos_t_format += 2;
+ format = sql.substring(pos_f_format+3, pos_t_format);
+ //alias = sql.substring(pos_t_format+3, pos_t_format+6);
+ pos_alias = sql.indexOf(" ", pos_t_format);
+ alias = sql.substring(pos_alias+1, pos_alias+4);
+ }
+ }
+ }
+
+ if(sql.indexOf(alias)!=-1) {
+ pos = sql.indexOf(alias);
+ debugLogger.debug(pos + " " + alias.length()+1 + "\n" + sql);
+ sql.delete(pos,pos+4);
+ sql.insert(pos, "TO_NUMBER("+alias+", '"+format+"')),'"+ format + "')");
+ pos = sql.lastIndexOf("SUM", pos);
+ if(pos==-1)
+ pos = sql.lastIndexOf("AVG", pos);
+ else if (pos==-1)
+ pos = sql.lastIndexOf("COUNT", pos);
+ else if (pos == -1)
+ pos = sql.lastIndexOf("STDDEV", pos);
+ else if (pos == -1)
+ pos = sql.lastIndexOf("VARIANCE", pos);
+ sql.insert(pos, "TO_CHAR (");
+ }
+
+ }
+
+ debugLogger.debug("Alias|" + alias + "| Format " + format);
+ debugLogger.debug(sql.toString());
+ return sql.toString();
+ } // FixSQL
+*/
+
+
+}
+
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.util;
+
+import java.sql.SQLException;
+import java.util.*;
+
+import org.onap.portalsdk.analytics.error.ReportSQLException;
+import org.onap.portalsdk.analytics.scheduler.SendNotifications;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+
+public class Scheduler extends TimerTask {
+ private Timer timer = new Timer(true);
+
+ private int timeInterval = 0;
+
+ public Scheduler(int timeInterval) {
+ super();
+
+ this.timeInterval = timeInterval;
+ start();
+ } // Scheduler
+
+ public void start() {
+ if (timeInterval > 0)
+ timer.schedule(this, 0, timeInterval * 1000);
+ }
+
+ public void stop() {
+ timer.cancel();
+ }
+
+ public void run() {
+
+ SendNotifications sendNotifications = null;
+
+ try {
+ Log.write("[Scheduler.run " + (new java.util.Date()).toString()
+ + "] Sending notifications...", 4);
+ //System.out.println("SMTP Server " + AppUtils.getSMTPServer());
+ //System.out.println("System Name " + Globals.getSystemName());
+ //System.out.println("DefaultEmailSender " + AppUtils.getDefaultEmailSender());
+ //System.out.println("DirectAccessURL " + AppUtils.getDirectAccessURL());
+ //System.out.println("timeInterval " + timeInterval);
+ /*
+ DbUtils.executeCall(
+ "BEGIN cr_raptor.send_notifications(" +
+ "'" + AppUtils.getSMTPServer() + "', " +
+ "'" + AppUtils.getDefaultEmailSender() + "', " +
+ "'" + Globals.getSystemName() + "', " +
+ "'" + AppUtils.getDirectAccessURL() + "', " +
+ timeInterval +
+ "); END;", false);
+ */
+ sendNotifications = new SendNotifications();
+ sendNotifications.send_notification(AppUtils.getSMTPServer(), AppUtils.getSMTPServer(), Globals.getSystemName() ,
+ AppUtils.getDirectAccessURL(), timeInterval);
+
+ } catch (Exception e) {
+ Log.write("[SYSTEM ERROR Scheduler.run] Exception: " + e.getMessage());
+ //e.printStackTrace();
+ }
+ finally {
+
+ try {
+ sendNotifications.deInit();
+ } catch (SQLException e) {
+ Log.write("[SYSTEM ERROR Scheduler.run] Could not close connection: " + e.getMessage());
+ }
+ }
+ } // run
+
+} // Scheduler
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.util;
+
+import java.util.*;
+import java.util.regex.Pattern;
+import java.io.File;
+import java.text.*;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalsdk.analytics.error.RaptorException;
+import org.onap.portalsdk.analytics.model.base.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.system.fusion.adapter.Item;
+
+
+public class Utils extends org.onap.portalsdk.analytics.RaptorObject {
+
+ public Utils() {
+ }
+
+ public static String getCurrentDateTime() {
+ return (new SimpleDateFormat(Globals.getJavaTimeFormat())).format(new Date());
+ } // getCurrentDateTime
+
+ public static String truncateDecimals(String value, int maxDecimals) {
+ return (maxDecimals < 0 || value == null || value.indexOf('.') < 0
+ || (value.indexOf('.') == value.length() - 1) || value.substring(
+ value.indexOf('.')).length() - 1 <= maxDecimals) ? value : value.substring(0,
+ value.indexOf('.') + maxDecimals + 1);
+ } // truncateDecimals
+
+ public static String truncateTotalDecimals(String value) {
+ return truncateDecimals(value, Globals.getMaxDecimalsOnTotals());
+ } // truncateTotalDecimals
+
+ public static String replaceInString(String replaceInStr, String replaceStr,
+ String replaceWithStr) {
+ if (replaceStr.equals(replaceWithStr))
+ return replaceInStr;
+
+ while (replaceInStr!=null && replaceInStr.indexOf(replaceStr) >= 0) {
+ int startIdx = replaceInStr.indexOf(replaceStr);
+ int endIdx = startIdx + replaceStr.length();
+
+ StringBuffer sb = new StringBuffer();
+ if (startIdx > 0)
+ sb.append(replaceInStr.substring(0, startIdx));
+ sb.append(nvls(replaceWithStr));
+ if (endIdx < replaceInStr.length())
+ sb.append(replaceInStr.substring(endIdx));
+ replaceInStr = sb.toString();
+ } // while
+
+ return replaceInStr;
+ } // replaceInString
+
+ public static String singleQuoteEncode(String value) {
+ value = value!=null?value:"";
+ value = Pattern.compile("[\']",Pattern.DOTALL).matcher(value).replaceAll("\\\\\\'");
+ return value;
+ }
+
+ public static String htmlEncode(String value) {
+ return replaceInString(replaceInString(value, "<", "<"), ">", ">");
+ } // htmlEncode
+
+ public static String excelEncode(String value) {
+ String replaceStr = replaceInString(replaceInString(value, "<", "<"), ">", ">");
+ String reg = "&(?!&#)";
+ Pattern p = Pattern.compile(reg);
+ String replaceStrAmpersand = p.matcher(replaceStr).replaceAll("&");
+ return replaceStrAmpersand;
+ } // htmlEncode
+
+
+ public static String oracleSafe(String s) {
+ if (s == null)
+ return null;
+
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < s.length(); i++) {
+ char ch = s.charAt(i);
+ if (ch == '\''/* &&(i>=s.length()-1||s.charAt(i+1)!='\'') */)
+ sb.append('\'');
+ sb.append(ch);
+ } // for
+
+ return sb.toString();
+ } // oracleSafe
+
+
+ public static String javaSafe(String s) {
+ if (s == null)
+ return null;
+
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < s.length(); i++) {
+ char ch = s.charAt(i);
+ if (ch == '"')
+ sb.append('\\');
+ sb.append(ch);
+ } // for
+
+ return sb.toString();
+ } // javaSafe
+
+ public static Vector getUsersNotInList(List excludeValues, HttpServletRequest request)throws RaptorException {
+ HttpSession session = request.getSession();
+// String[] whereConditionAndSess = Globals.getWhereConditionForUserRole().split(",");
+// String whereCondition = "";
+// String conditionalValue = "";
+// for (int i = 0; i < whereConditionAndSess.length; i++) {
+// whereCondition = whereConditionAndSess[0];
+// }
+// for (int i = 1; i < whereConditionAndSess.length; i++) {
+// conditionalValue = whereConditionAndSess[1];
+// }
+// whereCondition = " where "+ whereCondition + "'" + (String)session.getAttribute(conditionalValue) + "'";
+
+// Vector allUsers = AppUtils.getAllUsers(whereCondition);
+ String query = Globals.getCustomizedScheduleQueryForUsers();
+ session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
+ String userId = AppUtils.getUserID(request);
+ session.setAttribute("LOGGED_USERID", userId);
+ 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 allUsers = AppUtils.getAllUsers(query,param, isAdmin);
+ Vector result = new Vector(allUsers.size());
+
+ for (Iterator iter = allUsers.iterator(); iter.hasNext();) {
+ IdNameValue value = (IdNameValue) iter.next();
+
+ boolean exclude = false;
+ for (Iterator iterE = excludeValues.iterator(); iterE.hasNext();)
+ if (((IdNameValue) iterE.next()).getId().equals(value.getId())) {
+ exclude = true;
+ break;
+ } // if
+
+ if (!exclude)
+ result.add(value);
+ } // for
+
+ return result;
+ } // getUsersNotInList
+
+ public static Vector getRolesNotInList(List excludeValues, HttpServletRequest request) throws RaptorException {
+ HttpSession session = request.getSession();
+ String query = Globals.getCustomizedScheduleQueryForRoles();
+ session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
+ String userId = AppUtils.getUserID(request);
+ session.setAttribute("LOGGED_USERID", userId);
+ 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 result = new Vector(allRoles.size());
+
+ for (Iterator iter = allRoles.iterator(); iter.hasNext();) {
+ IdNameValue value = (IdNameValue) iter.next();
+
+ boolean exclude = false;
+ for (Iterator iterE = excludeValues.iterator(); iterE.hasNext();)
+ if (((IdNameValue) iterE.next()).getId().equals(value.getId())) {
+ exclude = true;
+ break;
+ } // if
+
+ // Exclude the super role
+ if (value.getId().equals(AppUtils.getSuperRoleID()))
+ exclude = true;
+
+ if (!exclude)
+ result.add(value);
+ } // for
+
+ return result;
+ } // getRolesNotInList
+
+ public static List<Item> getUsersNotInListLatest(List excludeValues, HttpServletRequest request)throws RaptorException {
+ HttpSession session = request.getSession();
+ String query = Globals.getCustomizedScheduleQueryForUsers();
+ session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
+ String userId = AppUtils.getUserID(request);
+ session.setAttribute("LOGGED_USERID", userId);
+ String[] sessionParameters = Globals.getSessionParams().split(",");
+ String param = "";
+ for (int i = 0; i < sessionParameters.length; i++) {
+ param = (String)session.getAttribute(sessionParameters[i]);
+ 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 result = new Vector(allUsers.size());
+
+ List<Item> resultLatest = new ArrayList<Item>();
+
+ for (Iterator iter = allUsers.iterator(); iter.hasNext();) {
+ IdNameValue value = (IdNameValue) iter.next();
+
+ boolean exclude = false;
+ for (Iterator iterE = excludeValues.iterator(); iterE.hasNext();)
+ if (((IdNameValue) iterE.next()).getId().equals(value.getId())) {
+ exclude = true;
+ break;
+ } // if
+
+ if (!exclude)
+ resultLatest.add(new Item(value.getId(), value.getName()));
+ } // for
+
+ return resultLatest;
+ } // getUsersNotInListLatest
+
+
+ public static List<Item> getRolesNotInListLatest(List excludeValues, HttpServletRequest request) throws RaptorException {
+ HttpSession session = request.getSession();
+ String query = Globals.getCustomizedScheduleQueryForRoles();
+ session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
+ String userId = AppUtils.getUserID(request);
+ session.setAttribute("LOGGED_USERID", userId);
+ String[] sessionParameters = Globals.getSessionParams().split(",");
+ String param = "";
+ for (int i = 0; i < sessionParameters.length; i++) {
+ param = (String)session.getAttribute(sessionParameters[i]);
+ 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 result = new Vector(allRoles.size());
+
+ List<Item> resultLatest = new ArrayList<Item>();
+
+ for (Iterator iter = allRoles.iterator(); iter.hasNext();) {
+ IdNameValue value = (IdNameValue) iter.next();
+
+ boolean exclude = false;
+ for (Iterator iterE = excludeValues.iterator(); iterE.hasNext();)
+ if (((IdNameValue) iterE.next()).getId().equals(value.getId())) {
+ exclude = true;
+ break;
+ } // if
+
+ // Exclude the super role
+ if (value.getId().equals(AppUtils.getSuperRoleID()))
+ exclude = true;
+
+ if (!exclude)
+ resultLatest.add(new Item(value.getId(), value.getName()));
+ } // for
+
+ return resultLatest;
+ } // getRolesNotInList
+ /*
+ * public static String nvl(String s) { return (s==null)?"":s; } // nvl
+ *
+ * public static String nvl(String s, String sDefault) { return
+ * nvl(s).equals("")?sDefault:s; } // nvl
+ */
+
+ public static void _assert(boolean condition, String errMsg) {
+ if (org.onap.portalsdk.analytics.system.Globals.getDebugLevel() > 0)
+ if (!condition)
+ throw new RuntimeException(errMsg);
+ } // _assert
+
+ public static boolean isNull(String a) {
+ if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null"))
+ return true;
+ else
+ return false;
+ }
+
+
+ public static boolean isDownloadFileExists(String fileNamePrefix) {
+ File f = new File (Globals.getShellScriptDir()+AppConstants.SHELL_DATA_DIR);
+ String[] fileNames = f.list();
+ //System.out.println("Util.boolean Prefix" + fileNamePrefix);
+ if(fileNames!=null) {
+ for (int i = 0; i < fileNames.length; i++) {
+ //System.out.println("Util.boolean " + fileNames[i]);
+ if(fileNames[i].startsWith(fileNamePrefix)) {
+ return true;
+ }
+ }
+ }
+ return false;
+
+ }
+
+ public static String getLatestDownloadableFile(String fileNamePrefix) {
+ File f = new File (Globals.getShellScriptDir()+AppConstants.SHELL_DATA_DIR);
+ String[] fileNames = f.list();
+ ArrayList matchingFiles = new ArrayList();
+ //System.out.println("Util.download Prefix" + fileNamePrefix);
+ for (int i = 0; i < fileNames.length; i++) {
+ //System.out.println("Util.download " + fileNames[i]);
+ if(fileNames[i].startsWith(fileNamePrefix)) {
+ matchingFiles.add(fileNames[i]);
+ }
+ }
+ //System.out.println("SIZE 1 " + matchingFiles.size());
+ String tmpFileName = "";
+ int numberOfTimesLooped = 0;
+ boolean isSorted = false;
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
+ Date date1 = null, date2 = null;
+ Date currDate = new Date();
+ Object[] matchingfileNamesArr = matchingFiles.toArray();
+ //System.out.println("SIZE " + matchingFiles.size());
+ String fileName1 = "", fileName2 ="";
+ do {
+ isSorted = true;
+ for (int j = 1; j < matchingfileNamesArr.length - numberOfTimesLooped++; j++) {
+ fileName1 = (String) matchingfileNamesArr[j];
+ fileName2 = (String) matchingfileNamesArr[j-1];
+ try{
+ date1 = sdf.parse(fileName1.substring(fileName1.lastIndexOf("_")+1,fileName1.lastIndexOf(".")));
+ date2 = sdf.parse(fileName2.substring(fileName2.lastIndexOf("_")+1,fileName2.lastIndexOf(".")));
+ }
+ catch(ParseException ex) {
+ return null;
+ }
+
+ if ( (currDate.getTime()-date1.getTime()) < (currDate.getTime()-date2.getTime())) {
+ tmpFileName = fileName1;
+ matchingfileNamesArr[j] = fileName2;
+ matchingfileNamesArr[j-1] = tmpFileName;
+ isSorted = false;
+ }
+
+ }
+ } while (!isSorted);
+ if(matchingfileNamesArr.length>0)
+ return (String)matchingfileNamesArr[0];
+ else
+ return null;
+
+ }
+
+
+} // Utils
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.util;
+
+ /**
+ *
+ * @author Sundar
+ * This class is used to filter javascript tags to avoid XSS attacks.
+ */
+public class XSSFilter {
+
+ // private static String[] filterChars = { "<", ">", "<", ">", "\"", "\\", "0x" };
+// private static String[] replacementChars = { " ", " ", " ", " ", "'", "/", "0 x" };
+
+/* public static synchronized String filterRequest(String param) {
+ String value = param;
+
+ if (param != null) {
+
+ for (int i = 0; i < filterChars.length; i++) {
+ value = filterCharacters(filterChars[i], replacementChars[i],
+ value);
+ }
+
+ }
+
+ return value;
+
+ }
+*/
+
+ public static synchronized String filterRequestOnlyScript(String param) {
+ String value = "";
+ value = nvl(param);
+ value = value.replaceAll("<[\\s]*[sS][\\s]*[cC][\\s]*[rR][\\s]*[iI][\\s]*[pP][\\s]*[tT][\\s]*>", "");
+ value = value.replaceAll("</[\\s]*[sS][\\s]*[cC][\\s]*[rR][\\s]*[iI][\\s]*[pP][\\s]*[tT][\\s]*>", "");
+ value = value.replaceAll("[\\s]*[jJ][\\s]*[aA][\\s]*[vV][\\s]*[aA][\\s]*[sS][\\s]*[cC][\\s]*[rR][\\s]*[iI][\\s]*[pP][\\s]*[tT][\\s]*", "");
+ return value;
+ }
+ public static synchronized String filterRequest (String param) {
+ String value = "";
+ value = nvl(param);
+ value = value.replaceAll("<[\\s]*[sS][\\s]*[cC][\\s]*[rR][\\s]*[iI][\\s]*[pP][\\s]*[tT][\\s]*>", "");
+ value = value.replaceAll("</[\\s]*[sS][\\s]*[cC][\\s]*[rR][\\s]*[iI][\\s]*[pP][\\s]*[tT][\\s]*>", "");
+ value = value.replaceAll("[\\s]*[jJ][\\s]*[aA][\\s]*[vV][\\s]*[aA][\\s]*[sS][\\s]*[cC][\\s]*[rR][\\s]*[iI][\\s]*[pP][\\s]*[tT][\\s]*", "");
+ value = value.replaceAll("[\\s]*<", "");
+ value = value.replaceAll("[\\s]*>", "");
+
+ return value;
+ }
+
+// private static synchronized String filterCharacters(String originalChar, String newChar,
+// String param) {
+// StringBuffer sb = new StringBuffer(param);
+//
+// for (int position = param.toLowerCase().indexOf(originalChar); position >= 0;) {
+// sb.replace(position, position + originalChar.length(), newChar);
+// param = sb.toString();
+// position = param.toLowerCase().indexOf(originalChar);
+// }
+//
+// return sb.toString();
+// }
+
+ public static void main (String args[]) {
+ String value = XSSFilter.filterRequest("<s\nC\nr\nI\np\nT\n>\na\nl\ne\nr\nt\n('sundar');</SCRIPT>javascript:alert('Sundar');");
+ int i = Integer.parseInt("8989");
+ System.out.println(value);
+ }
+
+ private static String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.util.jar;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.Writer;
+import java.net.URL;
+import java.util.jar.JarEntry;
+import java.util.jar.JarInputStream;
+
+public class ExtractJar {
+
+ public static int bufferSize = 8192;
+ public static String JARFILE = "raptor_upgrade.jar";
+
+ /**
+ * @param args
+ */
+ public static void main(String[] args) throws Exception {
+ if (args.length > 0 && args[0] != null && args[0].length() > 0)
+ extractFilesFromJar(args[0]);
+ else {
+ System.out.println("Current Directory is taken as webapp path");
+ String currentDir = new File(".").getAbsolutePath();
+ extractFilesFromJar(currentDir);
+ }
+ }
+
+ /**
+ *
+ * @param jarFile
+ * @throws Exception
+ */
+ public static void readJar(File jarFile) throws Exception {
+ JarInputStream in = new JarInputStream(new FileInputStream(jarFile));
+ JarEntry je;
+ while ((je = in.getNextJarEntry()) != null) {
+ if (je.isDirectory() == false) {
+ if (je.getName().startsWith("org/onap/portalsdk/analytics/config/")) {
+ System.out.println(je.getName() + " " + je.getTime());
+
+ }
+ }
+ }
+ in.close();
+ }
+
+ /**
+ *
+ * @param directory
+ * @throws IOException
+ */
+ public static void extractFilesFromJar(String directory) throws IOException {
+ Class clazz = ExtractJar.class;
+ URL jarUrl = clazz.getProtectionDomain().getCodeSource().getLocation();
+
+ JarInputStream entryStream = new JarInputStream(jarUrl.openStream());
+ JarEntry entry;
+
+ while (true) {
+ entry = entryStream.getNextJarEntry();
+ if (entry == null)
+ break;
+ if (entry.getName().indexOf("jarutil") < 0) {
+ System.out.println(entry.getName());
+ File file = new File(directory, entry.getName());
+ if (entry.isDirectory()) {
+ if (!file.exists())
+ file.mkdirs();
+ } else {
+ File dir = new File(file.getParent());
+ if (!dir.exists())
+ dir.mkdirs();
+ if (file.exists())
+ file.delete();
+ FileOutputStream fout = new FileOutputStream(file);
+ copy(entryStream, fout);
+ fout.close();
+
+ if (entry.getTime() >= 0)
+ file.setLastModified(entry.getTime());
+ }
+
+ }
+ entryStream.closeEntry();
+ }
+ entryStream.close();
+ System.out.println("/WEB-INF/classes/org/onap/portalsdk/analytics");
+ System.out.println("Delete .... ");
+
+ File file1 = new File(directory, "/WEB-INF/classes/org/onap/portalsdk/analytics");
+
+ deleteDir(file1);
+ System.out.println("Deleted ....");
+
+ System.out.println("raptor_upgrade_setup.jar");
+ file1 = new File(directory, "/raptor_upgrade_setup.jar");
+
+ deleteDir(file1);
+ System.out.println("Deleted ....");
+
+ System.out.println("/org");
+ System.out.println("Delete .... ");
+
+ file1 = new File(directory, "/org");
+ System.out.println(" ********************************* ");
+ deleteDir(file1);
+ System.out.println("Deleted ....");
+ System.out.println("org");
+ System.out.println("Delete .... ");
+
+ System.out.println("************************************************");
+ System.out.println("* *");
+ System.out.println("* *");
+ System.out.println("* RAPTOR SETUP COMPLETE. *");
+ System.out.println("* *");
+ System.out.println("* Thank you for upgrading. *");
+ System.out.println("* *");
+ System.out.println("************************************************");
+ }
+
+ /**
+ *
+ * @param in
+ * @param out
+ * @param byteCount
+ * @throws IOException
+ */
+ public static void copy(InputStream in, OutputStream out, long byteCount) throws IOException {
+ byte buffer[] = new byte[bufferSize];
+ int len = bufferSize;
+ if (byteCount >= 0) {
+ while (byteCount > 0) {
+ if (byteCount < bufferSize)
+ len = in.read(buffer, 0, (int) byteCount);
+ else
+ len = in.read(buffer, 0, bufferSize);
+ if (len == -1)
+ break;
+
+ byteCount -= len;
+ out.write(buffer, 0, len);
+ }
+ } else {
+ while (true) {
+ len = in.read(buffer, 0, bufferSize);
+ if (len < 0)
+ break;
+ out.write(buffer, 0, len);
+ }
+ }
+ }
+
+ /**
+ * Copy Reader to Writer for byteCount bytes or until EOF or exception.
+ *
+ * @param in
+ * @param out
+ * @param byteCount
+ * @throws IOException
+ */
+ public static void copy(Reader in, Writer out, long byteCount) throws IOException {
+ char buffer[] = new char[bufferSize];
+ int len = bufferSize;
+ if (byteCount >= 0) {
+ while (byteCount > 0) {
+ if (byteCount < bufferSize)
+ len = in.read(buffer, 0, (int) byteCount);
+ else
+ len = in.read(buffer, 0, bufferSize);
+
+ if (len == -1)
+ break;
+ byteCount -= len;
+ out.write(buffer, 0, len);
+ }
+ } else {
+ while (true) {
+ len = in.read(buffer, 0, bufferSize);
+ if (len == -1)
+ break;
+ out.write(buffer, 0, len);
+ }
+ }
+ }
+
+ /**
+ * Copy Stream in to Stream out until EOF or exception.
+ *
+ * @param in
+ * @param out
+ * @throws IOException
+ */
+ public static void copy(InputStream in, OutputStream out) throws IOException {
+ copy(in, out, -1);
+ }
+
+ public static boolean deleteDir(File dir) {
+ System.out.println("Name: " + dir.getName() + " " + dir.isDirectory());
+ if (dir.isDirectory()) {
+ String[] children = dir.list();
+ System.out.println(children);
+ for (int i = 0; i < children.length; i++) {
+ boolean success = deleteDir(new File(dir, children[i]));
+ if (!success) {
+ return false;
+ }
+ }
+ }
+
+ return dir.delete();
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.util.upgrade;
+
+import java.io.*;
+import java.sql.*;
+import java.util.*;
+import javax.servlet.http.*;
+
+import org.onap.portalsdk.analytics.controller.*;
+import org.onap.portalsdk.analytics.error.*;
+import org.onap.portalsdk.analytics.model.*;
+import org.onap.portalsdk.analytics.model.base.*;
+import org.onap.portalsdk.analytics.model.definition.*;
+import org.onap.portalsdk.analytics.model.runtime.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+import org.onap.portalsdk.analytics.view.*;
+import org.onap.portalsdk.analytics.xmlobj.*;
+
+public class SystemUpgrade extends org.onap.portalsdk.analytics.RaptorObject {
+ private static final String upgradeFromVersion = "1.x";
+ private static final String upgradeToVersion = "2.0";
+
+/* This script upgrades the Raptor database to a newer version
+ Make sure you execute the "upgrade_v0_to_v1_0_before_java.sql" before running this
+ and "upgrade_v0_to_v1_0_after_java.sql" afterwards
+
+ URL example: http://localhost:8082/databank/dispatcher?action=raptor&r_action=system_upgrade
+*/
+ public static String upgradeDB(HttpServletRequest request) {
+ request.setAttribute("system_message", "System upgrade disabled");
+ return "raptor/blank.jsp";
+
+/* try {
+ if(upgradeFromVersion.equals("1.x")&&upgradeToVersion.equals("2.0"))
+ upgrateFromV1ToV2_0(request);
+ else
+ throw new RuntimeException("Invalid version");
+
+ return "raptor/blank.jsp";
+ } catch(Exception e) {
+ return (new ErrorHandler()).processFatalError(request, e);
+ }*/
+ } // upgradeDB
+
+ private static void upgrateFromV1ToV2_0(HttpServletRequest request) throws Exception {
+ StringBuffer log = new StringBuffer();
+ log.append("Starting upgrade...<br>\n");
+
+ DataSet ds = DbUtils.executeQuery("SELECT cr.rep_id, cr.sched_mailto_user_ids FROM cr_report cr");
+ for(int i=0; i<ds.getRowCount(); i++) {
+ String repId = ds.getString(i, 0);
+ log.append("<li>Processing report ["+repId+"]: ");
+
+ Connection connection = DbUtils.startTransaction();
+ String emailIds = nvls(ds.getString(i, 1));
+ if(emailIds.length()>0)
+ try {
+ log.append("Converting emails ");
+ StringTokenizer st = new StringTokenizer(emailIds, ",");
+ while(st.hasMoreTokens()) {
+ String userId = nvls(st.nextToken());
+ log.append(userId);
+ if(userId.length()>0)
+ DbUtils.executeUpdate(connection, "INSERT INTO cr_report_schedule_users (rep_id, user_id) VALUES ("+repId+", "+userId+")");
+ log.append("-success, ");
+ } // while
+ log.append(" <font color=green>COMPLETED</font>; ");
+ } catch(Exception e) {
+ log.append("-<font color=red>FAILED</font>; ");
+ }
+
+ String reportXML = ReportLoader.loadCustomReportXML(repId);
+ ReportDefinition rdef = ReportDefinition.unmarshal(reportXML, repId, request);
+ ReportWrapper rw = new ReportWrapper(rdef.cloneCustomReport(), repId, null, null, null, null, null, null, false);
+
+ for(Iterator iter=rw.getAllColumns().iterator(); iter.hasNext(); ) {
+ DataColumnType col = (DataColumnType) iter.next();
+ String drillDownURL = nvls(col.getDrillDownURL());
+ if(drillDownURL.startsWith("dispatcher?action=custrep.run&c_master=")) {
+ drillDownURL = AppUtils.getReportExecuteActionURL()+drillDownURL.substring("dispatcher?action=custrep.run&c_master=".length());
+ log.append("Drill-down processed; ");
+ col.setDrillDownURL(drillDownURL);
+ }
+ } // for
+
+ reportXML = rw.marshal();
+
+ /*PrintWriter xmlOut = new PrintWriter(new BufferedWriter(new FileWriter(new File(AppUtils.getTempFolderPath()+AppUtils.getUserID(request)))));
+ xmlOut.println(reportXML);
+ xmlOut.close();*/
+
+ try {
+ ReportLoader.updateCustomReportRec(connection, rw, reportXML);
+ DbUtils.commitTransaction(connection);
+ log.append("<font color=green>REPORT UPDATED</font></li>\n");
+ } catch(Exception e) {
+ log.append("<font color=red>REPORT UPDATE FAILED</font></li>\n");
+ DbUtils.rollbackTransaction(connection);
+ } finally {
+ DbUtils.clearConnection(connection);
+ }
+ } // for
+
+ log.append("<br>\nSystem upgrade successfully completed...<br>\n");
+ request.setAttribute("system_message", log.toString());
+ } // upgrateFromV1ToV2_0
+
+} // SystemUpgrade
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import org.onap.portalsdk.analytics.util.*;
+
+public class ColumnHeader extends org.onap.portalsdk.analytics.RaptorObject {
+ private String columnTitle = "";
+
+ private String columnWidth = "";
+
+ private String alignment = "center";
+
+ private int rowSpan = 1;
+
+ private int actualColSpan = 1;
+
+ private int visibleColSpan = 1;
+
+ private String linkColId = null;
+
+ private int columnSort = 0;
+
+ private String colId = "";
+
+ private int groupLevel =0;
+
+ private int startGroup = 0;
+
+ private int colSpanGroup = 0;
+
+ private boolean sortable = false;
+
+
+ public ColumnHeader() {
+ super();
+ }
+
+ public ColumnHeader(String columnTitle) {
+ this();
+ setColumnTitle(columnTitle);
+ } // ColumnHeader
+
+ public ColumnHeader(String columnTitle, Integer columnSort) {
+ this();
+ setColumnTitle(columnTitle);
+ setColumnSort(columnSort.intValue());
+ } // ColumnHeader
+
+ public ColumnHeader(String columnTitle, String columnWidth) {
+ this(columnTitle);
+ setColumnWidth(columnWidth);
+ } // ColumnHeader
+
+ public ColumnHeader(String columnTitle, String columnWidth, int colSpan) {
+ this(columnTitle, columnWidth);
+ setColSpan(colSpan);
+ } // ColumnHeader
+
+ //public ColumnHeader(String columnTitle, String columnWidth, int colSpan, String linkColId) {
+ //this(columnTitle, columnWidth, colSpan);
+ //setLinkColId(linkColId);
+ //} // ColumnHeader
+
+ public ColumnHeader(String columnTitle, String columnWidth, String alignment, int colSpan, String linkColId) {
+ this(columnTitle, columnWidth, colSpan);
+ setAlignment(alignment);
+ setLinkColId(linkColId);
+ } // ColumnHeader
+
+ public ColumnHeader(String columnTitle, String columnWidth, int colSpan, int rowSpan) {
+ this(columnTitle, columnWidth, colSpan);
+ setRowSpan(rowSpan);
+ } // ColumnHeader
+
+ public String getColumnTitle() {
+ return columnTitle;
+ }
+
+ public String getColumnWidth() {
+ return columnWidth;
+ }
+
+ public int getRowSpan() {
+ return rowSpan;
+ }
+
+ public int getColSpan() {
+ return actualColSpan;
+ }
+
+ public boolean isVisible() {
+ return (visibleColSpan > 0) && (rowSpan > 0);
+ }
+
+ public String getLinkColId() {
+ return linkColId;
+ }
+
+ public void setColumnTitle(String columnTitle) {
+ this.columnTitle = nvl(columnTitle);
+ }
+
+ public void setColumnWidth(String columnWidth) {
+ this.columnWidth = columnWidth;
+ }
+
+ public void setLinkColId(String linkColId) {
+ this.linkColId = linkColId;
+ }
+
+ public void setRowSpan(int rowSpan) {
+ this.rowSpan = rowSpan;
+ }
+
+ public void setColSpan(int colSpan) {
+ this.visibleColSpan = colSpan;
+ this.actualColSpan = colSpan;
+ }
+
+ public void setVisible(boolean visible) {
+ if (visible) {
+ if (visibleColSpan < actualColSpan)
+ visibleColSpan++;
+ } else {
+ if (visibleColSpan > 0)
+ visibleColSpan--;
+ }
+ } // setVisible
+
+ public String getColumnWidthHtml() {
+ return (columnWidth.length() == 0) ? "" : (" width=" + columnWidth);
+ }
+
+ public String getRowSpanHtml() {
+ return (rowSpan == 1) ? "" : (" rowspan=" + rowSpan);
+ }
+
+ public String getColSpanHtml() {
+ return (visibleColSpan == 1) ? "" : (" colspan=" + visibleColSpan);
+ }
+
+ public String getColumnTitleHtml() {
+ if (linkColId == null)
+ return (columnTitle.length() == 0) ? " " : columnTitle;
+ else
+ return "<a href=\"javascript:performSortBy('" + linkColId
+ + "')\" title=\"Sort by column " + columnTitle + "\" class=rcolheader>"
+ + ((columnTitle.length() == 0) ? "[NULL]" : columnTitle) + "</a>";
+ } // getColumnTitleHtml
+
+ /**
+ * @return the columnSort
+ */
+ public int getColumnSort() {
+ return columnSort;
+ }
+
+ /**
+ * @param columnSort the columnSort to set
+ */
+ public void setColumnSort(int columnSort) {
+ this.columnSort = columnSort;
+ }
+
+ /**
+ * @return the colId
+ */
+ public String getColId() {
+ return colId;
+ }
+
+ /**
+ * @param colId the colId to set
+ */
+ public void setColId(String colId) {
+ this.colId = colId;
+ }
+
+ public String getAlignment() {
+ return alignment;
+ }
+
+ public void setAlignment(String alignment) {
+ if(nvl(alignment).length()>0)
+ this.alignment = alignment;
+ }
+
+ public int getGroupLevel() {
+ return groupLevel;
+ }
+
+ public void setGroupLevel(int groupLevel) {
+ this.groupLevel = groupLevel;
+ }
+
+ public int getStartGroup() {
+ return startGroup;
+ }
+
+ public void setStartGroup(int startGroup) {
+ this.startGroup = startGroup;
+ }
+
+ public int getColSpanGroup() {
+ return colSpanGroup;
+ }
+
+ public void setColSpanGroup(int colSpanGroup) {
+ this.colSpanGroup = colSpanGroup;
+ }
+
+ public boolean isSortable() {
+ return sortable;
+ }
+
+ public void setSortable(boolean sortable) {
+ this.sortable = sortable;
+ }
+
+
+
+} // ColumnHeader
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.util.*;
+
+public class ColumnHeaderRow extends Vector {
+ private String rowHeight = "";
+
+ private String displayWidth = "";
+
+ private String alignment = "center";
+
+ 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 ColumnHeader getNext() {
+ return hasNext() ? getColumnHeader(nextElemIdx++) : null;
+ } // getNext
+
+ public ColumnHeader getColumnHeader(int idx) {
+ return (ColumnHeader) get(idx);
+ } // getColumnHeader
+
+ public void addColumnHeader(ColumnHeader columnHeader) {
+ add(columnHeader);
+ } // addColumnHeader
+
+ public void addColumnHeader(int idx, ColumnHeader columnHeader) {
+ add(idx, columnHeader);
+ } // addColumnHeader
+
+ public String getRowHeightHtml() {
+ return (rowHeight.length() == 0) ? "" : (" height=" + rowHeight);
+ }
+
+ public String getRowHeight() {
+ return rowHeight;
+ }
+
+ public void setRowHeight(String rowHeight) {
+ this.rowHeight = nvl(rowHeight);
+ }
+
+ public void setDisplayWidth(String displayWidth) {
+ this.displayWidth = nvl(displayWidth);
+ }
+
+ public String getDisplayWidth() {
+ return this.displayWidth;
+ }
+ /** ************************************************************************************************* */
+
+ private String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ private String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+ public String getAlignment() {
+ return alignment;
+ }
+
+ public void setAlignment(String alignment) {
+ if(nvl(alignment).length()>0)
+ this.alignment = alignment;
+ }
+
+} // ColumnHeaderRow
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import org.onap.portalsdk.analytics.RaptorObject;
+
+public class ColumnVisual extends RaptorObject {
+ private String colId = null;
+
+ private String colDisplay = null;
+
+ private boolean visible = true;
+
+ private String sortType = null;
+
+ public ColumnVisual(String colId, String colDisplay, boolean visible, String sortType) {
+ super();
+
+ setColId(colId);
+ setColDisplay(colDisplay);
+ setVisible(visible);
+ setSortType(sortType);
+ } // ColumnVisual
+
+ public String getColId() {
+ return colId;
+ }
+
+ public String getColDisplay() {
+ return colDisplay;
+ }
+
+ public boolean isVisible() {
+ return visible;
+ }
+
+ public String getSortType() {
+ return sortType;
+ }
+
+ public void setColId(String colId) {
+ this.colId = colId;
+ }
+
+ public void setColDisplay(String colDisplay) {
+ this.colDisplay = colDisplay;
+ }
+
+ public void setVisible(boolean visible) {
+ this.visible = visible;
+ }
+
+ public void setSortType(String sortType) {
+ this.sortType = sortType;
+ }
+
+} // ColumnVisual
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.error.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+
+public class CrossTabColumnValues extends org.onap.portalsdk.analytics.RaptorObject {
+ private String colId = null;
+
+ private Vector columnValues = null;
+
+ public CrossTabColumnValues(String colId, String loadValuesSQL, String dbInfo)
+ throws RaptorException {
+ this.colId = colId;
+ DataSet ds = ConnectionUtils.getDataSet(loadValuesSQL, dbInfo);
+ // DataSet ds = DbUtils.executeQuery(loadValuesSQL);
+ columnValues = new Vector(ds.getRowCount());
+ for (int i = 0; i < ds.getRowCount(); i++)
+ columnValues.add(ds.getString(i, 0));
+ } // CrossTabColumnValues
+
+ public String getColId() {
+ return colId;
+ }
+
+ public Vector getColumnValues() {
+ return columnValues;
+ }
+
+ public int getValuesCount() {
+ return columnValues.size();
+ }
+
+ public String getValueAt(int idx) {
+ return (String) columnValues.get(idx);
+ }
+
+ public int getIndexOf(String value) {
+ for (int i = 0; i < getValuesCount(); i++)
+ if (value.equals(getValueAt(i)))
+ return i;
+
+ return -1;
+ } // getIndexOf
+
+ public int getIndexOf(int value) {
+ for (int i = 0; i < getValuesCount(); i++)
+ if (value == new Integer(getValueAt(i)).intValue())
+ return i;
+
+ return -1;
+ } // getIndexOf
+
+} // CrossTabColumnValues
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import java.util.*;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.analytics.RaptorObject;
+import org.onap.portalsdk.analytics.error.*;
+import org.onap.portalsdk.analytics.model.runtime.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+import org.onap.portalsdk.analytics.xmlobj.*;
+
+public class CrossTabOrderManager extends RaptorObject {
+ private Vector colHeaderValues = null;
+
+ private Vector rowHeaderValues = null;
+
+
+ public CrossTabOrderManager(ReportRuntime rr, String userId,HttpServletRequest request) throws RaptorException {
+ colHeaderValues = new Vector();
+ rowHeaderValues = new Vector();
+
+ for (Iterator iter = rr.getAllColumns().iterator(); iter.hasNext();) {
+ DataColumnType dct = (DataColumnType) iter.next();
+ if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_COLUMN)) {
+ if(rr.getColumnById(dct.getColId()+"_sort")!=null) {
+ dct = rr.getColumnById(dct.getColId()+"_sort");
+ colHeaderValues.add(new CrossTabColumnValues(dct.getColId(), rr
+ .generateDistinctValuesSQL(dct, userId,request), rr.getDbInfo()));
+ } else
+ colHeaderValues.add(new CrossTabColumnValues(dct.getColId(), rr
+ .generateDistinctValuesSQL(dct, userId,request), rr.getDbInfo()));
+ }
+ else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_ROW))
+ rowHeaderValues.add(new CrossTabColumnValues(dct.getColId(), rr
+ .generateDistinctValuesSQL(dct, userId,request), rr.getDbInfo()));
+ else if (nvl(dct.getCrossTabValue()).trim().length()<=0)
+ rowHeaderValues.add(new CrossTabColumnValues(dct.getColId(), rr
+ .generateDistinctValuesSQL(dct, userId,request), rr.getDbInfo()));
+ } // for
+ } // CrossTabOrderManager
+
+ public int getIndexOfColHeaderValue(int colIdx, String value) {
+ return ((CrossTabColumnValues) colHeaderValues.get(colIdx)).getIndexOf(value);
+ } // getIndexOfColHeaderValue
+
+ public int getIndexOfColHeaderValue(int colIdx, int value) {
+ return ((CrossTabColumnValues) colHeaderValues.get(colIdx)).getIndexOf(value);
+ } // getIndexOfColHeaderValue
+
+ public boolean isAfterColHeaderValue(int colIdx, String curValue, String newValue) {
+ return (getIndexOfColHeaderValue(colIdx, curValue) > getIndexOfColHeaderValue(colIdx,
+ newValue));
+ } // isBeforeColHeaderValue
+
+ public boolean isAfterColHeaderValue(int colIdx, int curValue, Integer newValue) {
+ return (getIndexOfColHeaderValue(colIdx, curValue) > getIndexOfColHeaderValue(colIdx,
+ newValue.intValue()));
+ } // isBeforeColHeaderValue
+
+ public int getIndexOfRowHeaderValue(int rowIdx, String value) {
+ return ((CrossTabColumnValues) rowHeaderValues.get(rowIdx)).getIndexOf(value);
+ } // getIndexOfRowHeaderValue
+
+ public boolean isAfterRowHeaderValue(int rowIdx, String curValue, String newValue) {
+ return (getIndexOfRowHeaderValue(rowIdx, curValue) > getIndexOfRowHeaderValue(rowIdx,
+ newValue));
+ } // isBeforeRowHeaderValue
+
+ public Vector getRowHeaderValues() {
+ return rowHeaderValues;
+ }
+
+ public void setRowHeaderValues(Vector rowHeaderValues) {
+ this.rowHeaderValues = rowHeaderValues;
+ }
+
+} // CrossTabOrderManager
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import java.util.*;
+
+public class CrossTabTotalValue extends org.onap.portalsdk.analytics.RaptorObject {
+ private Vector headerValues = null;
+
+ private String totalValue = null;
+
+ public CrossTabTotalValue() {
+ super();
+ }
+
+ public CrossTabTotalValue(Vector headerValues, String totalValue) {
+ this();
+
+ setHeaderValues(headerValues);
+ setTotalValue(totalValue);
+ } // CrossTabTotalValue
+
+ public Vector getHeaderValues() {
+ return headerValues;
+ }
+
+ public String getTotalValue() {
+ return totalValue;
+ }
+
+ public void setHeaderValues(Vector headerValues) {
+ this.headerValues = headerValues;
+ }
+
+ public void setTotalValue(String totalValue) {
+ this.totalValue = totalValue;
+ }
+
+} // CrossTabTotalValue
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import java.util.*;
+
+public class DataRow/* extends Vector*/ {
+
+ private ArrayList dataValueList = new ArrayList();
+ private HtmlFormatter rowFormatter = null;
+
+ private int nextElemIdx = 0;
+
+ private boolean rowFormat = false;
+
+ private String formatId = null;
+
+ private int rowNum = -1;
+
+ private Vector<DataValue> rowValues;
+
+ /**
+ * @return the rowNum
+ */
+ public int getRowNum() {
+ return rowNum;
+ }
+
+
+ /**
+ * @param rowNum the rowNum to set
+ * Used for crosstab
+ */
+ public void setRowNum(int rowNum) {
+ this.rowNum = rowNum;
+ }
+
+
+ public String getFormatId() {
+ return formatId;
+ }
+
+
+ public void setFormatId(String formatId) {
+ this.formatId = formatId;
+ }
+
+
+ public void resetNext() {
+ resetNext(0);
+ } // resetNext
+
+ public void resetNext(int toPos) {
+ nextElemIdx = toPos;
+ } // resetNext
+
+ public boolean hasNext() {
+ return (nextElemIdx < dataValueList.size());
+ } // hasNext
+
+ public DataValue getNext() {
+ return hasNext() ? getDataValue(nextElemIdx++) : null;
+ } // getNext
+
+ public DataValue getDataValue(int idx) {
+ return (DataValue) dataValueList.get(idx);
+ } // getRowHeader
+
+ public void addDataValue(DataValue dataValue) {
+ if (rowFormatter != null)
+ dataValue.setRowFormatter(rowFormatter);
+ dataValueList.add(dataValue);
+ } // addDataValue
+
+ public void addDataValue(int idx, DataValue dataValue) {
+ if (rowFormatter != null)
+ dataValue.setRowFormatter(rowFormatter);
+ dataValueList.add(idx, dataValue);
+ } // addDataValue
+
+ public void setDataValue(int idx, DataValue dataValue) {
+ if (rowFormatter != null)
+ dataValue.setRowFormatter(rowFormatter);
+ dataValueList.set(idx, dataValue);
+ } // addDataValue
+
+ public HtmlFormatter getRowFormatter() {
+ return rowFormatter;
+ }
+
+ public void setRowFormat(boolean b) {
+ rowFormat = b;
+ }
+ public boolean isRowFormat() {
+ return rowFormat;
+ }
+
+ public void setRowFormatter(HtmlFormatter rowFormatter) {
+ this.rowFormatter = rowFormatter;
+
+ for (int i = 0; i < dataValueList.size(); i++)
+ ((DataValue) dataValueList.get(i)).setRowFormatter(rowFormatter);
+ } // setRowFormatter
+
+ public String getBgColorHtml() {
+ if (rowFormatter != null && rowFormatter.getBgColor().length() > 0)
+ return " bgcolor=" + rowFormatter.getBgColor();
+ else
+ return "";
+ } // getBgColorHtml
+
+ public String getDataValue(String colId) {
+ String v_ColId = "";
+ for (int i = 0; i < dataValueList.size(); i++) {
+ v_ColId = ((DataValue) dataValueList.get(i)).getColId();
+ if(v_ColId.equals(colId)) {
+ return ((DataValue) dataValueList.get(i)).getDisplayValue();
+ }
+ }
+ return null;
+
+ }
+
+
+ /**
+ * @return the dataValueList
+ */
+ public ArrayList getDataValueList() {
+ return dataValueList;
+ }
+
+
+ /**
+ * @param dataValueList the dataValueList to set
+ */
+ public void setDataValueList(ArrayList dataValueList) {
+ this.dataValueList = dataValueList;
+ }
+
+
+ public Vector<DataValue> getRowValues() {
+ return rowValues;
+ }
+
+
+ public void setRowValues(Vector<DataValue> rowValues) {
+ this.rowValues = rowValues;
+ }
+
+} // DataRow
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import org.onap.portalsdk.analytics.util.*;
+
+public class DataValue extends org.onap.portalsdk.analytics.RaptorObject {
+ private String displayValue = "";
+
+ private String displayCalculatedValue = "";
+
+ private String drillDownURL = null;
+
+ private boolean drillDowninPoPUp = false;
+
+ private String indentation = "";
+
+ private String alignment = "Left";
+
+ private boolean visible = true;
+
+ private boolean hidden = false;
+
+ private boolean bold = false;
+
+ private HtmlFormatter cellFormatter = null;
+
+ private HtmlFormatter rowFormatter = null;
+
+ private String formatId = null;
+
+ private boolean cellFormat = false;
+
+ private String colId = null;
+
+ private String displayTotal = null;
+
+ private String colName = null;
+
+ private String displayName = null;
+
+ private String nowrap = "False";
+
+ private String hyperlinkURL = "";
+
+ private String displayType = "";
+
+ private String actionImg = "";
+
+
+ public String getColName() {
+
+ return colName;
+ }
+
+
+ public void setColName(String colName) {
+
+ this.colName = colName;
+ }
+
+ public DataValue() {
+ super();
+ }
+
+ public String getFormatId() {
+ return formatId;
+ }
+
+
+ public void setFormatId(String formatId) {
+ this.formatId = formatId;
+ }
+
+ public void setCellFormat(boolean b) {
+ cellFormat = b;
+ }
+ public boolean isCellFormat() {
+ return cellFormat;
+ }
+
+ public String getDisplayValue() {
+ return displayValue;
+ }
+
+ public String getDrillDownURL() {
+ return drillDownURL;
+ }
+
+ public String getAlignment() {
+ return alignment;
+ }
+
+ public boolean isVisible() {
+ return visible;
+ }
+
+ public boolean isBold() {
+ return bold;
+ }
+
+ public HtmlFormatter getCellFormatter() {
+ return cellFormatter;
+ }
+
+ public HtmlFormatter getRowFormatter() {
+ return rowFormatter;
+ }
+
+ public void setDisplayValue(String displayValue) {
+ this.displayValue = nvl(displayValue);
+ }
+
+ public void setDrillDownURL(String drillDownURL) {
+ this.drillDownURL = drillDownURL;
+ }
+
+ public void setAlignment(String alignment) {
+ this.alignment = alignment;
+ }
+
+ public void setVisible(boolean visible) {
+ this.visible = visible;
+ }
+
+ public void setBold(boolean bold) {
+ this.bold = bold;
+ }
+
+ public void setCellFormatter(HtmlFormatter cellFormatter) {
+ this.cellFormatter = cellFormatter;
+ }
+
+ public void setRowFormatter(HtmlFormatter rowFormatter) {
+ this.rowFormatter = rowFormatter;
+ }
+
+ private String getFormattedValue(String value) {
+ value = nvl(value.trim()).length()<=0 ? " ":value;
+ if (cellFormatter != null)
+ return cellFormatter.formatValue(value);
+ else if (rowFormatter != null)
+ return rowFormatter.formatValue(value);
+ else
+ return value;
+ } // getFormattedValue
+
+ private String getFormattedLink(String value) {
+ if (cellFormatter != null)
+ return cellFormatter.formatLink(value, drillDownURL, isDrillDowninPoPUp());
+ else if (rowFormatter != null)
+ return rowFormatter.formatLink(value, drillDownURL, isDrillDowninPoPUp());
+ else {
+ if(!isDrillDowninPoPUp()) {
+ return "<a href=\"" + drillDownURL + "\">" + value + "</a>";
+ } else {
+ return "<a href=\"#\" onClick=\"showDrillDownInPopup('" + drillDownURL + "&noFormFields=Y&isEmbedded=Y&show_back_btn=N"+ "')\">" + value + "</a>";
+ }
+
+ }
+ } // getFormattedValue
+
+ private String getValueHtml() {
+ return (nvl(displayValue).trim().length() == 0) ? " " : displayValue;
+ }
+
+ public String getDisplayValueHtml() {
+ return getFormattedValue(getValueHtml());
+ }
+
+ public String getDisplayValueLinkHtml() {
+ if (nvl(drillDownURL).length() == 0)
+ return getDisplayValueHtml();
+ else
+ return getFormattedLink(getValueHtml());
+ // return getFormattedValue("<a
+ // href=\""+drillDownURL+"\">"+getValueHtml()+"</a>");
+ } // getDisplayValueLinkHtml
+
+ public String getAlignmentHtml() {
+ if (cellFormatter != null && cellFormatter.getAlignment().length() > 0)
+ return " align=" + cellFormatter.getAlignment();
+ else if (rowFormatter != null && rowFormatter.getAlignment().length() > 0)
+ return " align=" + rowFormatter.getAlignment();
+ else
+ return (alignment.length() == 0) ? "" : (" align=" + alignment);
+ } // getAlignmentHtml
+
+ public String getBgColorHtml() {
+ if (cellFormatter != null && cellFormatter.getBgColor().length() > 0)
+ return " bgcolor=" + cellFormatter.getBgColor();
+ else if (rowFormatter != null && rowFormatter.getBgColor().length() > 0)
+ return " bgcolor=" + rowFormatter.getBgColor();
+ else
+ return "";
+ } // getBgColorHtml
+
+
+ public String getColId() {
+
+ return colId;
+ }
+
+
+ public void setColId(String colId) {
+
+ this.colId = colId;
+ }
+
+
+ public String getDisplayTotal() {
+
+ return displayTotal;
+ }
+
+
+ public void setDisplayTotal(String displayTotal) {
+
+ this.displayTotal = displayTotal;
+ }
+
+
+
+ public String getDisplayName() {
+
+ return displayName;
+ }
+
+
+
+ public void setDisplayName(String displayName) {
+
+ this.displayName = displayName;
+ }
+
+
+ public boolean isHidden() {
+ return hidden;
+ }
+
+
+ public void setHidden(boolean hidden) {
+ this.hidden = hidden;
+ }
+
+ public String getNowrap() {
+ return nowrap;
+ }
+
+
+ public void setNowrap(String nowrap) {
+ this.nowrap = nowrap;
+ }
+
+ public boolean isDrillDowninPoPUp() {
+ return drillDowninPoPUp;
+ }
+
+
+ public void setDrillDowninPoPUp(boolean drillDowninPoPUp) {
+ this.drillDowninPoPUp = drillDowninPoPUp;
+ }
+
+
+ /**
+ * @return the displayCalculatedValue
+ */
+ public String getDisplayCalculatedValue() {
+ return displayCalculatedValue;
+ }
+
+
+ /**
+ * @param displayCalculatedValue the displayCalculatedValue to set
+ */
+ public void setDisplayCalculatedValue(String displayCalculatedValue) {
+ this.displayCalculatedValue = displayCalculatedValue;
+ }
+
+
+ /**
+ * @return the indentation
+ */
+ public String getIndentation() {
+ return indentation;
+ }
+
+
+ /**
+ * @param indentation the indentation to set
+ */
+ public void setIndentation(String indentation) {
+ this.indentation = indentation;
+ }
+
+
+ /**
+ * @return the hyperlinkURL
+ */
+ public String getHyperlinkURL() {
+ return hyperlinkURL;
+ }
+
+
+ /**
+ * @param hyperlinkURL the hyperlinkURL to set
+ */
+ public void setHyperlinkURL(String hyperlinkURL) {
+ this.hyperlinkURL = hyperlinkURL;
+ }
+
+
+ /**
+ * @return the displayType
+ */
+ public String getDisplayType() {
+ return displayType;
+ }
+
+
+ /**
+ * @param displayType the displayType to set
+ */
+ public void setDisplayType(String displayType) {
+ this.displayType = displayType;
+ }
+
+
+ /**
+ * @return the actionImg
+ */
+ public String getActionImg() {
+ return actionImg;
+ }
+
+
+ /**
+ * @param actionImg the actionImg to set
+ */
+ public void setActionImg(String actionImg) {
+ this.actionImg = actionImg;
+ }
+
+} // DataValue
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import org.onap.portalsdk.analytics.RaptorObject;
+
+public class HtmlFormatter extends RaptorObject {
+ private boolean bold = false;
+
+ private boolean italic = false;
+
+ private boolean underline = false;
+
+ private String bgColor = "";
+
+ private String fontColor = "";
+
+ private String fontFace = "";
+
+ private String fontSize = "";
+
+ private String alignment = "";
+
+ private String formatId = "";
+
+ public HtmlFormatter() {
+ super();
+ }
+
+ public HtmlFormatter(boolean bold, boolean italic, boolean underline, String bgColor,
+ String fontColor, String fontFace, String fontSize) {
+ this();
+
+ setBold(bold);
+ setItalic(italic);
+ setUnderline(underline);
+ setBgColor(bgColor);
+ setFontColor(fontColor);
+ setFontFace(fontFace);
+ setFontSize(fontSize);
+ } // HtmlFormatter
+
+ public HtmlFormatter(boolean bold, boolean italic, boolean underline, String bgColor,
+ String fontColor, String fontFace, String fontSize, String alignment) {
+ this(bold, italic, underline, bgColor, fontColor, fontFace, fontSize);
+ setAlignment(alignment);
+ } // HtmlFormatter
+
+ public boolean isBold() {
+ return bold;
+ }
+
+ public boolean isItalic() {
+ return italic;
+ }
+
+ public boolean isUnderline() {
+ return underline;
+ }
+
+ public String getBgColor() {
+ return bgColor;
+ }
+
+ public String getFontColor() {
+ return fontColor;
+ }
+
+ public String getFontFace() {
+ return fontFace;
+ }
+
+ public String getFontSize() {
+ return fontSize;
+ }
+
+ public String getAlignment() {
+ return alignment;
+ }
+
+ public void setBold(boolean bold) {
+ this.bold = bold;
+ }
+
+ public void setItalic(boolean italic) {
+ this.italic = italic;
+ }
+
+ public void setUnderline(boolean underline) {
+ this.underline = underline;
+ }
+
+ public void setBgColor(String bgColor) {
+ this.bgColor = nvl(bgColor);
+ }
+
+ public void setFontColor(String fontColor) {
+ this.fontColor = nvl(fontColor);
+ }
+
+ public void setFontFace(String fontFace) {
+ this.fontFace = nvl(fontFace);
+ }
+
+ public void setFontSize(String fontSize) {
+ this.fontSize = nvl(fontSize);
+ }
+
+ public void setAlignment(String alignment) {
+ this.alignment = nvl(alignment);
+ }
+
+ private String generateStyleHtml() {
+ StringBuffer sb = new StringBuffer();
+
+ if (isBold())
+ sb.append("font-weight:bold;");
+ if (isItalic())
+ sb.append("font-style:italic;");
+ if (isUnderline())
+ sb.append("text-decoration:underline;");
+ // if(getBgColor().length()>0)
+ // sb.append("background-color:"+getBgColor()+";");
+ if (getFontColor().length() > 0)
+ sb.append("color:" + getFontColor() + ";");
+ if (getFontFace().length() > 0)
+ sb.append("font-family:" + getFontFace() + ";");
+ if (getFontSize().length() > 0)
+ sb.append("font-size:" + getFontSize() + "px;");
+ if (getAlignment().length() > 0)
+ sb.append("text-align:" + getAlignment() + ";");
+
+ if (sb.length() > 0) {
+ sb.insert(0, " style=\"");
+ sb.append("\"");
+ } // if
+
+ return sb.toString();
+ } // generateStyleHtml
+
+ public String generateStyleForZK() {
+ StringBuffer sb = new StringBuffer();
+
+ if (isBold())
+ sb.append("font-weight:bold;");
+ if (isItalic())
+ sb.append("font-style:italic;");
+ if (isUnderline())
+ sb.append("text-decoration:underline;");
+ // if(getBgColor().length()>0)
+ // sb.append("background-color:"+getBgColor()+";");
+ if (getFontColor().length() > 0)
+ sb.append("color:" + getFontColor() + ";");
+ if (getFontFace().length() > 0)
+ sb.append("font-family:" + getFontFace() + ";");
+ if (getFontSize().length() > 0)
+ sb.append("font-size:" + getFontSize() + "px;");
+ if (getAlignment().length() > 0)
+ sb.append("text-align:" + getAlignment() + ";");
+
+ return sb.toString();
+ } // generateStyleHtml
+
+ public String formatValue(String value) {
+ String style = generateStyleHtml();
+ if (style.length() > 0)
+ return "<font" + style + ">" + value + "</font>";
+ else
+ return value;
+ } // formatValue
+
+ public String formatLink(String value, String url, boolean drillDowninPoPUp) {
+ if(!drillDowninPoPUp) {
+ return "<a href=\"" + url + "\"" + generateStyleHtml() + ">" + value + "</a>";
+ } else {
+ return "<a href=\"#\" onClick=\"showDrillDownInPopup('" + url + "&noFormFields=Y&isEmbedded=Y&show_back_btn=N"+ "')\"" + generateStyleHtml() + ">" + value + "</a>";
+ }
+ } // formatLink
+
+ public String getFormatId() {
+ return formatId;
+ }
+
+ public void setFormatId(String formatId) {
+ this.formatId = formatId;
+ }
+
+} // HtmlFormatter
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import java.util.*;
+
+public class ReportColumnHeaderRows extends Vector {
+ 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 ColumnHeaderRow getNext() {
+ return hasNext() ? getColumnHeaderRow(nextElemIdx++) : null;
+ } // getNext
+
+ public ColumnHeader getColumnHeader(int rowIdx, int colIdx) {
+ return getColumnHeaderRow(rowIdx).getColumnHeader(colIdx);
+ } // getColumnHeader
+
+ public ColumnHeaderRow getColumnHeaderRow(int idx) {
+ return (ColumnHeaderRow) get(idx);
+ } // getColumnHeaderRow
+
+ public void addColumnHeaderRow(ColumnHeaderRow columnHeaderRow) {
+ add(columnHeaderRow);
+ } // addColumnHeaderRow
+
+ public void addColumnHeaderRow(int idx, ColumnHeaderRow columnHeaderRow) {
+ add(idx, columnHeaderRow);
+ } // addColumnHeaderRow
+
+ public int getRowCount() {
+ return size();
+ } // getRowCount
+
+ public int getColumnCount() {
+ int cSize = 0;
+ if (getRowCount() > 0)
+ cSize = getColumnHeaderRow(getRowCount() - 1).size();
+
+ return cSize;
+ } // getColumnCount
+
+} // ReportColumnHeaderRows
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import java.io.Serializable;
+import java.util.*;
+
+import org.onap.portalsdk.analytics.model.runtime.*;
+import org.onap.portalsdk.analytics.system.*;
+import org.onap.portalsdk.analytics.util.*;
+import org.onap.portalsdk.analytics.xmlobj.*;
+
+public class ReportData extends org.onap.portalsdk.analytics.RaptorObject implements Serializable {
+ // private static final boolean sortData = true; // sort cross-tab data by
+ // row/col name while being added
+ private static final int MAX_NUM_COLS = 150; // -1 => no restriction
+
+ private int pageNo = -1;
+
+ private int pageSetNo = -1;
+
+ public ReportColumnHeaderRows reportColumnHeaderRows = null;
+
+ public ReportRowHeaderCols reportRowHeaderCols = null;
+
+ public ReportDataRows reportDataRows = null;
+
+ public ReportDataRows reportDataTotalRow = null;
+
+ public ReportRowHeaderCols reportTotalRowHeaderCols = null;
+
+ public List reportDataList = null;
+
+ private boolean canSortAtRuntime = false;
+
+ private Vector columnVisuals = null; // Contains actual column Ids for
+ // linear or last header col values
+ // for cross-tab
+
+ public ReportData(int pageNo, boolean canSortAtRuntime) {
+ super();
+
+ this.pageNo = pageNo;
+ this.canSortAtRuntime = canSortAtRuntime;
+
+ reportColumnHeaderRows = new ReportColumnHeaderRows();
+ reportRowHeaderCols = new ReportRowHeaderCols();
+ reportDataRows = new ReportDataRows();
+
+ columnVisuals = new Vector();
+ } // ReportData
+
+ public int getPageNo() {
+ return pageNo;
+ } // pageNo
+
+ public int getPageSetNo() {
+ return pageSetNo;
+ } // pageSetNo
+
+ public int getHeaderRowCount() {
+ return reportColumnHeaderRows.getRowCount();
+ } // getHeaderRowCount
+
+ public int getDataRowCount() {
+ if(reportDataRows!=null && reportDataRows.getRowCount()>0)
+ return reportDataRows.getRowCount();
+ else if(getReportDataList()!=null)
+ return getReportDataList().size();
+ else
+ return 0;
+ } // getDataRowCount
+
+ public int getTotalRowCount() {
+ return getHeaderRowCount() + getDataRowCount();
+ } // getTotalRowCount
+
+ public int getHeaderColumnCount() {
+ return reportRowHeaderCols.getColumnCount();
+ } // getHeaderColumnCount
+
+ public int getDataColumnCount() {
+ int cCount = reportDataRows.getColumnCount();
+ if (cCount == 0)
+ cCount = reportColumnHeaderRows.getColumnCount();
+
+ return cCount;
+ } // getDataColumnCount
+
+ public int getTotalColumnCount() {
+ return getHeaderColumnCount() + getDataColumnCount();
+ } // getTotalColumnCount
+
+ // Cross-tab data section
+ private void insertColumn(int colIdx, Vector colNameValues, Vector colNameSortValues, List dataList, String alignment) {
+ int r = 0;
+ for (reportColumnHeaderRows.resetNext(); reportColumnHeaderRows.hasNext();) {
+ ColumnHeaderRow chr = reportColumnHeaderRows.getNext();
+ if(colNameSortValues!=null) {
+ ColumnHeader ch = new ColumnHeader(((DataValue) colNameValues.get(r)).getDisplayValue(), Integer.valueOf(((DataValue)colNameSortValues.get(r)).getDisplayValue()) );
+ ch.setColumnWidth(chr.getDisplayWidth());
+ ch.setAlignment(alignment);
+ chr.addColumnHeader(colIdx, ch);
+ }
+ else {
+ ColumnHeader ch = new ColumnHeader(((DataValue) colNameValues.get(r)).getDisplayValue());
+ ch.setColumnWidth(chr.getDisplayWidth());
+ ch.setAlignment(alignment);
+ chr.addColumnHeader(colIdx, ch);
+ }
+ r++;
+ } // for
+
+/* for (reportDataRows.resetNext(); reportDataRows.hasNext();) {
+ DataRow dr = reportDataRows.getNext();
+ dr.addDataValue(colIdx, new DataValue());
+ } // for
+ */
+ for(int j = 0; j < dataList.size(); j++) {
+ DataRow dr = (DataRow) dataList.get(j);
+ dr.addDataValue(colIdx, new DataValue());
+ }
+ } // insertColumn
+
+ private boolean prevColNamesChanged(int colIdx, Vector prevColNames) {
+ for (int k = 0; k < prevColNames.size(); k++)
+ if (!nvl((String) prevColNames.get(k)).equals(
+ reportColumnHeaderRows.getColumnHeader(k, colIdx).getColumnTitle()))
+ return true;
+
+ return false;
+ } // prevColNamesChanged
+
+ private int findColumnIdx(Vector colNameValues, Vector colNameSortValues, CrossTabOrderManager crossTabOrderManager,
+ boolean createIfMissing, List dataList) {
+ int colIdx = 0;
+ try {
+
+ boolean nameFound = false;
+ // String prevColName = null;
+ Vector prevColNames = new Vector();
+ int columnSort = -1;
+ for (int r = 0; r < colNameValues.size(); r++) {
+ //String colName = (String) colNameValues.get(r);
+ String colName = ((DataValue) colNameValues.get(r)).getDisplayValue();
+ Integer colSortName = null;
+ if(colNameSortValues!=null)
+ colSortName = Integer.valueOf(((DataValue)colNameSortValues.get(r)).getDisplayValue());
+ ColumnHeaderRow chr = reportColumnHeaderRows.getColumnHeaderRow(r);
+
+ chr.resetNext(colIdx);
+ nameFound = false;
+ boolean posFound = false;
+ while ((!nameFound) && (!posFound) && chr.hasNext()) {
+ ColumnHeader ch = chr.getNext();
+ columnSort = ch.getColumnSort();
+ if (colName.equals(ch.getColumnTitle())) {
+ if (prevColNamesChanged(colIdx, prevColNames))
+ posFound = true;
+ else
+ nameFound = true;
+ } else if (crossTabOrderManager != null) {
+ if( colNameSortValues!=null && crossTabOrderManager.isAfterColHeaderValue(r, columnSort,
+ colSortName))
+ posFound = true;
+ else if (colNameSortValues == null && crossTabOrderManager.isAfterColHeaderValue(r, ch.getColumnTitle(),
+ colName)) {
+ posFound = true;
+ }
+ }
+ else if (crossTabOrderManager == null) {
+ if( colNameSortValues!=null && colSortName.compareTo(ch.getColumnSort()) < 0)
+ posFound = true;
+ else if (colNameSortValues==null && colName.compareTo(ch.getColumnTitle()) < 0)
+ posFound = true;
+ }
+ else // if(prevColName!=null&&(!
+ // prevColName.equals(reportColumnHeaderRows.getColumnHeader(r-1,
+ // colIdx).getColumnTitle())))
+ if (prevColNamesChanged(colIdx, prevColNames))
+ posFound = true;
+
+ if ((!nameFound) && (!posFound))
+ colIdx++;
+ } // while
+
+ if (!nameFound)
+ if (createIfMissing && (MAX_NUM_COLS >= 0) && (colIdx <= MAX_NUM_COLS)) {
+ insertColumn(colIdx, colNameValues, colNameSortValues, dataList, chr.getAlignment());
+ return colIdx;
+ } else
+ return -1;
+
+ prevColNames.add(r, colName);
+ } // for
+ if (!nameFound)
+ if (createIfMissing && (MAX_NUM_COLS >= 0) && (colIdx <= MAX_NUM_COLS))
+ insertColumn(colIdx, colNameValues, colNameSortValues, dataList, "center");
+ else
+ return -1;
+ } catch (Exception ex) {ex.printStackTrace();}
+
+ return colIdx;
+ } // findColumnIdx
+
+ private void insertRow(int rowIdx, Vector rowNameValues, List dataList, CrossTabOrderManager crossTabOrderManager) {
+ int c = 0;
+ DataRow dr = new DataRow();
+ int dataRowIdx = 0;
+ for (reportRowHeaderCols.resetNext(); reportRowHeaderCols.hasNext();) {
+ if((c+1)==reportRowHeaderCols.size()) {
+ dataRowIdx = crossTabOrderManager.getIndexOfRowHeaderValue(c, ((DataValue) rowNameValues.get(c)).getDisplayValue());
+ }
+ RowHeaderCol rhc = reportRowHeaderCols.getNext();
+ rhc.addRowHeader(rowIdx, new RowHeader(((DataValue) rowNameValues.get(c)).getDisplayValue()));
+ c++;
+ } // for
+
+ dr.setRowNum(dataRowIdx);
+ for (c = 0; c < getDataColumnCount(); c++) {
+ dr.addDataValue(new DataValue());
+ }
+
+ //reportDataRows.addDataRow(rowIdx, dr);
+ //dr.setRowNum(dataList.size()==0?1:dataList.size());
+ dataList.add(rowIdx, dr);
+
+ } // insertRow
+
+ private boolean prevRowNamesChanged(int rowIdx, Vector prevRowNames) {
+ for (int k = 0; k < prevRowNames.size(); k++)
+ if (!nvl((String) prevRowNames.get(k)).equals(
+ reportRowHeaderCols.getRowHeader(k, rowIdx).getRowTitle()))
+ return true;
+
+ return false;
+ } // prevRowNamesChanged
+
+ private int findRowIdx(Vector rowNameValues, CrossTabOrderManager crossTabOrderManager,
+ boolean createIfMissing, List dataList) {
+ int rowIdx = 0;
+ boolean nameFound = false;
+ Vector prevRowNames = new Vector();
+ for (int c = 0; c < rowNameValues.size(); c++) {
+ //String rowName = (String) rowNameValues.get(c);
+ String rowName = ((DataValue) rowNameValues.get(c)).getDisplayValue();
+
+ RowHeaderCol rhc = reportRowHeaderCols.getRowHeaderCol(c);
+
+ rhc.resetNext(rowIdx);
+ nameFound = false;
+ boolean posFound = false;
+ while ((!nameFound) && (!posFound) && rhc.hasNext()) {
+ RowHeader rh = rhc.getNext();
+ if (rowName.equals(rh.getRowTitle())) {
+ if (prevRowNamesChanged(rowIdx, prevRowNames))
+ posFound = true;
+ else
+ nameFound = true;
+ } else if (crossTabOrderManager != null
+ && crossTabOrderManager.isAfterRowHeaderValue(c, rh.getRowTitle(),
+ rowName))
+ posFound = true;
+ else if (crossTabOrderManager == null
+ && rowName.compareTo(rh.getRowTitle()) < 0)
+ posFound = true;
+ else if (prevRowNamesChanged(rowIdx, prevRowNames))
+ posFound = true;
+
+ if ((!nameFound) && (!posFound))
+ rowIdx++;
+ } // while
+
+ if (!nameFound)
+ if (createIfMissing) {
+ insertRow(rowIdx, rowNameValues, dataList, crossTabOrderManager);
+ return rowIdx;
+ } else
+ return -1;
+
+ prevRowNames.add(c, rowName);
+ } // for
+ if (!nameFound)
+ if (createIfMissing)
+ insertRow(rowIdx, rowNameValues, dataList, crossTabOrderManager);
+ else
+ return -1;
+
+ return rowIdx;
+ } // findRowIdx
+
+ public void setDataValue(Vector rowNameValues, Vector colNameValues, Vector colNameSortValues, DataValue value,
+ FormatProcessor formatProcessor, CrossTabOrderManager crossTabOrderManager, List dataList) {
+ int rowIdx = findRowIdx(rowNameValues, crossTabOrderManager, true, dataList);
+ int colIdx = findColumnIdx(colNameValues, colNameSortValues, crossTabOrderManager, true, dataList);
+
+ if ((rowIdx >= 0) && (colIdx >= 0)) {
+ //DataRow dr = reportDataRows.getDataRow(rowIdx);
+ DataRow dr = (DataRow)dataList.get(rowIdx);
+ dr.setRowValues(rowNameValues);
+ dr.setDataValue(colIdx, value);
+ formatProcessor.setHtmlFormatters(value, dr, false);
+ } // if
+ } // setDataValue
+
+ public void consolidateColumnHeaders(VisualManager visualManager) {
+ // Setting column visuals
+ for (int i = 0; i < reportColumnHeaderRows.getColumnHeaderRow(
+ reportColumnHeaderRows.getRowCount() - 1).size(); i++) {
+ StringBuffer sb = new StringBuffer();
+
+ for (int ir = 0; ir < reportColumnHeaderRows.getRowCount(); ir++) {
+ ColumnHeader ch = reportColumnHeaderRows.getColumnHeaderRow(ir)
+ .getColumnHeader(i);
+ if (sb.length() > 0)
+ sb.append('|');
+ sb.append(Utils.replaceInString(ch.getColumnTitle(), "|", " "));
+ } // for
+
+ String colValue = sb.toString();
+ columnVisuals.add(new ColumnVisual(colValue, colValue, visualManager
+ .isColumnVisible(colValue), /* visualManager.getSortByColId().equals(colValue)?visualManager.getSortByAscDesc(): */
+ null));
+ } // for
+
+ // Consolidating column headers
+ for (int r = reportColumnHeaderRows.getRowCount() - 1; r >= 0; r--) {
+ ColumnHeaderRow chr = reportColumnHeaderRows.getColumnHeaderRow(r);
+
+ if (chr.size() > 0) {
+ ColumnHeader baseCH = chr.getColumnHeader(0);
+ int c = 1;
+ int c_shift = 0;
+ while (c < chr.size()) {
+ ColumnHeader ch = chr.getColumnHeader(c);
+
+ boolean performMerge = true;
+ for (int ir = r; ir >= 0; ir--) {
+ ColumnHeaderRow ichr = reportColumnHeaderRows.getColumnHeaderRow(ir);
+ ColumnHeader ch0 = ichr.getColumnHeader(c + ((ir == r) ? 0 : c_shift));
+ ColumnHeader ch1 = ichr.getColumnHeader(c + ((ir == r) ? 0 : c_shift)
+ - 1);
+ if (!ch0.getColumnTitle().equals(ch1.getColumnTitle()))
+ performMerge = false;
+ } // for
+
+ if (performMerge) {
+ c_shift++;
+ baseCH.setColSpan(baseCH.getColSpan() + 1);
+ chr.remove(c);
+ } else {
+ baseCH = ch;
+ c++;
+ }
+ } // while
+ } // if
+ } // for
+ } // consolidateColumnHeaders
+
+ public void consolidateRowHeaders() {
+ for (int c = reportRowHeaderCols.getColumnCount() - 1; c >= 0; c--) {
+ RowHeaderCol rhc = reportRowHeaderCols.getRowHeaderCol(c);
+
+ if (rhc.size() > 0) {
+ RowHeader baseRH = rhc.getRowHeader(0);
+ int r = 1;
+ while (r < rhc.size()) {
+ RowHeader rh = rhc.getRowHeader(r);
+
+ boolean performMerge = rh.getRowTitle().equals(baseRH.getRowTitle());
+ for (int ic = c - 1; ic >= 0; ic--) {
+ RowHeaderCol irhc = reportRowHeaderCols.getRowHeaderCol(ic);
+ RowHeader rh0 = irhc.getRowHeader(r);
+ RowHeader rh1 = irhc.getRowHeader(r - 1);
+ if (!rh0.getRowTitle().equals(rh1.getRowTitle()))
+ performMerge = false;
+ } // for
+
+ if (performMerge)
+ rh.setRowTitle(null);
+ else
+ baseRH = rh;
+
+ r++;
+ } // while
+ } // if
+ } // for
+ } // consolidateRowHeaders
+
+ public void addRowNumbers(int pageNo, List dataList) {
+ pageNo = 0;
+ //int startRowNum = ((pageNo < 0) ? 0 : pageNo) * pageSize + 1;
+ int startRowNum = 0;
+ RowHeaderCol rhc = new RowHeaderCol();
+ reportRowHeaderCols.addRowHeaderCol(0, rhc);
+ //rhc.setColumnWidth("5%");
+ for (int r = 0; r < dataList.size(); r++) {
+ rhc.add(new RowHeader(startRowNum + r+""));
+ ((DataRow)dataList.get(r)).setRowNum(r);
+ }
+ } // addRowNumbers
+
+ private void removeRow(int rowIdx) {
+ for (reportRowHeaderCols.resetNext(); reportRowHeaderCols.hasNext();) {
+ RowHeaderCol rhc = reportRowHeaderCols.getNext();
+ rhc.remove(rowIdx);
+ } // for
+
+ reportDataRows.remove(rowIdx);
+ } // removeRow
+
+ public void truncateData(int startRow, int endRow) {
+ if( endRow != -1){
+ for (int r = getDataRowCount() - 1; r > endRow; r--)
+ removeRow(r);
+ }
+
+ for (int r = startRow - 1; r >= 0; r--)
+ removeRow(r);
+ } // truncateData
+
+ /** *********************************************************************************** */
+
+ public void createColumn(String colId, String displayName, String displayWidthInPxls, String alignment,
+ boolean currentlyVisible, String currentSort, boolean isRuntimeColSortDisabled, int level, int start, int colspan, boolean sortable) {
+ ColumnHeaderRow chr = null;
+ if (getHeaderRowCount() > 0)
+ chr = reportColumnHeaderRows.getColumnHeaderRow(0);
+ else {
+ chr = new ColumnHeaderRow();
+ reportColumnHeaderRows.addColumnHeaderRow(chr);
+ chr.setRowHeight("30");
+ } // if
+ /*ColumnHeader ch = new ColumnHeader(displayName, (displayWidth > 100) ? "10%" : (""
+ + displayWidth + "%"), alignment, 1, isRuntimeColSortDisabled ? null : colId);
+ */
+ ColumnHeader ch = new ColumnHeader(displayName, displayWidthInPxls, alignment, 1, isRuntimeColSortDisabled ? null : colId);
+ ch.setGroupLevel(level);
+ ch.setStartGroup(start);
+ ch.setColSpanGroup(colspan);
+ ch.setColId(colId);
+ ch.setSortable(sortable);
+ //chr.addColumnHeader(new ColumnHeader(displayName, (displayWidth > 100) ? "10%" : (""
+ // + displayWidth + "%"), 1, isRuntimeColSortDisabled ? null : colId));
+
+ if (displayName != "Hidden") {
+
+ chr.addColumnHeader(ch);
+ columnVisuals.add(new ColumnVisual(colId, displayName, currentlyVisible, currentSort));
+ }
+ } // createColumn
+
+ public void columnVisualShowHide(String colId, boolean newVisible) {
+ for (int i = 0; i < columnVisuals.size(); i++) {
+ ColumnVisual col = (ColumnVisual) columnVisuals.get(i);
+ if (col.getColId().equals(colId)) {
+ col.setVisible(newVisible);
+ applyColumnVisibility(i, newVisible);
+ break;
+ } // if
+ } // for
+ } // columnVisualShowHide
+
+ private void applyColumnVisibility(int colIdx, boolean newVisible) {
+ boolean isLast = true;
+ for (int r = reportColumnHeaderRows.getRowCount() - 1; r >= 0; r--) {
+ ColumnHeaderRow chr = reportColumnHeaderRows.getColumnHeaderRow(r);
+
+ if (isLast) {
+ chr.getColumnHeader(colIdx).setVisible(newVisible);
+ isLast = false;
+ } else {
+ int curStartIdx = 0;
+ for (chr.resetNext(); chr.hasNext();) {
+ ColumnHeader ch = chr.getNext();
+ if (colIdx >= curStartIdx && colIdx <= curStartIdx + ch.getColSpan() - 1) {
+ ch.setVisible(newVisible);
+ break;
+ } else
+ curStartIdx += ch.getColSpan();
+ } // for
+ } // else
+ } // for
+ int row = 0;
+ for (reportDataRows.resetNext(); reportDataRows.hasNext();) {
+ //reportDataRows.getNext().getDataValue(colIdx).setVisible(newVisible);
+ DataRow dr = reportDataRows.getNext();
+ if(colIdx < dr.getDataValueList().size()) {
+ DataValue dv = dr.getDataValue(colIdx);
+ dr.getDataValueList().remove(colIdx);
+ if(!dv.isHidden())
+ dv.setVisible(newVisible);
+ else
+ dv.setVisible(false);
+ dr.addDataValue(colIdx, dv);
+ }
+ reportDataRows.removeElementAt(row);
+ reportDataRows.addDataRow(row, dr);
+ row++;
+ }
+ } // applyColumnVisibility
+
+ public void applyVisibility() {
+ for (int i = 0; i < columnVisuals.size(); i++)
+ applyColumnVisibility(i, ((ColumnVisual) columnVisuals.get(i)).isVisible());
+ } // applyVisibility
+
+ public void resetVisualSettings() {
+ // No need to reset sort - if sort exists, the report data is reloaded
+ for (int i = 0; i < columnVisuals.size(); i++)
+ ((ColumnVisual) columnVisuals.get(i)).setVisible(true);
+
+ applyVisibility();
+ } // resetVisualSettings
+
+ /** *********************************************************************************** */
+
+ private int nextVisualIdx = 0;
+
+ public void resetNextVisual() {
+ resetNextVisual(0);
+ } // resetNext
+
+ public void resetNextVisual(int toPos) {
+ nextVisualIdx = toPos;
+ } // resetNext
+
+ public boolean hasNextVisual() {
+ return (nextVisualIdx < columnVisuals.size());
+ } // hasNext
+
+ public String getNextHiddenColLinks(int toPos) {
+ resetNextVisual(toPos);
+ return getNextHiddenColLinks();
+ } // getNextHiddenColLinks
+
+ public String getNextHiddenColLinks() {
+ if (!hasNextVisual())
+ return "";
+
+ StringBuffer sb = new StringBuffer();
+ ColumnVisual col = (ColumnVisual) columnVisuals.get(nextVisualIdx);
+
+ while (!col.isVisible()) {
+ if(!col.getColDisplay().equals(AppConstants.HIDDEN)) {
+ sb.append("<input type=image border=0 src='");
+ sb.append(AppUtils.getImgFolderURL());
+ sb.append("plus.gif' alt=\"Show column ");
+ sb.append(col.getColDisplay());
+ sb.append("\" width=11 height=11 onClick=\"document.formd.");
+ sb.append(AppConstants.RI_VISUAL_ACTION);
+ sb.append(".value='");
+ sb.append(AppConstants.VA_SHOW);
+ sb.append("';document.formd.");
+ sb.append(AppConstants.RI_DETAIL_ID);
+ sb.append(".value='");
+ sb.append(col.getColId());
+ sb.append("';document.formd.submit();\">");
+ }
+
+ if (!(nextVisualIdx + 1 < columnVisuals.size()))
+ break;
+ col = (ColumnVisual) columnVisuals.get(++nextVisualIdx);
+ } // while
+
+ return sb.toString();
+ } // getNextHiddenColLinks
+
+ public String getNextVisual() {
+ if (!hasNextVisual())
+ return null;
+
+ ColumnVisual col = (ColumnVisual) columnVisuals.get(nextVisualIdx++);
+
+ StringBuffer sb = new StringBuffer();
+
+ if (!col.isVisible() || col.getColDisplay().equals(AppConstants.HIDDEN))
+ return null;
+
+ sb.append("\n\t\t\t<table width=100% border=0 cellspacing=0 cellpadding=0><tr>\n");
+ sb
+ .append("\t\t\t\t<td style=\"background:#ffffff;\" align=left valign=middle nowrap><input type=image border=0 src='");
+ sb.append(AppUtils.getImgFolderURL());
+ sb.append("minus.gif' alt=\"Hide column ");
+ sb.append(col.getColDisplay());
+ sb.append("\" width=11 height=11 onClick=\"document.formd.");
+ sb.append(AppConstants.RI_VISUAL_ACTION);
+ sb.append(".value='");
+ sb.append(AppConstants.VA_HIDE);
+ sb.append("';document.formd.");
+ sb.append(AppConstants.RI_DETAIL_ID);
+ sb.append(".value='");
+ sb.append(col.getColId());
+ sb.append("';document.formd.submit();");
+ sb.append("\"></td>\n");
+ sb.append("\t\t\t\t<td style=\"background:#ffffff;\" align=center valign=middle width=95% nowrap>");
+ if (col.getSortType() != null) {
+ sb.append("<img border=0 src='");
+ sb.append(AppUtils.getImgFolderURL());
+ if (col.getSortType().equals(AppConstants.SO_ASC))
+ sb.append("grnarrowdn.gif");
+ else
+ sb.append("grnarrowup.gif");
+ sb.append("' alt=\"Sorted by column ");
+ sb.append(col.getColDisplay());
+ if (col.getSortType().equals(AppConstants.SO_ASC))
+ sb.append(" ascending");
+ else
+ sb.append(" descending");
+ sb.append("\" width=13 height=11>");
+ }
+ sb.append("</td>\n");
+ sb.append("\t\t\t\t<td style=\"background:#ffffff;\" align=right valign=middle nowrap>");
+ sb.append(getNextHiddenColLinks());
+ sb.append("</td>\n");
+ sb.append("\t\t\t</tr></table>\n\t\t");
+
+ return sb.toString();
+ } // getNext
+
+ /** *********************************************************************************** */
+
+ public void setColumnDataTotalsLinear(DataRow colDataTotals, String colTotalLabel) {
+ //commented so that we could differentiate data rows with total rows
+ //reportDataRows.addDataRow(colDataTotals);
+ RowHeader rh = new RowHeader(colTotalLabel, "45", 1, reportRowHeaderCols.getColumnCount(),true);
+ if(reportRowHeaderCols.size()>0)
+ reportRowHeaderCols.getRowHeaderCol(0).add(rh);
+
+ reportDataTotalRow = new ReportDataRows();
+ reportDataTotalRow.addDataRow(colDataTotals);
+ RowHeaderCol rhc = new RowHeaderCol();
+ rhc.add(rh);
+ reportTotalRowHeaderCols = new ReportRowHeaderCols();
+ reportTotalRowHeaderCols.addRowHeaderCol(0, rhc);
+ } // setColumnDataTotalsLinear
+
+ public void setCrossTabColumnTotalLabel(String colTotalLabel) {
+ reportRowHeaderCols.getRowHeaderCol(0).getRowHeader(getDataRowCount() - 1)
+ .setRowTitle("");
+ reportRowHeaderCols.getRowHeaderCol(0).getRowHeader(getDataRowCount() - 1).setColSpan(
+ 0);
+ reportRowHeaderCols.getRowHeaderCol(1).set(
+ getDataRowCount() - 1,
+ new RowHeader(colTotalLabel, "45", 1, reportRowHeaderCols.getColumnCount(),
+ true));
+ } // setCrossTabColumnTotalLabel
+
+ public void setCrossTabColumnTotalLabel(int reportDataSize, String colTotalLabel) {
+
+ reportRowHeaderCols.getRowHeaderCol(0).getRowHeader(getDataRowCount() - 1)
+ .setRowTitle("");
+ reportRowHeaderCols.getRowHeaderCol(0).getRowHeader(getDataRowCount() - 1).setColSpan(
+ 0);
+ reportRowHeaderCols.getRowHeaderCol(1).set(
+ getDataRowCount() - 1,
+ new RowHeader(colTotalLabel, "45", 1, reportRowHeaderCols.getColumnCount(),
+ true));
+ } // setCrossTabColumnTotalLabel
+
+ public void setColumnDataTotalsCrossTab(Vector colDataTotals, String totalsAlignment,
+ String colDisplayTotal, CrossTabOrderManager crossTabOrderManager, List dataList) {
+ DataRow totalsDataRow = new DataRow();
+ for (int c = 0; c < getDataColumnCount(); c++)
+ totalsDataRow.addDataValue(new DataValue());
+
+ for (Iterator iter = colDataTotals.iterator(); iter.hasNext();) {
+ CrossTabTotalValue tVal = (CrossTabTotalValue) iter.next();
+
+ int colIdx = findColumnIdx(tVal.getHeaderValues(), null, crossTabOrderManager, false, dataList);
+ if (colIdx >= 0) {
+ DataValue dataValue = new DataValue();
+
+ String totalValue = tVal.getTotalValue();
+ // if(colDisplayTotal.length()>0&&(!
+ // colDisplayTotal.equals(AppConstants.TOTAL_SUM_ID)))
+ // totalValue =
+ // nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(colDisplayTotal))+":
+ // "+totalValue;
+ dataValue.setDisplayValue(totalValue);
+ //added below statement for displaying in excel as number
+ dataValue.setDisplayTotal("SUM(");
+ dataValue.setAlignment(totalsAlignment);
+ dataValue.setBold(true);
+ totalsDataRow.setDataValue(colIdx, dataValue);
+
+ //totalsDataRow.addDataValue(dataValue);
+
+ } // if
+ } // for
+
+ //reportDataRows.addDataRow(totalsDataRow);
+ //dr.setRowValues(rowNameValues);
+ Vector rowNameValues = new Vector();
+ for (int i=0; i < reportRowHeaderCols.size(); i++) {
+ if(i==0) {
+ DataValue dataValue = new DataValue();
+ dataValue.setBold(true);
+ dataValue.setAlignment("center");
+ dataValue.setDisplayValue("Total");
+ rowNameValues.add(dataValue);
+ //rowNameValues.add("Total");
+ } else {
+ //rowNameValues.add("");
+ DataValue dataValue = new DataValue();
+ dataValue.setDisplayValue("");
+ rowNameValues.add(dataValue);
+
+ }
+ }
+ totalsDataRow.setRowValues(rowNameValues);
+ totalsDataRow.setRowNum(dataList.size());
+ dataList.add(totalsDataRow);
+ //reportRowHeaderCols.getNext().addRowHeader(new RowHeader("", "30", 1, 0));
+ } // setColumnDataTotalsCrossTab
+
+ public void setRowDataTotalsCrossTab(Vector rowDataTotals, String totalsAlignment,
+ String rowDisplayTotal, CrossTabOrderManager crossTabOrderManager, List dataList) {
+ int colIdx = getDataColumnCount();
+
+ boolean isFirst = true;
+ for (reportColumnHeaderRows.resetNext(); reportColumnHeaderRows.hasNext();) {
+ ColumnHeaderRow chr = reportColumnHeaderRows.getNext();
+ if (isFirst) {
+ String totalLabel = "Total";
+ if (rowDisplayTotal.length() > 0
+ && (!rowDisplayTotal.equals(AppConstants.TOTAL_SUM_ID)))
+ totalLabel = nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(rowDisplayTotal));
+ chr.addColumnHeader(colIdx, new ColumnHeader(totalLabel, "", 1,
+ reportColumnHeaderRows.getRowCount()));
+ isFirst = false;
+ } else
+ chr.addColumnHeader(colIdx, new ColumnHeader("", "", 1, 0));
+ } // for
+
+ for (reportDataRows.resetNext(); reportDataRows.hasNext();) {
+ DataRow dr = reportDataRows.getNext();
+ dr.addDataValue(colIdx, new DataValue());
+ } // for
+
+ for (Iterator iter = rowDataTotals.iterator(); iter.hasNext();) {
+ CrossTabTotalValue tVal = (CrossTabTotalValue) iter.next();
+
+ int rowIdx = findRowIdx(tVal.getHeaderValues(), crossTabOrderManager, false, dataList);
+ if (rowIdx >= 0) {
+ DataValue dataValue = new DataValue();
+
+ String totalValue = tVal.getTotalValue();
+ // if(rowDisplayTotal.length()>0&&(!
+ // rowDisplayTotal.equals(AppConstants.TOTAL_SUM_ID)))
+ // totalValue =
+ // nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(rowDisplayTotal))+":
+ // "+totalValue;
+ dataValue.setDisplayValue(totalValue);
+ //added below statement for displaying in excel as number
+ dataValue.setDisplayTotal("SUM(");
+ dataValue.setAlignment(totalsAlignment);
+ dataValue.setBold(true);
+
+ //reportDataRows.getDataRow(rowIdx).getDataValueList().add(colIdx, dataValue);
+ ((DataRow)dataList.get(rowIdx)).addDataValue(colIdx, dataValue);
+ } // if
+ } // for
+ } // setRowDataTotalsCrossTab
+
+ public void setGrandTotalCrossTab(String totalValue, String totalAlignment,
+ String displayTotal, List dataList) {
+ DataValue dataValue = new DataValue();
+
+ // if(displayTotal.length()>0&&(!
+ // displayTotal.equals(AppConstants.TOTAL_SUM_ID)))
+ // totalValue =
+ // nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(displayTotal))+":
+ // "+totalValue;
+ dataValue.setDisplayValue(totalValue);
+ //added below statement for displaying in excel as number
+ dataValue.setDisplayTotal("SUM(");
+ dataValue.setAlignment(totalAlignment);
+ dataValue.setBold(true);
+
+ //int colIdx = getDataColumnCount() - 1;
+ int rowIdx = getDataRowCount() - 1;
+ //reportDataRows.getDataRow(rowIdx).getDataValueList().add(colIdx, dataValue);
+ DataRow dr = (DataRow)dataList.get(rowIdx);
+ dr.addDataValue(dr.getDataValueList().size(), dataValue);
+ } // setGrandTotalCrossTab
+
+ public List getReportDataList() {
+ return reportDataList;
+ }
+
+ public void setReportDataList(List reportDataList) {
+ this.reportDataList = reportDataList;
+ }
+
+} // ReportData
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import java.util.*;
+
+public class ReportDataRows extends Vector {
+ 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 DataRow getNext() {
+ return hasNext() ? getDataRow(nextElemIdx++) : null;
+ } // getNext
+
+ public DataValue getDataValue(int rowIdx, int colIdx) {
+ return getDataRow(rowIdx).getDataValue(colIdx);
+ } // getDataValue
+
+ public DataRow getDataRow(int idx) {
+ return (DataRow) get(idx);
+ } // getDataRow
+
+ public void addDataRow(DataRow dataRow) {
+ add(dataRow);
+ } // addDataRow
+
+ public void addDataRow(int idx, DataRow dataRow) {
+ add(idx, dataRow);
+ } // addDataRow
+
+ public int getRowCount() {
+ return size();
+ } // getRowCount
+
+ public int getColumnCount() {
+ int cSize = 0;
+ if (getRowCount() > 0)
+ cSize = getDataRow(0).getDataValueList().size();
+
+ return cSize;
+ } // getColumnCount
+
+} // ReportDataRows
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import java.util.*;
+
+public class ReportRowHeaderCols extends Vector {
+ 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 RowHeaderCol getNext() {
+ return hasNext() ? getRowHeaderCol(nextElemIdx++) : null;
+ } // getNext
+
+ public RowHeader getRowHeader(int colIdx, int rowIdx) {
+ return getRowHeaderCol(colIdx).getRowHeader(rowIdx);
+ } // getRowHeader
+
+ public RowHeaderCol getRowHeaderCol(int idx) {
+ return (RowHeaderCol) get(idx);
+ } // getRowHeaderCol
+
+ public void addRowHeaderCol(RowHeaderCol rowHeaderCol) {
+ add(rowHeaderCol);
+ } // addRowHeaderCol
+
+ public void addRowHeaderCol(int idx, RowHeaderCol rowHeaderCol) {
+ add(idx, rowHeaderCol);
+ } // addRowHeaderCol
+
+ public int getRowCount() {
+ int cSize = 0;
+ if (getColumnCount() > 0)
+ cSize = getRowHeaderCol(0).size();
+
+ return cSize;
+ } // getRowCount
+
+ public int getColumnCount() {
+ return size();
+ } // getColumnCount
+
+} // ReportRowHeaderCols
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import org.onap.portalsdk.analytics.util.*;
+
+public class RowHeader extends org.onap.portalsdk.analytics.RaptorObject {
+ private String rowTitle = "";
+
+ private String rowHeight = "";
+
+ private int rowSpan = 1;
+
+ private int colSpan = 1;
+
+ private boolean bold = false;
+
+ public RowHeader() {
+ super();
+ }
+
+ public RowHeader(String rowTitle) {
+ this();
+ setRowTitle(rowTitle);
+ } // RowHeader
+
+ public RowHeader(String rowTitle, String rowHeight) {
+ this(rowTitle);
+ setRowHeight(rowHeight);
+ } // RowHeader
+
+ public RowHeader(String rowTitle, String rowHeight, int rowSpan) {
+ this(rowTitle, rowHeight);
+ setRowSpan(rowSpan);
+ } // RowHeader
+
+ public RowHeader(String rowTitle, String rowHeight, int rowSpan, int colSpan) {
+ this(rowTitle, rowHeight, rowSpan);
+ setColSpan(colSpan);
+ } // RowHeader
+
+ public RowHeader(String rowTitle, String rowHeight, int rowSpan, int colSpan, boolean bold) {
+ this(rowTitle, rowHeight, rowSpan, colSpan);
+ setBold(bold);
+ } // RowHeader
+
+ public String getRowTitle() {
+ return rowTitle;
+ }
+
+ public String getRowHeight() {
+ return rowHeight;
+ }
+
+ public int getRowSpan() {
+ return rowSpan;
+ }
+
+ public int getColSpan() {
+ return colSpan;
+ }
+
+ public boolean isBold() {
+ return bold;
+ }
+
+ public void setRowTitle(String rowTitle) {
+ this.rowTitle = nvl(rowTitle);
+ }
+
+ public void setRowHeight(String rowHeight) {
+ this.rowHeight = rowHeight;
+ }
+
+ public void setRowSpan(int rowSpan) {
+ this.rowSpan = rowSpan;
+ }
+
+ public void setColSpan(int colSpan) {
+ this.colSpan = colSpan;
+ }
+
+ public void setBold(boolean bold) {
+ this.bold = bold;
+ }
+
+ public String getRowTitleHtml() {
+ return (rowTitle.length() == 0) ? " " : rowTitle;
+ }
+
+ public String getRowHeightHtml() {
+ return (rowHeight.length() == 0) ? "" : (" height=" + rowHeight);
+ }
+
+ public String getRowSpanHtml() {
+ return (rowSpan == 1) ? "" : (" rowspan=" + rowSpan);
+ }
+
+ public String getColSpanHtml() {
+ return (colSpan == 1) ? "" : (" colspan=" + colSpan);
+ }
+
+} // RowHeader
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.analytics.view;
+
+import java.util.*;
+
+import org.onap.portalsdk.analytics.util.*;
+
+public class RowHeaderCol extends Vector {
+ private String columnWidth = "";
+
+ private String columnTitle = "";
+
+ private String alignment = "";
+
+ private String displayHeaderAlignment = "";
+
+ private int nextElemIdx = 0;
+
+ private boolean visible = true;
+
+ private String colId = "";
+
+ private String nowrap = "False";
+
+ public void resetNext() {
+ resetNext(0);
+ } // resetNext
+
+ public void resetNext(int toPos) {
+ nextElemIdx = toPos;
+ } // resetNext
+
+ public boolean hasNext() {
+ return (nextElemIdx < size());
+ } // hasNext
+
+ public RowHeader getNext() {
+ return hasNext() ? getRowHeader(nextElemIdx++) : null;
+ } // getNext
+
+ public RowHeader getRowHeader(int idx) {
+ return (RowHeader) get(idx);
+ } // getRowHeader
+
+ public void addRowHeader(RowHeader rowHeader) {
+ add(rowHeader);
+ } // addRowHeader
+
+ public void addRowHeader(int idx, RowHeader rowHeader) {
+ add(idx, rowHeader);
+ } // addRowHeader
+
+ public String getColumnTitle() {
+ return columnTitle;
+ }
+
+ public String getColumnWidth() {
+ return columnWidth;
+ }
+
+ public String getAlignment() {
+ return alignment;
+ }
+
+ public void setColumnTitle(String columnTitle) {
+ this.columnTitle = nvl(columnTitle);
+ }
+
+ public void setColumnWidth(String columnWidth) {
+ this.columnWidth = nvl(columnWidth);
+ }
+
+ public void setAlignment(String alignment) {
+ this.alignment = alignment;
+ }
+
+ public String getColumnTitleHtml() {
+ return (columnTitle.length() == 0) ? " " : columnTitle;
+ }
+
+ public String getColumnWidthHtml() {
+ return (columnWidth.length() == 0) ? "" : (" width=" + columnWidth);
+ }
+
+ public String getAlignmentHtml() {
+ return " align=" + nvl(alignment, "center");
+ }
+
+ /** ************************************************************************************************* */
+
+ private String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ private String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+ public String getNowrap() {
+ return nowrap;
+ }
+
+ public void setNowrap(String nowrap) {
+ this.nowrap = nowrap;
+ }
+
+ public boolean isVisible() {
+ return visible;
+ }
+
+ public void setVisible(boolean visible) {
+ this.visible = visible;
+ }
+
+ /**
+ * @return the colId
+ */
+ public String getColId() {
+ return colId;
+ }
+
+ /**
+ * @param colId the colId to set
+ */
+ public void setColId(String colId) {
+ this.colId = colId;
+ }
+
+ public String getDisplayHeaderAlignment() {
+ return displayHeaderAlignment;
+ }
+
+ public void setDisplayHeaderAlignment(String displayHeaderAlignment) {
+ this.displayHeaderAlignment = displayHeaderAlignment;
+ }
+
+
+
+} // RowHeaderCol
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for ChartAdditionalOptions complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="ChartAdditionalOptions">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="chartMultiplePieOrder" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartMultiplePieLabelDisplay" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartOrientation" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="secondaryChartRenderer" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartDisplay" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="hideToolTips" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="hidechartLegend" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="legendPosition" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="labelAngle" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="intervalFromdate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="intervalTodate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="intervalLabel" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="lastSeriesALineChart" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="lastSeriesABarChart" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="maxLabelsInDomainAxis" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="linearRegression" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="linearRegressionColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="exponentialRegressionColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="maxRegression" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="rangeAxisUpperLimit" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="rangeAxisLowerLimit" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="overlayItemValueOnStackBar" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="animate" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="animateAnimatedChart" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="keepDomainAxisValueAsString" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="stacked" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="barControls" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="xAxisDateType" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="lessXaxisTickers" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="timeAxis" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="timeSeriesRender" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="multiSeries" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="showXAxisLabel" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="addXAxisTickers" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="zoomIn" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="timeAxisType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="logScale" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="topMargin" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="bottomMargin" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="rightMargin" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="leftMargin" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "ChartAdditionalOptions", propOrder = {
+ "chartMultiplePieOrder",
+ "chartMultiplePieLabelDisplay",
+ "chartOrientation",
+ "secondaryChartRenderer",
+ "chartDisplay",
+ "hideToolTips",
+ "hidechartLegend",
+ "legendPosition",
+ "labelAngle",
+ "intervalFromdate",
+ "intervalTodate",
+ "intervalLabel",
+ "lastSeriesALineChart",
+ "lastSeriesABarChart",
+ "maxLabelsInDomainAxis",
+ "linearRegression",
+ "linearRegressionColor",
+ "exponentialRegressionColor",
+ "maxRegression",
+ "rangeAxisUpperLimit",
+ "rangeAxisLowerLimit",
+ "overlayItemValueOnStackBar",
+ "animate",
+ "animateAnimatedChart",
+ "keepDomainAxisValueAsString",
+ "stacked",
+ "barControls",
+ "xAxisDateType",
+ "lessXaxisTickers",
+ "timeAxis",
+ "timeSeriesRender",
+ "multiSeries",
+ "showXAxisLabel",
+ "addXAxisTickers",
+ "zoomIn",
+ "timeAxisType",
+ "logScale",
+ "topMargin",
+ "bottomMargin",
+ "rightMargin",
+ "leftMargin"
+})
+public class ChartAdditionalOptions {
+
+ protected String chartMultiplePieOrder;
+ protected String chartMultiplePieLabelDisplay;
+ protected String chartOrientation;
+ protected String secondaryChartRenderer;
+ protected String chartDisplay;
+ protected String hideToolTips;
+ protected String hidechartLegend;
+ protected String legendPosition;
+ protected String labelAngle;
+ protected String intervalFromdate;
+ protected String intervalTodate;
+ protected String intervalLabel;
+ protected String lastSeriesALineChart;
+ protected String lastSeriesABarChart;
+ protected String maxLabelsInDomainAxis;
+ protected String linearRegression;
+ protected String linearRegressionColor;
+ protected String exponentialRegressionColor;
+ protected String maxRegression;
+ protected String rangeAxisUpperLimit;
+ protected String rangeAxisLowerLimit;
+ protected String overlayItemValueOnStackBar;
+ @XmlElement(defaultValue = "false")
+ protected Boolean animate;
+ @XmlElement(defaultValue = "true")
+ protected Boolean animateAnimatedChart;
+ protected String keepDomainAxisValueAsString;
+ @XmlElement(defaultValue = "false")
+ protected Boolean stacked;
+ @XmlElement(defaultValue = "false")
+ protected Boolean barControls;
+ @XmlElement(defaultValue = "false")
+ protected Boolean xAxisDateType;
+ @XmlElement(defaultValue = "false")
+ protected Boolean lessXaxisTickers;
+ @XmlElement(defaultValue = "true")
+ protected Boolean timeAxis;
+ protected String timeSeriesRender;
+ @XmlElement(defaultValue = "false")
+ protected Boolean multiSeries;
+ @XmlElement(defaultValue = "false")
+ protected Boolean showXAxisLabel;
+ @XmlElement(defaultValue = "false")
+ protected Boolean addXAxisTickers;
+ protected Integer zoomIn;
+ protected String timeAxisType;
+ @XmlElement(defaultValue = "false")
+ protected Boolean logScale;
+ protected Integer topMargin;
+ protected Integer bottomMargin;
+ protected Integer rightMargin;
+ protected Integer leftMargin;
+
+ /**
+ * Gets the value of the chartMultiplePieOrder property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartMultiplePieOrder() {
+ return chartMultiplePieOrder;
+ }
+
+ /**
+ * Sets the value of the chartMultiplePieOrder property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartMultiplePieOrder(String value) {
+ this.chartMultiplePieOrder = value;
+ }
+
+ /**
+ * Gets the value of the chartMultiplePieLabelDisplay property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartMultiplePieLabelDisplay() {
+ return chartMultiplePieLabelDisplay;
+ }
+
+ /**
+ * Sets the value of the chartMultiplePieLabelDisplay property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartMultiplePieLabelDisplay(String value) {
+ this.chartMultiplePieLabelDisplay = value;
+ }
+
+ /**
+ * Gets the value of the chartOrientation property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartOrientation() {
+ return chartOrientation;
+ }
+
+ /**
+ * Sets the value of the chartOrientation property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartOrientation(String value) {
+ this.chartOrientation = value;
+ }
+
+ /**
+ * Gets the value of the secondaryChartRenderer property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getSecondaryChartRenderer() {
+ return secondaryChartRenderer;
+ }
+
+ /**
+ * Sets the value of the secondaryChartRenderer property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setSecondaryChartRenderer(String value) {
+ this.secondaryChartRenderer = value;
+ }
+
+ /**
+ * Gets the value of the chartDisplay property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartDisplay() {
+ return chartDisplay;
+ }
+
+ /**
+ * Sets the value of the chartDisplay property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartDisplay(String value) {
+ this.chartDisplay = value;
+ }
+
+ /**
+ * Gets the value of the hideToolTips property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getHideToolTips() {
+ return hideToolTips;
+ }
+
+ /**
+ * Sets the value of the hideToolTips property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setHideToolTips(String value) {
+ this.hideToolTips = value;
+ }
+
+ /**
+ * Gets the value of the hidechartLegend property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getHidechartLegend() {
+ return hidechartLegend;
+ }
+
+ /**
+ * Sets the value of the hidechartLegend property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setHidechartLegend(String value) {
+ this.hidechartLegend = value;
+ }
+
+ /**
+ * Gets the value of the legendPosition property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getLegendPosition() {
+ return legendPosition;
+ }
+
+ /**
+ * Sets the value of the legendPosition property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setLegendPosition(String value) {
+ this.legendPosition = value;
+ }
+
+ /**
+ * Gets the value of the labelAngle property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getLabelAngle() {
+ return labelAngle;
+ }
+
+ /**
+ * Sets the value of the labelAngle property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setLabelAngle(String value) {
+ this.labelAngle = value;
+ }
+
+ /**
+ * Gets the value of the intervalFromdate property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getIntervalFromdate() {
+ return intervalFromdate;
+ }
+
+ /**
+ * Sets the value of the intervalFromdate property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setIntervalFromdate(String value) {
+ this.intervalFromdate = value;
+ }
+
+ /**
+ * Gets the value of the intervalTodate property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getIntervalTodate() {
+ return intervalTodate;
+ }
+
+ /**
+ * Sets the value of the intervalTodate property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setIntervalTodate(String value) {
+ this.intervalTodate = value;
+ }
+
+ /**
+ * Gets the value of the intervalLabel property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getIntervalLabel() {
+ return intervalLabel;
+ }
+
+ /**
+ * Sets the value of the intervalLabel property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setIntervalLabel(String value) {
+ this.intervalLabel = value;
+ }
+
+ /**
+ * Gets the value of the lastSeriesALineChart property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getLastSeriesALineChart() {
+ return lastSeriesALineChart;
+ }
+
+ /**
+ * Sets the value of the lastSeriesALineChart property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setLastSeriesALineChart(String value) {
+ this.lastSeriesALineChart = value;
+ }
+
+ /**
+ * Gets the value of the lastSeriesABarChart property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getLastSeriesABarChart() {
+ return lastSeriesABarChart;
+ }
+
+ /**
+ * Sets the value of the lastSeriesABarChart property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setLastSeriesABarChart(String value) {
+ this.lastSeriesABarChart = value;
+ }
+
+ /**
+ * Gets the value of the maxLabelsInDomainAxis property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getMaxLabelsInDomainAxis() {
+ return maxLabelsInDomainAxis;
+ }
+
+ /**
+ * Sets the value of the maxLabelsInDomainAxis property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setMaxLabelsInDomainAxis(String value) {
+ this.maxLabelsInDomainAxis = value;
+ }
+
+ /**
+ * Gets the value of the linearRegression property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getLinearRegression() {
+ return linearRegression;
+ }
+
+ /**
+ * Sets the value of the linearRegression property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setLinearRegression(String value) {
+ this.linearRegression = value;
+ }
+
+ /**
+ * Gets the value of the linearRegressionColor property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getLinearRegressionColor() {
+ return linearRegressionColor;
+ }
+
+ /**
+ * Sets the value of the linearRegressionColor property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setLinearRegressionColor(String value) {
+ this.linearRegressionColor = value;
+ }
+
+ /**
+ * Gets the value of the exponentialRegressionColor property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getExponentialRegressionColor() {
+ return exponentialRegressionColor;
+ }
+
+ /**
+ * Sets the value of the exponentialRegressionColor property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setExponentialRegressionColor(String value) {
+ this.exponentialRegressionColor = value;
+ }
+
+ /**
+ * Gets the value of the maxRegression property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getMaxRegression() {
+ return maxRegression;
+ }
+
+ /**
+ * Sets the value of the maxRegression property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setMaxRegression(String value) {
+ this.maxRegression = value;
+ }
+
+ /**
+ * Gets the value of the rangeAxisUpperLimit property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getRangeAxisUpperLimit() {
+ return rangeAxisUpperLimit;
+ }
+
+ /**
+ * Sets the value of the rangeAxisUpperLimit property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setRangeAxisUpperLimit(String value) {
+ this.rangeAxisUpperLimit = value;
+ }
+
+ /**
+ * Gets the value of the rangeAxisLowerLimit property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getRangeAxisLowerLimit() {
+ return rangeAxisLowerLimit;
+ }
+
+ /**
+ * Sets the value of the rangeAxisLowerLimit property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setRangeAxisLowerLimit(String value) {
+ this.rangeAxisLowerLimit = value;
+ }
+
+ /**
+ * Gets the value of the overlayItemValueOnStackBar property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getOverlayItemValueOnStackBar() {
+ return overlayItemValueOnStackBar;
+ }
+
+ /**
+ * Sets the value of the overlayItemValueOnStackBar property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setOverlayItemValueOnStackBar(String value) {
+ this.overlayItemValueOnStackBar = value;
+ }
+
+ /**
+ * Gets the value of the animate property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isAnimate() {
+ return animate;
+ }
+
+ /**
+ * Sets the value of the animate property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setAnimate(Boolean value) {
+ this.animate = value;
+ }
+
+ /**
+ * Gets the value of the animateAnimatedChart property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isAnimateAnimatedChart() {
+ return animateAnimatedChart;
+ }
+
+ /**
+ * Sets the value of the animateAnimatedChart property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setAnimateAnimatedChart(Boolean value) {
+ this.animateAnimatedChart = value;
+ }
+
+ /**
+ * Gets the value of the keepDomainAxisValueAsString property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getKeepDomainAxisValueAsString() {
+ return keepDomainAxisValueAsString;
+ }
+
+ /**
+ * Sets the value of the keepDomainAxisValueAsString property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setKeepDomainAxisValueAsString(String value) {
+ this.keepDomainAxisValueAsString = value;
+ }
+
+ /**
+ * Gets the value of the stacked property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isStacked() {
+ return stacked;
+ }
+
+ /**
+ * Sets the value of the stacked property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setStacked(Boolean value) {
+ this.stacked = value;
+ }
+
+ /**
+ * Gets the value of the barControls property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isBarControls() {
+ return barControls;
+ }
+
+ /**
+ * Sets the value of the barControls property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setBarControls(Boolean value) {
+ this.barControls = value;
+ }
+
+ /**
+ * Gets the value of the xAxisDateType property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isXAxisDateType() {
+ return xAxisDateType;
+ }
+
+ /**
+ * Sets the value of the xAxisDateType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setXAxisDateType(Boolean value) {
+ this.xAxisDateType = value;
+ }
+
+ /**
+ * Gets the value of the lessXaxisTickers property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isLessXaxisTickers() {
+ return lessXaxisTickers;
+ }
+
+ /**
+ * Sets the value of the lessXaxisTickers property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setLessXaxisTickers(Boolean value) {
+ this.lessXaxisTickers = value;
+ }
+
+ /**
+ * Gets the value of the timeAxis property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isTimeAxis() {
+ return timeAxis;
+ }
+
+ /**
+ * Sets the value of the timeAxis property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setTimeAxis(Boolean value) {
+ this.timeAxis = value;
+ }
+
+ /**
+ * Gets the value of the timeSeriesRender property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getTimeSeriesRender() {
+ return timeSeriesRender;
+ }
+
+ /**
+ * Sets the value of the timeSeriesRender property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setTimeSeriesRender(String value) {
+ this.timeSeriesRender = value;
+ }
+
+ /**
+ * Gets the value of the multiSeries property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isMultiSeries() {
+ return multiSeries;
+ }
+
+ /**
+ * Sets the value of the multiSeries property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setMultiSeries(Boolean value) {
+ this.multiSeries = value;
+ }
+
+ /**
+ * Gets the value of the showXAxisLabel property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isShowXAxisLabel() {
+ return showXAxisLabel;
+ }
+
+ /**
+ * Sets the value of the showXAxisLabel property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setShowXAxisLabel(Boolean value) {
+ this.showXAxisLabel = value;
+ }
+
+ /**
+ * Gets the value of the addXAxisTickers property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isAddXAxisTickers() {
+ return addXAxisTickers;
+ }
+
+ /**
+ * Sets the value of the addXAxisTickers property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setAddXAxisTickers(Boolean value) {
+ this.addXAxisTickers = value;
+ }
+
+ /**
+ * Gets the value of the zoomIn property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getZoomIn() {
+ return zoomIn;
+ }
+
+ /**
+ * Sets the value of the zoomIn property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setZoomIn(Integer value) {
+ this.zoomIn = value;
+ }
+
+ /**
+ * Gets the value of the timeAxisType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getTimeAxisType() {
+ return timeAxisType;
+ }
+
+ /**
+ * Sets the value of the timeAxisType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setTimeAxisType(String value) {
+ this.timeAxisType = value;
+ }
+
+ /**
+ * Gets the value of the logScale property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isLogScale() {
+ return logScale;
+ }
+
+ /**
+ * Sets the value of the logScale property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setLogScale(Boolean value) {
+ this.logScale = value;
+ }
+
+ /**
+ * Gets the value of the topMargin property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getTopMargin() {
+ return topMargin;
+ }
+
+ /**
+ * Sets the value of the topMargin property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setTopMargin(Integer value) {
+ this.topMargin = value;
+ }
+
+ /**
+ * Gets the value of the bottomMargin property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getBottomMargin() {
+ return bottomMargin;
+ }
+
+ /**
+ * Sets the value of the bottomMargin property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setBottomMargin(Integer value) {
+ this.bottomMargin = value;
+ }
+
+ /**
+ * Gets the value of the rightMargin property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getRightMargin() {
+ return rightMargin;
+ }
+
+ /**
+ * Sets the value of the rightMargin property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setRightMargin(Integer value) {
+ this.rightMargin = value;
+ }
+
+ /**
+ * Gets the value of the leftMargin property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getLeftMargin() {
+ return leftMargin;
+ }
+
+ /**
+ * Sets the value of the leftMargin property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setLeftMargin(Integer value) {
+ this.leftMargin = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for ChartDrillFormfield complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="ChartDrillFormfield">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="formfield" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "ChartDrillFormfield", propOrder = {
+ "formfield"
+})
+public class ChartDrillFormfield {
+
+ protected String formfield;
+
+ /**
+ * Gets the value of the formfield property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getFormfield() {
+ return formfield;
+ }
+
+ /**
+ * Sets the value of the formfield property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setFormfield(String value) {
+ this.formfield = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for ChartDrillOptions complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="ChartDrillOptions">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="drill_reportId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="drill_xAxis_FormField" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="drill_yAxis_FormField" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="drill_series_FormField" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="targetFormfield" type="{}ChartDrillFormfield" maxOccurs="unbounded" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "ChartDrillOptions", propOrder = {
+ "drillReportId",
+ "drillXAxisFormField",
+ "drillYAxisFormField",
+ "drillSeriesFormField",
+ "targetFormfield"
+})
+public class ChartDrillOptions {
+
+ @XmlElement(name = "drill_reportId")
+ protected String drillReportId;
+ @XmlElement(name = "drill_xAxis_FormField")
+ protected String drillXAxisFormField;
+ @XmlElement(name = "drill_yAxis_FormField")
+ protected String drillYAxisFormField;
+ @XmlElement(name = "drill_series_FormField")
+ protected String drillSeriesFormField;
+ protected List<ChartDrillFormfield> targetFormfield;
+
+ /**
+ * Gets the value of the drillReportId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDrillReportId() {
+ return drillReportId;
+ }
+
+ /**
+ * Sets the value of the drillReportId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDrillReportId(String value) {
+ this.drillReportId = value;
+ }
+
+ /**
+ * Gets the value of the drillXAxisFormField property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDrillXAxisFormField() {
+ return drillXAxisFormField;
+ }
+
+ /**
+ * Sets the value of the drillXAxisFormField property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDrillXAxisFormField(String value) {
+ this.drillXAxisFormField = value;
+ }
+
+ /**
+ * Gets the value of the drillYAxisFormField property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDrillYAxisFormField() {
+ return drillYAxisFormField;
+ }
+
+ /**
+ * Sets the value of the drillYAxisFormField property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDrillYAxisFormField(String value) {
+ this.drillYAxisFormField = value;
+ }
+
+ /**
+ * Gets the value of the drillSeriesFormField property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDrillSeriesFormField() {
+ return drillSeriesFormField;
+ }
+
+ /**
+ * Sets the value of the drillSeriesFormField property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDrillSeriesFormField(String value) {
+ this.drillSeriesFormField = value;
+ }
+
+ /**
+ * Gets the value of the targetFormfield property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the targetFormfield property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getTargetFormfield().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link ChartDrillFormfield }
+ *
+ *
+ */
+ public List<ChartDrillFormfield> getTargetFormfield() {
+ if (targetFormfield == null) {
+ targetFormfield = new ArrayList<ChartDrillFormfield>();
+ }
+ return this.targetFormfield;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for ColFilterList complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="ColFilterList">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="colFilter" type="{}ColFilterType" maxOccurs="unbounded" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "ColFilterList", propOrder = {
+ "colFilter"
+})
+public class ColFilterList {
+
+ protected List<ColFilterType> colFilter;
+
+ /**
+ * Gets the value of the colFilter property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the colFilter property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getColFilter().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link ColFilterType }
+ *
+ *
+ */
+ public List<ColFilterType> getColFilter() {
+ if (colFilter == null) {
+ colFilter = new ArrayList<ColFilterType>();
+ }
+ return this.colFilter;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for ColFilterType complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="ColFilterType">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="colId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="filterSeq" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ * <element name="joinCondition" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="openBrackets" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="expression" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="argType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="argValue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="closeBrackets" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element ref="{}comment" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "ColFilterType", propOrder = {
+ "colId",
+ "filterSeq",
+ "joinCondition",
+ "openBrackets",
+ "expression",
+ "argType",
+ "argValue",
+ "closeBrackets",
+ "comment"
+})
+public class ColFilterType {
+
+ @XmlElement(required = true)
+ protected String colId;
+ protected int filterSeq;
+ @XmlElement(required = true)
+ protected String joinCondition;
+ protected String openBrackets;
+ @XmlElement(required = true)
+ protected String expression;
+ protected String argType;
+ protected String argValue;
+ protected String closeBrackets;
+ protected String comment;
+
+ /**
+ * Gets the value of the colId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getColId() {
+ return colId;
+ }
+
+ /**
+ * Sets the value of the colId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setColId(String value) {
+ this.colId = value;
+ }
+
+ /**
+ * Gets the value of the filterSeq property.
+ *
+ */
+ public int getFilterSeq() {
+ return filterSeq;
+ }
+
+ /**
+ * Sets the value of the filterSeq property.
+ *
+ */
+ public void setFilterSeq(int value) {
+ this.filterSeq = value;
+ }
+
+ /**
+ * Gets the value of the joinCondition property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getJoinCondition() {
+ return joinCondition;
+ }
+
+ /**
+ * Sets the value of the joinCondition property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setJoinCondition(String value) {
+ this.joinCondition = value;
+ }
+
+ /**
+ * Gets the value of the openBrackets property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getOpenBrackets() {
+ return openBrackets;
+ }
+
+ /**
+ * Sets the value of the openBrackets property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setOpenBrackets(String value) {
+ this.openBrackets = value;
+ }
+
+ /**
+ * Gets the value of the expression property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getExpression() {
+ return expression;
+ }
+
+ /**
+ * Sets the value of the expression property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setExpression(String value) {
+ this.expression = value;
+ }
+
+ /**
+ * Gets the value of the argType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getArgType() {
+ return argType;
+ }
+
+ /**
+ * Sets the value of the argType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setArgType(String value) {
+ this.argType = value;
+ }
+
+ /**
+ * Gets the value of the argValue property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getArgValue() {
+ return argValue;
+ }
+
+ /**
+ * Sets the value of the argValue property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setArgValue(String value) {
+ this.argValue = value;
+ }
+
+ /**
+ * Gets the value of the closeBrackets property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getCloseBrackets() {
+ return closeBrackets;
+ }
+
+ /**
+ * Sets the value of the closeBrackets property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setCloseBrackets(String value) {
+ this.closeBrackets = value;
+ }
+
+ /**
+ * Gets the value of the comment property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getComment() {
+ return comment;
+ }
+
+ /**
+ * Sets the value of the comment property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setComment(String value) {
+ this.comment = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlSchemaType;
+import javax.xml.bind.annotation.XmlType;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+
+/**
+ * <p>Java class for CustomReportType complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="CustomReportType">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="reportName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="reportDescr" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="numDashCols" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="dashboardLayoutHTML" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="dbInfo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="dbType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartType" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="chartTypeFixed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartMultiSeries" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartLeftAxisLabel" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartRightAxisLabel" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartWidth" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartHeight" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="showChartTitle" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
+ * <element name="public" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
+ * <element name="hideFormFieldAfterRun" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="createId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="createDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
+ * <element name="reportSQL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="reportTitle" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="reportSubTitle" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="reportHeader" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="frozenColumns" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="pdfImgLogo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="emptyMessage" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="widthNoColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="dataGridAlign" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="reportFooter" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="numFormCols" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="displayOptions" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="jumpTo" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="searchPageSize" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="navPosition" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="toggleLayout" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="pageNav" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="showPageSize" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="showNavPos" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="showGotoOption" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="dataContainerHeight" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="dataContainerWidth" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="allowSchedule" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="multiGroupColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="topDown" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="sizedByContent" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element ref="{}comment" minOccurs="0"/>
+ * <element name="dataSourceList" type="{}DataSourceList" minOccurs="0"/>
+ * <element name="formFieldList" type="{}FormFieldList" minOccurs="0"/>
+ * <element name="javascriptList" type="{}JavascriptList" minOccurs="0"/>
+ * <element name="semaphoreList" type="{}SemaphoreList" minOccurs="0"/>
+ * <element name="dashboardOptions" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="dashboardType" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="reportInNewWindow" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="displayFolderTree" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="maxRowsInExcelDownload" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="dashBoardReports" type="{}DashboardReports" minOccurs="0"/>
+ * <element name="dashBoardReportsNew" type="{}DashboardReportsNew" minOccurs="0"/>
+ * <element name="chartAdditionalOptions" type="{}ChartAdditionalOptions" minOccurs="0"/>
+ * <element name="pdfAdditionalOptions" type="{}PDFAdditionalOptions" minOccurs="0"/>
+ * <element name="chartDrillOptions" type="{}ChartDrillOptions" minOccurs="0"/>
+ * <element name="dataminingOptions" type="{}DataminingOptions" minOccurs="0"/>
+ * <element name="javascriptElement" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="folderId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="drillURLInPoPUpPresent" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="isOneTimeScheduleAllowed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="isHourlyScheduleAllowed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="isDailyScheduleAllowed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="isDailyMFScheduleAllowed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="isWeeklyScheduleAllowed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="isMonthlyScheduleAllowed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="reportMap" type="{}ReportMap" minOccurs="0"/>
+ * </sequence>
+ * <attribute name="pageSize" type="{http://www.w3.org/2001/XMLSchema}int" />
+ * <attribute name="reportType" type="{http://www.w3.org/2001/XMLSchema}string" />
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "CustomReportType", propOrder = {
+ "reportName",
+ "reportDescr",
+ "numDashCols",
+ "dashboardLayoutHTML",
+ "dbInfo",
+ "dbType",
+ "chartType",
+ "chartTypeFixed",
+ "chartMultiSeries",
+ "chartLeftAxisLabel",
+ "chartRightAxisLabel",
+ "chartWidth",
+ "chartHeight",
+ "showChartTitle",
+ "_public",
+ "hideFormFieldAfterRun",
+ "createId",
+ "createDate",
+ "reportSQL",
+ "reportTitle",
+ "reportSubTitle",
+ "reportHeader",
+ "frozenColumns",
+ "pdfImgLogo",
+ "emptyMessage",
+ "widthNoColumn",
+ "dataGridAlign",
+ "reportFooter",
+ "numFormCols",
+ "displayOptions",
+ "jumpTo",
+ "searchPageSize",
+ "navPosition",
+ "toggleLayout",
+ "pageNav",
+ "showPageSize",
+ "showNavPos",
+ "showGotoOption",
+ "dataContainerHeight",
+ "dataContainerWidth",
+ "allowSchedule",
+ "multiGroupColumn",
+ "topDown",
+ "sizedByContent",
+ "comment",
+ "dataSourceList",
+ "formFieldList",
+ "javascriptList",
+ "semaphoreList",
+ "dashboardOptions",
+ "dashboardType",
+ "reportInNewWindow",
+ "displayFolderTree",
+ "maxRowsInExcelDownload",
+ "dashBoardReports",
+ "dashBoardReportsNew",
+ "chartAdditionalOptions",
+ "pdfAdditionalOptions",
+ "chartDrillOptions",
+ "dataminingOptions",
+ "javascriptElement",
+ "folderId",
+ "drillURLInPoPUpPresent",
+ "isOneTimeScheduleAllowed",
+ "isHourlyScheduleAllowed",
+ "isDailyScheduleAllowed",
+ "isDailyMFScheduleAllowed",
+ "isWeeklyScheduleAllowed",
+ "isMonthlyScheduleAllowed",
+ "reportMap"
+})
+public class CustomReportType {
+
+ @XmlElement(required = true)
+ protected String reportName;
+ @XmlElement(required = true)
+ protected String reportDescr;
+ protected String numDashCols;
+ protected String dashboardLayoutHTML;
+ protected String dbInfo;
+ protected String dbType;
+ @XmlElement(required = true)
+ protected String chartType;
+ protected String chartTypeFixed;
+ protected String chartMultiSeries;
+ protected String chartLeftAxisLabel;
+ protected String chartRightAxisLabel;
+ protected String chartWidth;
+ protected String chartHeight;
+ @XmlElement(defaultValue = "false")
+ protected boolean showChartTitle;
+ @XmlElement(name = "public", defaultValue = "false")
+ protected boolean _public;
+ @XmlElement(defaultValue = "false")
+ protected Boolean hideFormFieldAfterRun;
+ @XmlElement(required = true)
+ protected String createId;
+ @XmlElement(required = true)
+ @XmlSchemaType(name = "date")
+ protected XMLGregorianCalendar createDate;
+ protected String reportSQL;
+ protected String reportTitle;
+ protected String reportSubTitle;
+ protected String reportHeader;
+ @XmlElement(defaultValue = "0")
+ protected Integer frozenColumns;
+ protected String pdfImgLogo;
+ protected String emptyMessage;
+ protected String widthNoColumn;
+ protected String dataGridAlign;
+ protected String reportFooter;
+ protected String numFormCols;
+ protected String displayOptions;
+ protected Integer jumpTo;
+ protected Integer searchPageSize;
+ protected String navPosition;
+ @XmlElement(defaultValue = "true")
+ protected Boolean toggleLayout;
+ @XmlElement(defaultValue = "true")
+ protected Boolean pageNav;
+ @XmlElement(defaultValue = "true")
+ protected Boolean showPageSize;
+ @XmlElement(defaultValue = "true")
+ protected Boolean showNavPos;
+ @XmlElement(defaultValue = "true")
+ protected Boolean showGotoOption;
+ protected String dataContainerHeight;
+ protected String dataContainerWidth;
+ protected String allowSchedule;
+ protected String multiGroupColumn;
+ protected String topDown;
+ protected String sizedByContent;
+ protected String comment;
+ protected DataSourceList dataSourceList;
+ protected FormFieldList formFieldList;
+ protected JavascriptList javascriptList;
+ protected SemaphoreList semaphoreList;
+ protected String dashboardOptions;
+ @XmlElement(defaultValue = "false")
+ protected Boolean dashboardType;
+ @XmlElement(defaultValue = "false")
+ protected Boolean reportInNewWindow;
+ @XmlElement(defaultValue = "false")
+ protected Boolean displayFolderTree;
+ protected Integer maxRowsInExcelDownload;
+ protected DashboardReports dashBoardReports;
+ protected DashboardReportsNew dashBoardReportsNew;
+ protected ChartAdditionalOptions chartAdditionalOptions;
+ protected PDFAdditionalOptions pdfAdditionalOptions;
+ protected ChartDrillOptions chartDrillOptions;
+ protected DataminingOptions dataminingOptions;
+ protected String javascriptElement;
+ @XmlElement(defaultValue = "0")
+ protected String folderId;
+ @XmlElement(defaultValue = "false")
+ protected Boolean drillURLInPoPUpPresent;
+ protected String isOneTimeScheduleAllowed;
+ protected String isHourlyScheduleAllowed;
+ protected String isDailyScheduleAllowed;
+ protected String isDailyMFScheduleAllowed;
+ protected String isWeeklyScheduleAllowed;
+ protected String isMonthlyScheduleAllowed;
+ protected ReportMap reportMap;
+ @XmlAttribute(name = "pageSize")
+ protected Integer pageSize;
+ @XmlAttribute(name = "reportType")
+ protected String reportType;
+
+ /**
+ * Gets the value of the reportName property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getReportName() {
+ return reportName;
+ }
+
+ /**
+ * Sets the value of the reportName property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setReportName(String value) {
+ this.reportName = value;
+ }
+
+ /**
+ * Gets the value of the reportDescr property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getReportDescr() {
+ return reportDescr;
+ }
+
+ /**
+ * Sets the value of the reportDescr property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setReportDescr(String value) {
+ this.reportDescr = value;
+ }
+
+ /**
+ * Gets the value of the numDashCols property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getNumDashCols() {
+ return numDashCols;
+ }
+
+ /**
+ * Sets the value of the numDashCols property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setNumDashCols(String value) {
+ this.numDashCols = value;
+ }
+
+ /**
+ * Gets the value of the dashboardLayoutHTML property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDashboardLayoutHTML() {
+ return dashboardLayoutHTML;
+ }
+
+ /**
+ * Sets the value of the dashboardLayoutHTML property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDashboardLayoutHTML(String value) {
+ this.dashboardLayoutHTML = value;
+ }
+
+ /**
+ * Gets the value of the dbInfo property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDbInfo() {
+ return dbInfo;
+ }
+
+ /**
+ * Sets the value of the dbInfo property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDbInfo(String value) {
+ this.dbInfo = value;
+ }
+
+ /**
+ * Gets the value of the dbType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDbType() {
+ return dbType;
+ }
+
+ /**
+ * Sets the value of the dbType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDbType(String value) {
+ this.dbType = value;
+ }
+
+ /**
+ * Gets the value of the chartType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartType() {
+ return chartType;
+ }
+
+ /**
+ * Sets the value of the chartType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartType(String value) {
+ this.chartType = value;
+ }
+
+ /**
+ * Gets the value of the chartTypeFixed property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartTypeFixed() {
+ return chartTypeFixed;
+ }
+
+ /**
+ * Sets the value of the chartTypeFixed property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartTypeFixed(String value) {
+ this.chartTypeFixed = value;
+ }
+
+ /**
+ * Gets the value of the chartMultiSeries property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartMultiSeries() {
+ return chartMultiSeries;
+ }
+
+ /**
+ * Sets the value of the chartMultiSeries property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartMultiSeries(String value) {
+ this.chartMultiSeries = value;
+ }
+
+ /**
+ * Gets the value of the chartLeftAxisLabel property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartLeftAxisLabel() {
+ return chartLeftAxisLabel;
+ }
+
+ /**
+ * Sets the value of the chartLeftAxisLabel property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartLeftAxisLabel(String value) {
+ this.chartLeftAxisLabel = value;
+ }
+
+ /**
+ * Gets the value of the chartRightAxisLabel property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartRightAxisLabel() {
+ return chartRightAxisLabel;
+ }
+
+ /**
+ * Sets the value of the chartRightAxisLabel property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartRightAxisLabel(String value) {
+ this.chartRightAxisLabel = value;
+ }
+
+ /**
+ * Gets the value of the chartWidth property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartWidth() {
+ return chartWidth;
+ }
+
+ /**
+ * Sets the value of the chartWidth property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartWidth(String value) {
+ this.chartWidth = value;
+ }
+
+ /**
+ * Gets the value of the chartHeight property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartHeight() {
+ return chartHeight;
+ }
+
+ /**
+ * Sets the value of the chartHeight property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartHeight(String value) {
+ this.chartHeight = value;
+ }
+
+ /**
+ * Gets the value of the showChartTitle property.
+ *
+ */
+ public boolean isShowChartTitle() {
+ return showChartTitle;
+ }
+
+ /**
+ * Sets the value of the showChartTitle property.
+ *
+ */
+ public void setShowChartTitle(boolean value) {
+ this.showChartTitle = value;
+ }
+
+ /**
+ * Gets the value of the public property.
+ *
+ */
+ public boolean isPublic() {
+ return _public;
+ }
+
+ /**
+ * Sets the value of the public property.
+ *
+ */
+ public void setPublic(boolean value) {
+ this._public = value;
+ }
+
+ /**
+ * Gets the value of the hideFormFieldAfterRun property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isHideFormFieldAfterRun() {
+ return hideFormFieldAfterRun;
+ }
+
+ /**
+ * Sets the value of the hideFormFieldAfterRun property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setHideFormFieldAfterRun(Boolean value) {
+ this.hideFormFieldAfterRun = value;
+ }
+
+ /**
+ * Gets the value of the createId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getCreateId() {
+ return createId;
+ }
+
+ /**
+ * Sets the value of the createId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setCreateId(String value) {
+ this.createId = value;
+ }
+
+ /**
+ * Gets the value of the createDate property.
+ *
+ * @return
+ * possible object is
+ * {@link XMLGregorianCalendar }
+ *
+ */
+ public XMLGregorianCalendar getCreateDate() {
+ return createDate;
+ }
+
+ /**
+ * Sets the value of the createDate property.
+ *
+ * @param value
+ * allowed object is
+ * {@link XMLGregorianCalendar }
+ *
+ */
+ public void setCreateDate(XMLGregorianCalendar value) {
+ this.createDate = value;
+ }
+
+ /**
+ * Gets the value of the reportSQL property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getReportSQL() {
+ return reportSQL;
+ }
+
+ /**
+ * Sets the value of the reportSQL property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setReportSQL(String value) {
+ this.reportSQL = value;
+ }
+
+ /**
+ * Gets the value of the reportTitle property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getReportTitle() {
+ return reportTitle;
+ }
+
+ /**
+ * Sets the value of the reportTitle property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setReportTitle(String value) {
+ this.reportTitle = value;
+ }
+
+ /**
+ * Gets the value of the reportSubTitle property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getReportSubTitle() {
+ return reportSubTitle;
+ }
+
+ /**
+ * Sets the value of the reportSubTitle property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setReportSubTitle(String value) {
+ this.reportSubTitle = value;
+ }
+
+ /**
+ * Gets the value of the reportHeader property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getReportHeader() {
+ return reportHeader;
+ }
+
+ /**
+ * Sets the value of the reportHeader property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setReportHeader(String value) {
+ this.reportHeader = value;
+ }
+
+ /**
+ * Gets the value of the frozenColumns property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getFrozenColumns() {
+ return frozenColumns;
+ }
+
+ /**
+ * Sets the value of the frozenColumns property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setFrozenColumns(Integer value) {
+ this.frozenColumns = value;
+ }
+
+ /**
+ * Gets the value of the pdfImgLogo property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getPdfImgLogo() {
+ return pdfImgLogo;
+ }
+
+ /**
+ * Sets the value of the pdfImgLogo property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setPdfImgLogo(String value) {
+ this.pdfImgLogo = value;
+ }
+
+ /**
+ * Gets the value of the emptyMessage property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getEmptyMessage() {
+ return emptyMessage;
+ }
+
+ /**
+ * Sets the value of the emptyMessage property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setEmptyMessage(String value) {
+ this.emptyMessage = value;
+ }
+
+ /**
+ * Gets the value of the widthNoColumn property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getWidthNoColumn() {
+ return widthNoColumn;
+ }
+
+ /**
+ * Sets the value of the widthNoColumn property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setWidthNoColumn(String value) {
+ this.widthNoColumn = value;
+ }
+
+ /**
+ * Gets the value of the dataGridAlign property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDataGridAlign() {
+ return dataGridAlign;
+ }
+
+ /**
+ * Sets the value of the dataGridAlign property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDataGridAlign(String value) {
+ this.dataGridAlign = value;
+ }
+
+ /**
+ * Gets the value of the reportFooter property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getReportFooter() {
+ return reportFooter;
+ }
+
+ /**
+ * Sets the value of the reportFooter property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setReportFooter(String value) {
+ this.reportFooter = value;
+ }
+
+ /**
+ * Gets the value of the numFormCols property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getNumFormCols() {
+ return numFormCols;
+ }
+
+ /**
+ * Sets the value of the numFormCols property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setNumFormCols(String value) {
+ this.numFormCols = value;
+ }
+
+ /**
+ * Gets the value of the displayOptions property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDisplayOptions() {
+ return displayOptions;
+ }
+
+ /**
+ * Sets the value of the displayOptions property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDisplayOptions(String value) {
+ this.displayOptions = value;
+ }
+
+ /**
+ * Gets the value of the jumpTo property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getJumpTo() {
+ return jumpTo;
+ }
+
+ /**
+ * Sets the value of the jumpTo property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setJumpTo(Integer value) {
+ this.jumpTo = value;
+ }
+
+ /**
+ * Gets the value of the searchPageSize property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getSearchPageSize() {
+ return searchPageSize;
+ }
+
+ /**
+ * Sets the value of the searchPageSize property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setSearchPageSize(Integer value) {
+ this.searchPageSize = value;
+ }
+
+ /**
+ * Gets the value of the navPosition property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getNavPosition() {
+ return navPosition;
+ }
+
+ /**
+ * Sets the value of the navPosition property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setNavPosition(String value) {
+ this.navPosition = value;
+ }
+
+ /**
+ * Gets the value of the toggleLayout property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isToggleLayout() {
+ return toggleLayout;
+ }
+
+ /**
+ * Sets the value of the toggleLayout property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setToggleLayout(Boolean value) {
+ this.toggleLayout = value;
+ }
+
+ /**
+ * Gets the value of the pageNav property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isPageNav() {
+ return pageNav;
+ }
+
+ /**
+ * Sets the value of the pageNav property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setPageNav(Boolean value) {
+ this.pageNav = value;
+ }
+
+ /**
+ * Gets the value of the showPageSize property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isShowPageSize() {
+ return showPageSize;
+ }
+
+ /**
+ * Sets the value of the showPageSize property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setShowPageSize(Boolean value) {
+ this.showPageSize = value;
+ }
+
+ /**
+ * Gets the value of the showNavPos property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isShowNavPos() {
+ return showNavPos;
+ }
+
+ /**
+ * Sets the value of the showNavPos property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setShowNavPos(Boolean value) {
+ this.showNavPos = value;
+ }
+
+ /**
+ * Gets the value of the showGotoOption property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isShowGotoOption() {
+ return showGotoOption;
+ }
+
+ /**
+ * Sets the value of the showGotoOption property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setShowGotoOption(Boolean value) {
+ this.showGotoOption = value;
+ }
+
+ /**
+ * Gets the value of the dataContainerHeight property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDataContainerHeight() {
+ return dataContainerHeight;
+ }
+
+ /**
+ * Sets the value of the dataContainerHeight property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDataContainerHeight(String value) {
+ this.dataContainerHeight = value;
+ }
+
+ /**
+ * Gets the value of the dataContainerWidth property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDataContainerWidth() {
+ return dataContainerWidth;
+ }
+
+ /**
+ * Sets the value of the dataContainerWidth property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDataContainerWidth(String value) {
+ this.dataContainerWidth = value;
+ }
+
+ /**
+ * Gets the value of the allowSchedule property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getAllowSchedule() {
+ return allowSchedule;
+ }
+
+ /**
+ * Sets the value of the allowSchedule property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setAllowSchedule(String value) {
+ this.allowSchedule = value;
+ }
+
+ /**
+ * Gets the value of the multiGroupColumn property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getMultiGroupColumn() {
+ return multiGroupColumn;
+ }
+
+ /**
+ * Sets the value of the multiGroupColumn property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setMultiGroupColumn(String value) {
+ this.multiGroupColumn = value;
+ }
+
+ /**
+ * Gets the value of the topDown property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getTopDown() {
+ return topDown;
+ }
+
+ /**
+ * Sets the value of the topDown property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setTopDown(String value) {
+ this.topDown = value;
+ }
+
+ /**
+ * Gets the value of the sizedByContent property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getSizedByContent() {
+ return sizedByContent;
+ }
+
+ /**
+ * Sets the value of the sizedByContent property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setSizedByContent(String value) {
+ this.sizedByContent = value;
+ }
+
+ /**
+ * Gets the value of the comment property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getComment() {
+ return comment;
+ }
+
+ /**
+ * Sets the value of the comment property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setComment(String value) {
+ this.comment = value;
+ }
+
+ /**
+ * Gets the value of the dataSourceList property.
+ *
+ * @return
+ * possible object is
+ * {@link DataSourceList }
+ *
+ */
+ public DataSourceList getDataSourceList() {
+ return dataSourceList;
+ }
+
+ /**
+ * Sets the value of the dataSourceList property.
+ *
+ * @param value
+ * allowed object is
+ * {@link DataSourceList }
+ *
+ */
+ public void setDataSourceList(DataSourceList value) {
+ this.dataSourceList = value;
+ }
+
+ /**
+ * Gets the value of the formFieldList property.
+ *
+ * @return
+ * possible object is
+ * {@link FormFieldList }
+ *
+ */
+ public FormFieldList getFormFieldList() {
+ return formFieldList;
+ }
+
+ /**
+ * Sets the value of the formFieldList property.
+ *
+ * @param value
+ * allowed object is
+ * {@link FormFieldList }
+ *
+ */
+ public void setFormFieldList(FormFieldList value) {
+ this.formFieldList = value;
+ }
+
+ /**
+ * Gets the value of the javascriptList property.
+ *
+ * @return
+ * possible object is
+ * {@link JavascriptList }
+ *
+ */
+ public JavascriptList getJavascriptList() {
+ return javascriptList;
+ }
+
+ /**
+ * Sets the value of the javascriptList property.
+ *
+ * @param value
+ * allowed object is
+ * {@link JavascriptList }
+ *
+ */
+ public void setJavascriptList(JavascriptList value) {
+ this.javascriptList = value;
+ }
+
+ /**
+ * Gets the value of the semaphoreList property.
+ *
+ * @return
+ * possible object is
+ * {@link SemaphoreList }
+ *
+ */
+ public SemaphoreList getSemaphoreList() {
+ return semaphoreList;
+ }
+
+ /**
+ * Sets the value of the semaphoreList property.
+ *
+ * @param value
+ * allowed object is
+ * {@link SemaphoreList }
+ *
+ */
+ public void setSemaphoreList(SemaphoreList value) {
+ this.semaphoreList = value;
+ }
+
+ /**
+ * Gets the value of the dashboardOptions property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDashboardOptions() {
+ return dashboardOptions;
+ }
+
+ /**
+ * Sets the value of the dashboardOptions property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDashboardOptions(String value) {
+ this.dashboardOptions = value;
+ }
+
+ /**
+ * Gets the value of the dashboardType property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isDashboardType() {
+ return dashboardType;
+ }
+
+ /**
+ * Sets the value of the dashboardType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setDashboardType(Boolean value) {
+ this.dashboardType = value;
+ }
+
+ /**
+ * Gets the value of the reportInNewWindow property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isReportInNewWindow() {
+ return reportInNewWindow;
+ }
+
+ /**
+ * Sets the value of the reportInNewWindow property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setReportInNewWindow(Boolean value) {
+ this.reportInNewWindow = value;
+ }
+
+ /**
+ * Gets the value of the displayFolderTree property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isDisplayFolderTree() {
+ return displayFolderTree;
+ }
+
+ /**
+ * Sets the value of the displayFolderTree property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setDisplayFolderTree(Boolean value) {
+ this.displayFolderTree = value;
+ }
+
+ /**
+ * Gets the value of the maxRowsInExcelDownload property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getMaxRowsInExcelDownload() {
+ return maxRowsInExcelDownload;
+ }
+
+ /**
+ * Sets the value of the maxRowsInExcelDownload property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setMaxRowsInExcelDownload(Integer value) {
+ this.maxRowsInExcelDownload = value;
+ }
+
+ /**
+ * Gets the value of the dashBoardReports property.
+ *
+ * @return
+ * possible object is
+ * {@link DashboardReports }
+ *
+ */
+ public DashboardReports getDashBoardReports() {
+ return dashBoardReports;
+ }
+
+ /**
+ * Sets the value of the dashBoardReports property.
+ *
+ * @param value
+ * allowed object is
+ * {@link DashboardReports }
+ *
+ */
+ public void setDashBoardReports(DashboardReports value) {
+ this.dashBoardReports = value;
+ }
+
+ /**
+ * Gets the value of the dashBoardReportsNew property.
+ *
+ * @return
+ * possible object is
+ * {@link DashboardReportsNew }
+ *
+ */
+ public DashboardReportsNew getDashBoardReportsNew() {
+ return dashBoardReportsNew;
+ }
+
+ /**
+ * Sets the value of the dashBoardReportsNew property.
+ *
+ * @param value
+ * allowed object is
+ * {@link DashboardReportsNew }
+ *
+ */
+ public void setDashBoardReportsNew(DashboardReportsNew value) {
+ this.dashBoardReportsNew = value;
+ }
+
+ /**
+ * Gets the value of the chartAdditionalOptions property.
+ *
+ * @return
+ * possible object is
+ * {@link ChartAdditionalOptions }
+ *
+ */
+ public ChartAdditionalOptions getChartAdditionalOptions() {
+ return chartAdditionalOptions;
+ }
+
+ /**
+ * Sets the value of the chartAdditionalOptions property.
+ *
+ * @param value
+ * allowed object is
+ * {@link ChartAdditionalOptions }
+ *
+ */
+ public void setChartAdditionalOptions(ChartAdditionalOptions value) {
+ this.chartAdditionalOptions = value;
+ }
+
+ /**
+ * Gets the value of the pdfAdditionalOptions property.
+ *
+ * @return
+ * possible object is
+ * {@link PDFAdditionalOptions }
+ *
+ */
+ public PDFAdditionalOptions getPdfAdditionalOptions() {
+ return pdfAdditionalOptions;
+ }
+
+ /**
+ * Sets the value of the pdfAdditionalOptions property.
+ *
+ * @param value
+ * allowed object is
+ * {@link PDFAdditionalOptions }
+ *
+ */
+ public void setPdfAdditionalOptions(PDFAdditionalOptions value) {
+ this.pdfAdditionalOptions = value;
+ }
+
+ /**
+ * Gets the value of the chartDrillOptions property.
+ *
+ * @return
+ * possible object is
+ * {@link ChartDrillOptions }
+ *
+ */
+ public ChartDrillOptions getChartDrillOptions() {
+ return chartDrillOptions;
+ }
+
+ /**
+ * Sets the value of the chartDrillOptions property.
+ *
+ * @param value
+ * allowed object is
+ * {@link ChartDrillOptions }
+ *
+ */
+ public void setChartDrillOptions(ChartDrillOptions value) {
+ this.chartDrillOptions = value;
+ }
+
+ /**
+ * Gets the value of the dataminingOptions property.
+ *
+ * @return
+ * possible object is
+ * {@link DataminingOptions }
+ *
+ */
+ public DataminingOptions getDataminingOptions() {
+ return dataminingOptions;
+ }
+
+ /**
+ * Sets the value of the dataminingOptions property.
+ *
+ * @param value
+ * allowed object is
+ * {@link DataminingOptions }
+ *
+ */
+ public void setDataminingOptions(DataminingOptions value) {
+ this.dataminingOptions = value;
+ }
+
+ /**
+ * Gets the value of the javascriptElement property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getJavascriptElement() {
+ return javascriptElement;
+ }
+
+ /**
+ * Sets the value of the javascriptElement property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setJavascriptElement(String value) {
+ this.javascriptElement = value;
+ }
+
+ /**
+ * Gets the value of the folderId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getFolderId() {
+ return folderId;
+ }
+
+ /**
+ * Sets the value of the folderId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setFolderId(String value) {
+ this.folderId = value;
+ }
+
+ /**
+ * Gets the value of the drillURLInPoPUpPresent property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isDrillURLInPoPUpPresent() {
+ return drillURLInPoPUpPresent;
+ }
+
+ /**
+ * Sets the value of the drillURLInPoPUpPresent property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setDrillURLInPoPUpPresent(Boolean value) {
+ this.drillURLInPoPUpPresent = value;
+ }
+
+ /**
+ * Gets the value of the isOneTimeScheduleAllowed property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getIsOneTimeScheduleAllowed() {
+ return isOneTimeScheduleAllowed;
+ }
+
+ /**
+ * Sets the value of the isOneTimeScheduleAllowed property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setIsOneTimeScheduleAllowed(String value) {
+ this.isOneTimeScheduleAllowed = value;
+ }
+
+ /**
+ * Gets the value of the isHourlyScheduleAllowed property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getIsHourlyScheduleAllowed() {
+ return isHourlyScheduleAllowed;
+ }
+
+ /**
+ * Sets the value of the isHourlyScheduleAllowed property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setIsHourlyScheduleAllowed(String value) {
+ this.isHourlyScheduleAllowed = value;
+ }
+
+ /**
+ * Gets the value of the isDailyScheduleAllowed property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getIsDailyScheduleAllowed() {
+ return isDailyScheduleAllowed;
+ }
+
+ /**
+ * Sets the value of the isDailyScheduleAllowed property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setIsDailyScheduleAllowed(String value) {
+ this.isDailyScheduleAllowed = value;
+ }
+
+ /**
+ * Gets the value of the isDailyMFScheduleAllowed property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getIsDailyMFScheduleAllowed() {
+ return isDailyMFScheduleAllowed;
+ }
+
+ /**
+ * Sets the value of the isDailyMFScheduleAllowed property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setIsDailyMFScheduleAllowed(String value) {
+ this.isDailyMFScheduleAllowed = value;
+ }
+
+ /**
+ * Gets the value of the isWeeklyScheduleAllowed property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getIsWeeklyScheduleAllowed() {
+ return isWeeklyScheduleAllowed;
+ }
+
+ /**
+ * Sets the value of the isWeeklyScheduleAllowed property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setIsWeeklyScheduleAllowed(String value) {
+ this.isWeeklyScheduleAllowed = value;
+ }
+
+ /**
+ * Gets the value of the isMonthlyScheduleAllowed property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getIsMonthlyScheduleAllowed() {
+ return isMonthlyScheduleAllowed;
+ }
+
+ /**
+ * Sets the value of the isMonthlyScheduleAllowed property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setIsMonthlyScheduleAllowed(String value) {
+ this.isMonthlyScheduleAllowed = value;
+ }
+
+ /**
+ * Gets the value of the reportMap property.
+ *
+ * @return
+ * possible object is
+ * {@link ReportMap }
+ *
+ */
+ public ReportMap getReportMap() {
+ return reportMap;
+ }
+
+ /**
+ * Sets the value of the reportMap property.
+ *
+ * @param value
+ * allowed object is
+ * {@link ReportMap }
+ *
+ */
+ public void setReportMap(ReportMap value) {
+ this.reportMap = value;
+ }
+
+ /**
+ * Gets the value of the pageSize property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getPageSize() {
+ return pageSize;
+ }
+
+ /**
+ * Sets the value of the pageSize property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setPageSize(Integer value) {
+ this.pageSize = value;
+ }
+
+ /**
+ * Gets the value of the reportType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getReportType() {
+ return reportType;
+ }
+
+ /**
+ * Sets the value of the reportType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setReportType(String value) {
+ this.reportType = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for DashboardEditorList complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="DashboardEditorList">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="editorList" type="{}DashboardEditorReport" maxOccurs="unbounded" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "DashboardEditorList", propOrder = {
+ "editorList"
+})
+public class DashboardEditorList {
+
+ protected List<DashboardEditorReport> editorList;
+
+ /**
+ * Gets the value of the editorList property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the editorList property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getEditorList().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link DashboardEditorReport }
+ *
+ *
+ */
+ public List<DashboardEditorReport> getEditorList() {
+ if (editorList == null) {
+ editorList = new ArrayList<DashboardEditorReport>();
+ }
+ return this.editorList;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for DashboardEditorReport complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="DashboardEditorReport">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="reportId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="reportName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="dataType" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="position" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "DashboardEditorReport", propOrder = {
+ "reportId",
+ "reportName",
+ "dataType",
+ "position"
+})
+public class DashboardEditorReport {
+
+ @XmlElement(required = true)
+ protected String reportId;
+ @XmlElement(required = true)
+ protected String reportName;
+ @XmlElement(required = true)
+ protected String dataType;
+ @XmlElement(required = true)
+ protected String position;
+
+ /**
+ * Gets the value of the reportId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getReportId() {
+ return reportId;
+ }
+
+ /**
+ * Sets the value of the reportId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setReportId(String value) {
+ this.reportId = value;
+ }
+
+ /**
+ * Gets the value of the reportName property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getReportName() {
+ return reportName;
+ }
+
+ /**
+ * Sets the value of the reportName property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setReportName(String value) {
+ this.reportName = value;
+ }
+
+ /**
+ * Gets the value of the dataType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDataType() {
+ return dataType;
+ }
+
+ /**
+ * Sets the value of the dataType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDataType(String value) {
+ this.dataType = value;
+ }
+
+ /**
+ * Gets the value of the position property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getPosition() {
+ return position;
+ }
+
+ /**
+ * Sets the value of the position property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setPosition(String value) {
+ this.position = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for DashboardReports complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="DashboardReports">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="reportsList" type="{}Reports" maxOccurs="unbounded" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "DashboardReports", propOrder = {
+ "reportsList"
+})
+public class DashboardReports {
+
+ protected List<Reports> reportsList;
+
+ /**
+ * Gets the value of the reportsList property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the reportsList property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getReportsList().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link Reports }
+ *
+ *
+ */
+ public List<Reports> getReportsList() {
+ if (reportsList == null) {
+ reportsList = new ArrayList<Reports>();
+ }
+ return this.reportsList;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for DashboardReportsNew complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="DashboardReportsNew">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="reportsList" type="{}Reports" maxOccurs="unbounded" minOccurs="0"/>
+ * <element name="dashboardEditor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="dashboardEditorList" type="{}DashboardEditorList" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "DashboardReportsNew", propOrder = {
+ "reportsList",
+ "dashboardEditor",
+ "dashboardEditorList"
+})
+public class DashboardReportsNew {
+
+ protected List<Reports> reportsList;
+ protected String dashboardEditor;
+ protected DashboardEditorList dashboardEditorList;
+
+ /**
+ * Gets the value of the reportsList property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the reportsList property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getReportsList().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link Reports }
+ *
+ *
+ */
+ public List<Reports> getReportsList() {
+ if (reportsList == null) {
+ reportsList = new ArrayList<Reports>();
+ }
+ return this.reportsList;
+ }
+
+ /**
+ * Gets the value of the dashboardEditor property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDashboardEditor() {
+ return dashboardEditor;
+ }
+
+ /**
+ * Sets the value of the dashboardEditor property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDashboardEditor(String value) {
+ this.dashboardEditor = value;
+ }
+
+ /**
+ * Gets the value of the dashboardEditorList property.
+ *
+ * @return
+ * possible object is
+ * {@link DashboardEditorList }
+ *
+ */
+ public DashboardEditorList getDashboardEditorList() {
+ return dashboardEditorList;
+ }
+
+ /**
+ * Sets the value of the dashboardEditorList property.
+ *
+ * @param value
+ * allowed object is
+ * {@link DashboardEditorList }
+ *
+ */
+ public void setDashboardEditorList(DashboardEditorList value) {
+ this.dashboardEditorList = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for DataColumnList complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="DataColumnList">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="dataColumn" type="{}DataColumnType" maxOccurs="unbounded"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "DataColumnList", propOrder = {
+ "dataColumn"
+})
+public class DataColumnList {
+
+ @XmlElement(required = true)
+ protected List<DataColumnType> dataColumn;
+
+ /**
+ * Gets the value of the dataColumn property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the dataColumn property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getDataColumn().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link DataColumnType }
+ *
+ *
+ */
+ public List<DataColumnType> getDataColumn() {
+ if (dataColumn == null) {
+ dataColumn = new ArrayList<DataColumnType>();
+ }
+ return this.dataColumn;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for DataColumnType complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="DataColumnType">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="tableId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="dbColName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="crossTabValue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="colName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="displayName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="displayWidth" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="displayWidthInPxls" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="pdfDisplayWidthInPxls" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="displayAlignment" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="displayHeaderAlignment" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="orderSeq" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ * <element name="visible" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
+ * <element name="calculated" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
+ * <element name="colType" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="hyperlinkURL" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="hyperlinkType" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="actionImg" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="groupByPos" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="subTotalCustomText" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="hideRepeatedKey" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="colFormat" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="groupBreak" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
+ * <element name="orderBySeq" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="orderByAscDesc" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="displayTotal" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="colOnChart" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartSeq" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="chartColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartLineType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartSeries" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="isRangeAxisFilled" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="isSortable" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="createInNewChart" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="drillDownType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="drillinPoPUp" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="drillDownURL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="drillDownParams" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element ref="{}comment" minOccurs="0"/>
+ * <element name="colFilterList" type="{}ColFilterList" minOccurs="0"/>
+ * <element name="semaphoreId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="dbColType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="chartGroup" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="yAxis" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="dependsOnFormField" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="nowrap" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="indentation" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="enhancedPagination" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="level" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="start" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="colspan" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="dataMiningCol" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * </sequence>
+ * <attribute name="colId" type="{http://www.w3.org/2001/XMLSchema}string" />
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "DataColumnType", propOrder = {
+ "tableId",
+ "dbColName",
+ "crossTabValue",
+ "colName",
+ "displayName",
+ "displayWidth",
+ "displayWidthInPxls",
+ "pdfDisplayWidthInPxls",
+ "displayAlignment",
+ "displayHeaderAlignment",
+ "orderSeq",
+ "visible",
+ "calculated",
+ "colType",
+ "hyperlinkURL",
+ "hyperlinkType",
+ "actionImg",
+ "groupByPos",
+ "subTotalCustomText",
+ "hideRepeatedKey",
+ "colFormat",
+ "groupBreak",
+ "orderBySeq",
+ "orderByAscDesc",
+ "displayTotal",
+ "colOnChart",
+ "chartSeq",
+ "chartColor",
+ "chartLineType",
+ "chartSeries",
+ "isRangeAxisFilled",
+ "isSortable",
+ "createInNewChart",
+ "drillDownType",
+ "drillinPoPUp",
+ "drillDownURL",
+ "drillDownParams",
+ "comment",
+ "colFilterList",
+ "semaphoreId",
+ "dbColType",
+ "chartGroup",
+ "yAxis",
+ "dependsOnFormField",
+ "nowrap",
+ "indentation",
+ "enhancedPagination",
+ "level",
+ "start",
+ "colspan",
+ "dataMiningCol"
+})
+public class DataColumnType {
+
+ @XmlElement(required = true)
+ protected String tableId;
+ @XmlElement(required = true)
+ protected String dbColName;
+ protected String crossTabValue;
+ @XmlElement(required = true)
+ protected String colName;
+ @XmlElement(required = true)
+ protected String displayName;
+ protected Integer displayWidth;
+ protected String displayWidthInPxls;
+ protected String pdfDisplayWidthInPxls;
+ protected String displayAlignment;
+ protected String displayHeaderAlignment;
+ protected int orderSeq;
+ @XmlElement(defaultValue = "true")
+ protected boolean visible;
+ @XmlElement(defaultValue = "false")
+ protected boolean calculated;
+ @XmlElement(required = true)
+ protected String colType;
+ @XmlElement(required = true)
+ protected String hyperlinkURL;
+ @XmlElement(required = true)
+ protected String hyperlinkType;
+ @XmlElement(required = true)
+ protected String actionImg;
+ protected Integer groupByPos;
+ protected String subTotalCustomText;
+ @XmlElement(defaultValue = "false")
+ protected Boolean hideRepeatedKey;
+ protected String colFormat;
+ @XmlElement(defaultValue = "false")
+ protected boolean groupBreak;
+ protected Integer orderBySeq;
+ protected String orderByAscDesc;
+ protected String displayTotal;
+ protected String colOnChart;
+ protected Integer chartSeq;
+ protected String chartColor;
+ protected String chartLineType;
+ @XmlElement(defaultValue = "false")
+ protected Boolean chartSeries;
+ @XmlElement(defaultValue = "false")
+ protected Boolean isRangeAxisFilled;
+ @XmlElement(defaultValue = "false")
+ protected Boolean isSortable;
+ @XmlElement(defaultValue = "false")
+ protected Boolean createInNewChart;
+ protected String drillDownType;
+ @XmlElement(defaultValue = "false")
+ protected Boolean drillinPoPUp;
+ protected String drillDownURL;
+ protected String drillDownParams;
+ protected String comment;
+ protected ColFilterList colFilterList;
+ protected String semaphoreId;
+ protected String dbColType;
+ protected String chartGroup;
+ protected String yAxis;
+ protected String dependsOnFormField;
+ protected String nowrap;
+ @XmlElement(defaultValue = "0")
+ protected Integer indentation;
+ @XmlElement(defaultValue = "false")
+ protected Boolean enhancedPagination;
+ @XmlElement(defaultValue = "0")
+ protected Integer level;
+ @XmlElement(defaultValue = "0")
+ protected Integer start;
+ @XmlElement(defaultValue = "0")
+ protected Integer colspan;
+ protected String dataMiningCol;
+ @XmlAttribute(name = "colId")
+ protected String colId;
+
+ /**
+ * Gets the value of the tableId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getTableId() {
+ return tableId;
+ }
+
+ /**
+ * Sets the value of the tableId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setTableId(String value) {
+ this.tableId = value;
+ }
+
+ /**
+ * Gets the value of the dbColName property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDbColName() {
+ return dbColName;
+ }
+
+ /**
+ * Sets the value of the dbColName property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDbColName(String value) {
+ this.dbColName = value;
+ }
+
+ /**
+ * Gets the value of the crossTabValue property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getCrossTabValue() {
+ return crossTabValue;
+ }
+
+ /**
+ * Sets the value of the crossTabValue property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setCrossTabValue(String value) {
+ this.crossTabValue = value;
+ }
+
+ /**
+ * Gets the value of the colName property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getColName() {
+ return colName;
+ }
+
+ /**
+ * Sets the value of the colName property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setColName(String value) {
+ this.colName = value;
+ }
+
+ /**
+ * Gets the value of the displayName property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ /**
+ * Sets the value of the displayName property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDisplayName(String value) {
+ this.displayName = value;
+ }
+
+ /**
+ * Gets the value of the displayWidth property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getDisplayWidth() {
+ return displayWidth;
+ }
+
+ /**
+ * Sets the value of the displayWidth property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setDisplayWidth(Integer value) {
+ this.displayWidth = value;
+ }
+
+ /**
+ * Gets the value of the displayWidthInPxls property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDisplayWidthInPxls() {
+ return displayWidthInPxls;
+ }
+
+ /**
+ * Sets the value of the displayWidthInPxls property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDisplayWidthInPxls(String value) {
+ this.displayWidthInPxls = value;
+ }
+
+ /**
+ * Gets the value of the pdfDisplayWidthInPxls property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getPdfDisplayWidthInPxls() {
+ return pdfDisplayWidthInPxls;
+ }
+
+ /**
+ * Sets the value of the pdfDisplayWidthInPxls property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setPdfDisplayWidthInPxls(String value) {
+ this.pdfDisplayWidthInPxls = value;
+ }
+
+ /**
+ * Gets the value of the displayAlignment property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDisplayAlignment() {
+ return displayAlignment;
+ }
+
+ /**
+ * Sets the value of the displayAlignment property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDisplayAlignment(String value) {
+ this.displayAlignment = value;
+ }
+
+ /**
+ * Gets the value of the displayHeaderAlignment property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDisplayHeaderAlignment() {
+ return displayHeaderAlignment;
+ }
+
+ /**
+ * Sets the value of the displayHeaderAlignment property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDisplayHeaderAlignment(String value) {
+ this.displayHeaderAlignment = value;
+ }
+
+ /**
+ * Gets the value of the orderSeq property.
+ *
+ */
+ public int getOrderSeq() {
+ return orderSeq;
+ }
+
+ /**
+ * Sets the value of the orderSeq property.
+ *
+ */
+ public void setOrderSeq(int value) {
+ this.orderSeq = value;
+ }
+
+ /**
+ * Gets the value of the visible property.
+ *
+ */
+ public boolean isVisible() {
+ return visible;
+ }
+
+ /**
+ * Sets the value of the visible property.
+ *
+ */
+ public void setVisible(boolean value) {
+ this.visible = value;
+ }
+
+ /**
+ * Gets the value of the calculated property.
+ *
+ */
+ public boolean isCalculated() {
+ return calculated;
+ }
+
+ /**
+ * Sets the value of the calculated property.
+ *
+ */
+ public void setCalculated(boolean value) {
+ this.calculated = value;
+ }
+
+ /**
+ * Gets the value of the colType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getColType() {
+ return colType;
+ }
+
+ /**
+ * Sets the value of the colType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setColType(String value) {
+ this.colType = value;
+ }
+
+ /**
+ * Gets the value of the hyperlinkURL property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getHyperlinkURL() {
+ return hyperlinkURL;
+ }
+
+ /**
+ * Sets the value of the hyperlinkURL property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setHyperlinkURL(String value) {
+ this.hyperlinkURL = value;
+ }
+
+ /**
+ * Gets the value of the hyperlinkType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getHyperlinkType() {
+ return hyperlinkType;
+ }
+
+ /**
+ * Sets the value of the hyperlinkType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setHyperlinkType(String value) {
+ this.hyperlinkType = value;
+ }
+
+ /**
+ * Gets the value of the actionImg property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getActionImg() {
+ return actionImg;
+ }
+
+ /**
+ * Sets the value of the actionImg property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setActionImg(String value) {
+ this.actionImg = value;
+ }
+
+ /**
+ * Gets the value of the groupByPos property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getGroupByPos() {
+ return groupByPos;
+ }
+
+ /**
+ * Sets the value of the groupByPos property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setGroupByPos(Integer value) {
+ this.groupByPos = value;
+ }
+
+ /**
+ * Gets the value of the subTotalCustomText property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getSubTotalCustomText() {
+ return subTotalCustomText;
+ }
+
+ /**
+ * Sets the value of the subTotalCustomText property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setSubTotalCustomText(String value) {
+ this.subTotalCustomText = value;
+ }
+
+ /**
+ * Gets the value of the hideRepeatedKey property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isHideRepeatedKey() {
+ return hideRepeatedKey;
+ }
+
+ /**
+ * Sets the value of the hideRepeatedKey property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setHideRepeatedKey(Boolean value) {
+ this.hideRepeatedKey = value;
+ }
+
+ /**
+ * Gets the value of the colFormat property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getColFormat() {
+ return colFormat;
+ }
+
+ /**
+ * Sets the value of the colFormat property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setColFormat(String value) {
+ this.colFormat = value;
+ }
+
+ /**
+ * Gets the value of the groupBreak property.
+ *
+ */
+ public boolean isGroupBreak() {
+ return groupBreak;
+ }
+
+ /**
+ * Sets the value of the groupBreak property.
+ *
+ */
+ public void setGroupBreak(boolean value) {
+ this.groupBreak = value;
+ }
+
+ /**
+ * Gets the value of the orderBySeq property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getOrderBySeq() {
+ return orderBySeq;
+ }
+
+ /**
+ * Sets the value of the orderBySeq property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setOrderBySeq(Integer value) {
+ this.orderBySeq = value;
+ }
+
+ /**
+ * Gets the value of the orderByAscDesc property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getOrderByAscDesc() {
+ return orderByAscDesc;
+ }
+
+ /**
+ * Sets the value of the orderByAscDesc property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setOrderByAscDesc(String value) {
+ this.orderByAscDesc = value;
+ }
+
+ /**
+ * Gets the value of the displayTotal property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDisplayTotal() {
+ return displayTotal;
+ }
+
+ /**
+ * Sets the value of the displayTotal property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDisplayTotal(String value) {
+ this.displayTotal = value;
+ }
+
+ /**
+ * Gets the value of the colOnChart property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getColOnChart() {
+ return colOnChart;
+ }
+
+ /**
+ * Sets the value of the colOnChart property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setColOnChart(String value) {
+ this.colOnChart = value;
+ }
+
+ /**
+ * Gets the value of the chartSeq property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getChartSeq() {
+ return chartSeq;
+ }
+
+ /**
+ * Sets the value of the chartSeq property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setChartSeq(Integer value) {
+ this.chartSeq = value;
+ }
+
+ /**
+ * Gets the value of the chartColor property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartColor() {
+ return chartColor;
+ }
+
+ /**
+ * Sets the value of the chartColor property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartColor(String value) {
+ this.chartColor = value;
+ }
+
+ /**
+ * Gets the value of the chartLineType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartLineType() {
+ return chartLineType;
+ }
+
+ /**
+ * Sets the value of the chartLineType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartLineType(String value) {
+ this.chartLineType = value;
+ }
+
+ /**
+ * Gets the value of the chartSeries property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isChartSeries() {
+ return chartSeries;
+ }
+
+ /**
+ * Sets the value of the chartSeries property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setChartSeries(Boolean value) {
+ this.chartSeries = value;
+ }
+
+ /**
+ * Gets the value of the isRangeAxisFilled property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isIsRangeAxisFilled() {
+ return isRangeAxisFilled;
+ }
+
+ /**
+ * Sets the value of the isRangeAxisFilled property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setIsRangeAxisFilled(Boolean value) {
+ this.isRangeAxisFilled = value;
+ }
+
+ /**
+ * Gets the value of the isSortable property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isIsSortable() {
+ return isSortable;
+ }
+
+ /**
+ * Sets the value of the isSortable property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setIsSortable(Boolean value) {
+ this.isSortable = value;
+ }
+
+ /**
+ * Gets the value of the createInNewChart property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isCreateInNewChart() {
+ return createInNewChart;
+ }
+
+ /**
+ * Sets the value of the createInNewChart property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setCreateInNewChart(Boolean value) {
+ this.createInNewChart = value;
+ }
+
+ /**
+ * Gets the value of the drillDownType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDrillDownType() {
+ return drillDownType;
+ }
+
+ /**
+ * Sets the value of the drillDownType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDrillDownType(String value) {
+ this.drillDownType = value;
+ }
+
+ /**
+ * Gets the value of the drillinPoPUp property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isDrillinPoPUp() {
+ return drillinPoPUp;
+ }
+
+ /**
+ * Sets the value of the drillinPoPUp property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setDrillinPoPUp(Boolean value) {
+ this.drillinPoPUp = value;
+ }
+
+ /**
+ * Gets the value of the drillDownURL property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDrillDownURL() {
+ return drillDownURL;
+ }
+
+ /**
+ * Sets the value of the drillDownURL property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDrillDownURL(String value) {
+ this.drillDownURL = value;
+ }
+
+ /**
+ * Gets the value of the drillDownParams property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDrillDownParams() {
+ return drillDownParams;
+ }
+
+ /**
+ * Sets the value of the drillDownParams property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDrillDownParams(String value) {
+ this.drillDownParams = value;
+ }
+
+ /**
+ * Gets the value of the comment property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getComment() {
+ return comment;
+ }
+
+ /**
+ * Sets the value of the comment property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setComment(String value) {
+ this.comment = value;
+ }
+
+ /**
+ * Gets the value of the colFilterList property.
+ *
+ * @return
+ * possible object is
+ * {@link ColFilterList }
+ *
+ */
+ public ColFilterList getColFilterList() {
+ return colFilterList;
+ }
+
+ /**
+ * Sets the value of the colFilterList property.
+ *
+ * @param value
+ * allowed object is
+ * {@link ColFilterList }
+ *
+ */
+ public void setColFilterList(ColFilterList value) {
+ this.colFilterList = value;
+ }
+
+ /**
+ * Gets the value of the semaphoreId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getSemaphoreId() {
+ return semaphoreId;
+ }
+
+ /**
+ * Sets the value of the semaphoreId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setSemaphoreId(String value) {
+ this.semaphoreId = value;
+ }
+
+ /**
+ * Gets the value of the dbColType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDbColType() {
+ return dbColType;
+ }
+
+ /**
+ * Sets the value of the dbColType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDbColType(String value) {
+ this.dbColType = value;
+ }
+
+ /**
+ * Gets the value of the chartGroup property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getChartGroup() {
+ return chartGroup;
+ }
+
+ /**
+ * Sets the value of the chartGroup property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setChartGroup(String value) {
+ this.chartGroup = value;
+ }
+
+ /**
+ * Gets the value of the yAxis property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getYAxis() {
+ return yAxis;
+ }
+
+ /**
+ * Sets the value of the yAxis property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setYAxis(String value) {
+ this.yAxis = value;
+ }
+
+ /**
+ * Gets the value of the dependsOnFormField property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDependsOnFormField() {
+ return dependsOnFormField;
+ }
+
+ /**
+ * Sets the value of the dependsOnFormField property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDependsOnFormField(String value) {
+ this.dependsOnFormField = value;
+ }
+
+ /**
+ * Gets the value of the nowrap property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getNowrap() {
+ return nowrap;
+ }
+
+ /**
+ * Sets the value of the nowrap property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setNowrap(String value) {
+ this.nowrap = value;
+ }
+
+ /**
+ * Gets the value of the indentation property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getIndentation() {
+ return indentation;
+ }
+
+ /**
+ * Sets the value of the indentation property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setIndentation(Integer value) {
+ this.indentation = value;
+ }
+
+ /**
+ * Gets the value of the enhancedPagination property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isEnhancedPagination() {
+ return enhancedPagination;
+ }
+
+ /**
+ * Sets the value of the enhancedPagination property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setEnhancedPagination(Boolean value) {
+ this.enhancedPagination = value;
+ }
+
+ /**
+ * Gets the value of the level property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getLevel() {
+ return level;
+ }
+
+ /**
+ * Sets the value of the level property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setLevel(Integer value) {
+ this.level = value;
+ }
+
+ /**
+ * Gets the value of the start property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getStart() {
+ return start;
+ }
+
+ /**
+ * Sets the value of the start property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setStart(Integer value) {
+ this.start = value;
+ }
+
+ /**
+ * Gets the value of the colspan property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getColspan() {
+ return colspan;
+ }
+
+ /**
+ * Sets the value of the colspan property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setColspan(Integer value) {
+ this.colspan = value;
+ }
+
+ /**
+ * Gets the value of the dataMiningCol property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDataMiningCol() {
+ return dataMiningCol;
+ }
+
+ /**
+ * Sets the value of the dataMiningCol property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDataMiningCol(String value) {
+ this.dataMiningCol = value;
+ }
+
+ /**
+ * Gets the value of the colId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getColId() {
+ return colId;
+ }
+
+ /**
+ * Sets the value of the colId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setColId(String value) {
+ this.colId = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for DataSourceList complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="DataSourceList">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="dataSource" type="{}DataSourceType" maxOccurs="unbounded" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "DataSourceList", propOrder = {
+ "dataSource"
+})
+public class DataSourceList {
+
+ protected List<DataSourceType> dataSource;
+
+ /**
+ * Gets the value of the dataSource property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the dataSource property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getDataSource().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link DataSourceType }
+ *
+ *
+ */
+ public List<DataSourceType> getDataSource() {
+ if (dataSource == null) {
+ dataSource = new ArrayList<DataSourceType>();
+ }
+ return this.dataSource;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for DataSourceType complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="DataSourceType">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="tableName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="tablePK" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="displayName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="refTableId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="refDefinition" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element ref="{}comment" minOccurs="0"/>
+ * <element name="dataColumnList" type="{}DataColumnList"/>
+ * </sequence>
+ * <attribute name="tableId" type="{http://www.w3.org/2001/XMLSchema}string" />
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "DataSourceType", propOrder = {
+ "tableName",
+ "tablePK",
+ "displayName",
+ "refTableId",
+ "refDefinition",
+ "comment",
+ "dataColumnList"
+})
+public class DataSourceType {
+
+ @XmlElement(required = true)
+ protected String tableName;
+ @XmlElement(required = true)
+ protected String tablePK;
+ @XmlElement(required = true)
+ protected String displayName;
+ protected String refTableId;
+ protected String refDefinition;
+ protected String comment;
+ @XmlElement(required = true)
+ protected DataColumnList dataColumnList;
+ @XmlAttribute(name = "tableId")
+ protected String tableId;
+
+ /**
+ * Gets the value of the tableName property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getTableName() {
+ return tableName;
+ }
+
+ /**
+ * Sets the value of the tableName property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setTableName(String value) {
+ this.tableName = value;
+ }
+
+ /**
+ * Gets the value of the tablePK property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getTablePK() {
+ return tablePK;
+ }
+
+ /**
+ * Sets the value of the tablePK property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setTablePK(String value) {
+ this.tablePK = value;
+ }
+
+ /**
+ * Gets the value of the displayName property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ /**
+ * Sets the value of the displayName property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDisplayName(String value) {
+ this.displayName = value;
+ }
+
+ /**
+ * Gets the value of the refTableId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getRefTableId() {
+ return refTableId;
+ }
+
+ /**
+ * Sets the value of the refTableId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setRefTableId(String value) {
+ this.refTableId = value;
+ }
+
+ /**
+ * Gets the value of the refDefinition property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getRefDefinition() {
+ return refDefinition;
+ }
+
+ /**
+ * Sets the value of the refDefinition property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setRefDefinition(String value) {
+ this.refDefinition = value;
+ }
+
+ /**
+ * Gets the value of the comment property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getComment() {
+ return comment;
+ }
+
+ /**
+ * Sets the value of the comment property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setComment(String value) {
+ this.comment = value;
+ }
+
+ /**
+ * Gets the value of the dataColumnList property.
+ *
+ * @return
+ * possible object is
+ * {@link DataColumnList }
+ *
+ */
+ public DataColumnList getDataColumnList() {
+ return dataColumnList;
+ }
+
+ /**
+ * Sets the value of the dataColumnList property.
+ *
+ * @param value
+ * allowed object is
+ * {@link DataColumnList }
+ *
+ */
+ public void setDataColumnList(DataColumnList value) {
+ this.dataColumnList = value;
+ }
+
+ /**
+ * Gets the value of the tableId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getTableId() {
+ return tableId;
+ }
+
+ /**
+ * Sets the value of the tableId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setTableId(String value) {
+ this.tableId = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for DataminingOptions complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="DataminingOptions">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="classifier" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="timeAttribute" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="timeformat" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="forecastingUnits" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "DataminingOptions", propOrder = {
+ "classifier",
+ "timeAttribute",
+ "timeformat",
+ "forecastingUnits"
+})
+public class DataminingOptions {
+
+ protected String classifier;
+ protected String timeAttribute;
+ protected String timeformat;
+ protected String forecastingUnits;
+
+ /**
+ * Gets the value of the classifier property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getClassifier() {
+ return classifier;
+ }
+
+ /**
+ * Sets the value of the classifier property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setClassifier(String value) {
+ this.classifier = value;
+ }
+
+ /**
+ * Gets the value of the timeAttribute property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getTimeAttribute() {
+ return timeAttribute;
+ }
+
+ /**
+ * Sets the value of the timeAttribute property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setTimeAttribute(String value) {
+ this.timeAttribute = value;
+ }
+
+ /**
+ * Gets the value of the timeformat property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getTimeformat() {
+ return timeformat;
+ }
+
+ /**
+ * Sets the value of the timeformat property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setTimeformat(String value) {
+ this.timeformat = value;
+ }
+
+ /**
+ * Gets the value of the forecastingUnits property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getForecastingUnits() {
+ return forecastingUnits;
+ }
+
+ /**
+ * Sets the value of the forecastingUnits property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setForecastingUnits(String value) {
+ this.forecastingUnits = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for FormFieldList complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="FormFieldList">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="formField" type="{}FormFieldType" maxOccurs="unbounded" minOccurs="0"/>
+ * <element ref="{}comment" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "FormFieldList", propOrder = {
+ "formField",
+ "comment"
+})
+public class FormFieldList {
+
+ protected List<FormFieldType> formField;
+ protected String comment;
+
+ /**
+ * Gets the value of the formField property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the formField property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getFormField().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link FormFieldType }
+ *
+ *
+ */
+ public List<FormFieldType> getFormField() {
+ if (formField == null) {
+ formField = new ArrayList<FormFieldType>();
+ }
+ return this.formField;
+ }
+
+ /**
+ * Gets the value of the comment property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getComment() {
+ return comment;
+ }
+
+ /**
+ * Sets the value of the comment property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setComment(String value) {
+ this.comment = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlSchemaType;
+import javax.xml.bind.annotation.XmlType;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+
+/**
+ * <p>Java class for FormFieldType complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="FormFieldType">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="colId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="fieldName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="fieldType" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="visible" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="validationType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="mandatory" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="defaultValue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="orderBySeq" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="fieldSQL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="fieldDefaultSQL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="rangeStartDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
+ * <element name="rangeEndDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
+ * <element name="rangeStartDateSQL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="rangeEndDateSQL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element ref="{}comment" minOccurs="0"/>
+ * <element name="predefinedValueList" type="{}PredefinedValueList" minOccurs="0"/>
+ * <element name="dependsOn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="groupFormField" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="multiSelectListSize" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * </sequence>
+ * <attribute name="fieldId" type="{http://www.w3.org/2001/XMLSchema}string" />
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "FormFieldType", propOrder = {
+ "colId",
+ "fieldName",
+ "fieldType",
+ "visible",
+ "validationType",
+ "mandatory",
+ "defaultValue",
+ "orderBySeq",
+ "fieldSQL",
+ "fieldDefaultSQL",
+ "rangeStartDate",
+ "rangeEndDate",
+ "rangeStartDateSQL",
+ "rangeEndDateSQL",
+ "comment",
+ "predefinedValueList",
+ "dependsOn",
+ "groupFormField",
+ "multiSelectListSize"
+})
+public class FormFieldType {
+
+ @XmlElement(required = true)
+ protected String colId;
+ @XmlElement(required = true)
+ protected String fieldName;
+ @XmlElement(required = true)
+ protected String fieldType;
+ protected String visible;
+ protected String validationType;
+ protected String mandatory;
+ protected String defaultValue;
+ protected Integer orderBySeq;
+ protected String fieldSQL;
+ protected String fieldDefaultSQL;
+ @XmlSchemaType(name = "date")
+ protected XMLGregorianCalendar rangeStartDate;
+ @XmlSchemaType(name = "date")
+ protected XMLGregorianCalendar rangeEndDate;
+ protected String rangeStartDateSQL;
+ protected String rangeEndDateSQL;
+ protected String comment;
+ protected PredefinedValueList predefinedValueList;
+ protected String dependsOn;
+ @XmlElement(defaultValue = "false")
+ protected Boolean groupFormField;
+ @XmlElement(defaultValue = "4")
+ protected String multiSelectListSize;
+ @XmlAttribute(name = "fieldId")
+ protected String fieldId;
+
+ /**
+ * Gets the value of the colId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getColId() {
+ return colId;
+ }
+
+ /**
+ * Sets the value of the colId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setColId(String value) {
+ this.colId = value;
+ }
+
+ /**
+ * Gets the value of the fieldName property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getFieldName() {
+ return fieldName;
+ }
+
+ /**
+ * Sets the value of the fieldName property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setFieldName(String value) {
+ this.fieldName = value;
+ }
+
+ /**
+ * Gets the value of the fieldType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getFieldType() {
+ return fieldType;
+ }
+
+ /**
+ * Sets the value of the fieldType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setFieldType(String value) {
+ this.fieldType = value;
+ }
+
+ /**
+ * Gets the value of the visible property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getVisible() {
+ return visible;
+ }
+
+ /**
+ * Sets the value of the visible property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setVisible(String value) {
+ this.visible = value;
+ }
+
+ /**
+ * Gets the value of the validationType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getValidationType() {
+ return validationType;
+ }
+
+ /**
+ * Sets the value of the validationType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setValidationType(String value) {
+ this.validationType = value;
+ }
+
+ /**
+ * Gets the value of the mandatory property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getMandatory() {
+ return mandatory;
+ }
+
+ /**
+ * Sets the value of the mandatory property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setMandatory(String value) {
+ this.mandatory = value;
+ }
+
+ /**
+ * Gets the value of the defaultValue property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDefaultValue() {
+ return defaultValue;
+ }
+
+ /**
+ * Sets the value of the defaultValue property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDefaultValue(String value) {
+ this.defaultValue = value;
+ }
+
+ /**
+ * Gets the value of the orderBySeq property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getOrderBySeq() {
+ return orderBySeq;
+ }
+
+ /**
+ * Sets the value of the orderBySeq property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setOrderBySeq(Integer value) {
+ this.orderBySeq = value;
+ }
+
+ /**
+ * Gets the value of the fieldSQL property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getFieldSQL() {
+ return fieldSQL;
+ }
+
+ /**
+ * Sets the value of the fieldSQL property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setFieldSQL(String value) {
+ this.fieldSQL = value;
+ }
+
+ /**
+ * Gets the value of the fieldDefaultSQL property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getFieldDefaultSQL() {
+ return fieldDefaultSQL;
+ }
+
+ /**
+ * Sets the value of the fieldDefaultSQL property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setFieldDefaultSQL(String value) {
+ this.fieldDefaultSQL = value;
+ }
+
+ /**
+ * Gets the value of the rangeStartDate property.
+ *
+ * @return
+ * possible object is
+ * {@link XMLGregorianCalendar }
+ *
+ */
+ public XMLGregorianCalendar getRangeStartDate() {
+ return rangeStartDate;
+ }
+
+ /**
+ * Sets the value of the rangeStartDate property.
+ *
+ * @param value
+ * allowed object is
+ * {@link XMLGregorianCalendar }
+ *
+ */
+ public void setRangeStartDate(XMLGregorianCalendar value) {
+ this.rangeStartDate = value;
+ }
+
+ /**
+ * Gets the value of the rangeEndDate property.
+ *
+ * @return
+ * possible object is
+ * {@link XMLGregorianCalendar }
+ *
+ */
+ public XMLGregorianCalendar getRangeEndDate() {
+ return rangeEndDate;
+ }
+
+ /**
+ * Sets the value of the rangeEndDate property.
+ *
+ * @param value
+ * allowed object is
+ * {@link XMLGregorianCalendar }
+ *
+ */
+ public void setRangeEndDate(XMLGregorianCalendar value) {
+ this.rangeEndDate = value;
+ }
+
+ /**
+ * Gets the value of the rangeStartDateSQL property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getRangeStartDateSQL() {
+ return rangeStartDateSQL;
+ }
+
+ /**
+ * Sets the value of the rangeStartDateSQL property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setRangeStartDateSQL(String value) {
+ this.rangeStartDateSQL = value;
+ }
+
+ /**
+ * Gets the value of the rangeEndDateSQL property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getRangeEndDateSQL() {
+ return rangeEndDateSQL;
+ }
+
+ /**
+ * Sets the value of the rangeEndDateSQL property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setRangeEndDateSQL(String value) {
+ this.rangeEndDateSQL = value;
+ }
+
+ /**
+ * Gets the value of the comment property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getComment() {
+ return comment;
+ }
+
+ /**
+ * Sets the value of the comment property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setComment(String value) {
+ this.comment = value;
+ }
+
+ /**
+ * Gets the value of the predefinedValueList property.
+ *
+ * @return
+ * possible object is
+ * {@link PredefinedValueList }
+ *
+ */
+ public PredefinedValueList getPredefinedValueList() {
+ return predefinedValueList;
+ }
+
+ /**
+ * Sets the value of the predefinedValueList property.
+ *
+ * @param value
+ * allowed object is
+ * {@link PredefinedValueList }
+ *
+ */
+ public void setPredefinedValueList(PredefinedValueList value) {
+ this.predefinedValueList = value;
+ }
+
+ /**
+ * Gets the value of the dependsOn property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDependsOn() {
+ return dependsOn;
+ }
+
+ /**
+ * Sets the value of the dependsOn property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDependsOn(String value) {
+ this.dependsOn = value;
+ }
+
+ /**
+ * Gets the value of the groupFormField property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isGroupFormField() {
+ return groupFormField;
+ }
+
+ /**
+ * Sets the value of the groupFormField property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setGroupFormField(Boolean value) {
+ this.groupFormField = value;
+ }
+
+ /**
+ * Gets the value of the multiSelectListSize property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getMultiSelectListSize() {
+ return multiSelectListSize;
+ }
+
+ /**
+ * Sets the value of the multiSelectListSize property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setMultiSelectListSize(String value) {
+ this.multiSelectListSize = value;
+ }
+
+ /**
+ * Gets the value of the fieldId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getFieldId() {
+ return fieldId;
+ }
+
+ /**
+ * Sets the value of the fieldId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setFieldId(String value) {
+ this.fieldId = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for FormatList complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="FormatList">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="format" type="{}FormatType" maxOccurs="unbounded"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "FormatList", propOrder = {
+ "format"
+})
+public class FormatList {
+
+ @XmlElement(required = true)
+ protected List<FormatType> format;
+
+ /**
+ * Gets the value of the format property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the format property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getFormat().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link FormatType }
+ *
+ *
+ */
+ public List<FormatType> getFormat() {
+ if (format == null) {
+ format = new ArrayList<FormatType>();
+ }
+ return this.format;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for FormatType complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="FormatType">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="lessThanValue" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="expression" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="bold" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
+ * <element name="italic" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
+ * <element name="underline" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
+ * <element name="bgColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="fontColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="fontFace" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="fontSize" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="alignment" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element ref="{}comment" minOccurs="0"/>
+ * </sequence>
+ * <attribute name="formatId" type="{http://www.w3.org/2001/XMLSchema}string" />
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "FormatType", propOrder = {
+ "lessThanValue",
+ "expression",
+ "bold",
+ "italic",
+ "underline",
+ "bgColor",
+ "fontColor",
+ "fontFace",
+ "fontSize",
+ "alignment",
+ "comment"
+})
+public class FormatType {
+
+ @XmlElement(required = true)
+ protected String lessThanValue;
+ @XmlElement(required = true)
+ protected String expression;
+ @XmlElement(defaultValue = "false")
+ protected boolean bold;
+ @XmlElement(defaultValue = "false")
+ protected boolean italic;
+ @XmlElement(defaultValue = "false")
+ protected boolean underline;
+ protected String bgColor;
+ protected String fontColor;
+ protected String fontFace;
+ protected String fontSize;
+ protected String alignment;
+ protected String comment;
+ @XmlAttribute(name = "formatId")
+ protected String formatId;
+
+ /**
+ * Gets the value of the lessThanValue property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getLessThanValue() {
+ return lessThanValue;
+ }
+
+ /**
+ * Sets the value of the lessThanValue property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setLessThanValue(String value) {
+ this.lessThanValue = value;
+ }
+
+ /**
+ * Gets the value of the expression property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getExpression() {
+ return expression;
+ }
+
+ /**
+ * Sets the value of the expression property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setExpression(String value) {
+ this.expression = value;
+ }
+
+ /**
+ * Gets the value of the bold property.
+ *
+ */
+ public boolean isBold() {
+ return bold;
+ }
+
+ /**
+ * Sets the value of the bold property.
+ *
+ */
+ public void setBold(boolean value) {
+ this.bold = value;
+ }
+
+ /**
+ * Gets the value of the italic property.
+ *
+ */
+ public boolean isItalic() {
+ return italic;
+ }
+
+ /**
+ * Sets the value of the italic property.
+ *
+ */
+ public void setItalic(boolean value) {
+ this.italic = value;
+ }
+
+ /**
+ * Gets the value of the underline property.
+ *
+ */
+ public boolean isUnderline() {
+ return underline;
+ }
+
+ /**
+ * Sets the value of the underline property.
+ *
+ */
+ public void setUnderline(boolean value) {
+ this.underline = value;
+ }
+
+ /**
+ * Gets the value of the bgColor property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getBgColor() {
+ return bgColor;
+ }
+
+ /**
+ * Sets the value of the bgColor property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setBgColor(String value) {
+ this.bgColor = value;
+ }
+
+ /**
+ * Gets the value of the fontColor property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getFontColor() {
+ return fontColor;
+ }
+
+ /**
+ * Sets the value of the fontColor property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setFontColor(String value) {
+ this.fontColor = value;
+ }
+
+ /**
+ * Gets the value of the fontFace property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getFontFace() {
+ return fontFace;
+ }
+
+ /**
+ * Sets the value of the fontFace property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setFontFace(String value) {
+ this.fontFace = value;
+ }
+
+ /**
+ * Gets the value of the fontSize property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getFontSize() {
+ return fontSize;
+ }
+
+ /**
+ * Sets the value of the fontSize property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setFontSize(String value) {
+ this.fontSize = value;
+ }
+
+ /**
+ * Gets the value of the alignment property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getAlignment() {
+ return alignment;
+ }
+
+ /**
+ * Sets the value of the alignment property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setAlignment(String value) {
+ this.alignment = value;
+ }
+
+ /**
+ * Gets the value of the comment property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getComment() {
+ return comment;
+ }
+
+ /**
+ * Sets the value of the comment property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setComment(String value) {
+ this.comment = value;
+ }
+
+ /**
+ * Gets the value of the formatId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getFormatId() {
+ return formatId;
+ }
+
+ /**
+ * Sets the value of the formatId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setFormatId(String value) {
+ this.formatId = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for JavascriptItemType complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="JavascriptItemType">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="fieldId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="callText" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "JavascriptItemType", propOrder = {
+ "id",
+ "fieldId",
+ "callText"
+})
+public class JavascriptItemType {
+
+ @XmlElement(required = true)
+ protected String id;
+ @XmlElement(required = true)
+ protected String fieldId;
+ @XmlElement(required = true)
+ protected String callText;
+
+ /**
+ * Gets the value of the id property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getId() {
+ return id;
+ }
+
+ /**
+ * Sets the value of the id property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setId(String value) {
+ this.id = value;
+ }
+
+ /**
+ * Gets the value of the fieldId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getFieldId() {
+ return fieldId;
+ }
+
+ /**
+ * Sets the value of the fieldId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setFieldId(String value) {
+ this.fieldId = value;
+ }
+
+ /**
+ * Gets the value of the callText property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getCallText() {
+ return callText;
+ }
+
+ /**
+ * Sets the value of the callText property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setCallText(String value) {
+ this.callText = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for JavascriptList complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="JavascriptList">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="javascriptItem" type="{}JavascriptItemType" maxOccurs="unbounded" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "JavascriptList", propOrder = {
+ "javascriptItem"
+})
+public class JavascriptList {
+
+ protected List<JavascriptItemType> javascriptItem;
+
+ /**
+ * Gets the value of the javascriptItem property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the javascriptItem property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getJavascriptItem().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link JavascriptItemType }
+ *
+ *
+ */
+ public List<JavascriptItemType> getJavascriptItem() {
+ if (javascriptItem == null) {
+ javascriptItem = new ArrayList<JavascriptItemType>();
+ }
+ return this.javascriptItem;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for Marker complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="Marker">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="markerColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="dataHeader" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="addressColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="dataColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "Marker", propOrder = {
+ "markerColor",
+ "dataHeader",
+ "addressColumn",
+ "dataColumn"
+})
+public class Marker {
+
+ protected String markerColor;
+ protected String dataHeader;
+ protected String addressColumn;
+ protected String dataColumn;
+
+ /**
+ * Gets the value of the markerColor property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getMarkerColor() {
+ return markerColor;
+ }
+
+ /**
+ * Sets the value of the markerColor property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setMarkerColor(String value) {
+ this.markerColor = value;
+ }
+
+ /**
+ * Gets the value of the dataHeader property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDataHeader() {
+ return dataHeader;
+ }
+
+ /**
+ * Sets the value of the dataHeader property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDataHeader(String value) {
+ this.dataHeader = value;
+ }
+
+ /**
+ * Gets the value of the addressColumn property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getAddressColumn() {
+ return addressColumn;
+ }
+
+ /**
+ * Sets the value of the addressColumn property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setAddressColumn(String value) {
+ this.addressColumn = value;
+ }
+
+ /**
+ * Gets the value of the dataColumn property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDataColumn() {
+ return dataColumn;
+ }
+
+ /**
+ * Sets the value of the dataColumn property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDataColumn(String value) {
+ this.dataColumn = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.annotation.XmlElementDecl;
+import javax.xml.bind.annotation.XmlRegistry;
+import javax.xml.namespace.QName;
+
+
+/**
+ * This object contains factory methods for each
+ * Java content interface and Java element interface
+ * generated in the org.onap.portalsdk.analytics.xmlobj package.
+ * <p>An ObjectFactory allows you to programatically
+ * construct new instances of the Java representation
+ * for XML content. The Java representation of XML
+ * content can consist of schema derived interfaces
+ * and classes representing the binding of schema
+ * type definitions, element declarations and model
+ * groups. Factory methods for each of these are
+ * provided in this class.
+ *
+ */
+@XmlRegistry
+public class ObjectFactory {
+
+ private final static QName _CustomReport_QNAME = new QName("", "customReport");
+ private final static QName _Comment_QNAME = new QName("", "comment");
+
+ /**
+ * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.portalsdk.analytics.xmlobj
+ *
+ */
+ public ObjectFactory() {
+ }
+
+ /**
+ * Create an instance of {@link CustomReportType }
+ *
+ */
+ public CustomReportType createCustomReportType() {
+ return new CustomReportType();
+ }
+
+ /**
+ * Create an instance of {@link ChartAdditionalOptions }
+ *
+ */
+ public ChartAdditionalOptions createChartAdditionalOptions() {
+ return new ChartAdditionalOptions();
+ }
+
+ /**
+ * Create an instance of {@link DataminingOptions }
+ *
+ */
+ public DataminingOptions createDataminingOptions() {
+ return new DataminingOptions();
+ }
+
+ /**
+ * Create an instance of {@link FormFieldType }
+ *
+ */
+ public FormFieldType createFormFieldType() {
+ return new FormFieldType();
+ }
+
+ /**
+ * Create an instance of {@link PredefinedValueList }
+ *
+ */
+ public PredefinedValueList createPredefinedValueList() {
+ return new PredefinedValueList();
+ }
+
+ /**
+ * Create an instance of {@link DashboardEditorReport }
+ *
+ */
+ public DashboardEditorReport createDashboardEditorReport() {
+ return new DashboardEditorReport();
+ }
+
+ /**
+ * Create an instance of {@link DataSourceList }
+ *
+ */
+ public DataSourceList createDataSourceList() {
+ return new DataSourceList();
+ }
+
+ /**
+ * Create an instance of {@link DashboardReports }
+ *
+ */
+ public DashboardReports createDashboardReports() {
+ return new DashboardReports();
+ }
+
+ /**
+ * Create an instance of {@link ReportMap }
+ *
+ */
+ public ReportMap createReportMap() {
+ return new ReportMap();
+ }
+
+ /**
+ * Create an instance of {@link FormatList }
+ *
+ */
+ public FormatList createFormatList() {
+ return new FormatList();
+ }
+
+ /**
+ * Create an instance of {@link JavascriptList }
+ *
+ */
+ public JavascriptList createJavascriptList() {
+ return new JavascriptList();
+ }
+
+ /**
+ * Create an instance of {@link JavascriptItemType }
+ *
+ */
+ public JavascriptItemType createJavascriptItemType() {
+ return new JavascriptItemType();
+ }
+
+ /**
+ * Create an instance of {@link DataColumnType }
+ *
+ */
+ public DataColumnType createDataColumnType() {
+ return new DataColumnType();
+ }
+
+ /**
+ * Create an instance of {@link DataSourceType }
+ *
+ */
+ public DataSourceType createDataSourceType() {
+ return new DataSourceType();
+ }
+
+ /**
+ * Create an instance of {@link DashboardEditorList }
+ *
+ */
+ public DashboardEditorList createDashboardEditorList() {
+ return new DashboardEditorList();
+ }
+
+ /**
+ * Create an instance of {@link SemaphoreList }
+ *
+ */
+ public SemaphoreList createSemaphoreList() {
+ return new SemaphoreList();
+ }
+
+ /**
+ * Create an instance of {@link ColFilterType }
+ *
+ */
+ public ColFilterType createColFilterType() {
+ return new ColFilterType();
+ }
+
+ /**
+ * Create an instance of {@link ChartDrillOptions }
+ *
+ */
+ public ChartDrillOptions createChartDrillOptions() {
+ return new ChartDrillOptions();
+ }
+
+ /**
+ * Create an instance of {@link DashboardReportsNew }
+ *
+ */
+ public DashboardReportsNew createDashboardReportsNew() {
+ return new DashboardReportsNew();
+ }
+
+ /**
+ * Create an instance of {@link ChartDrillFormfield }
+ *
+ */
+ public ChartDrillFormfield createChartDrillFormfield() {
+ return new ChartDrillFormfield();
+ }
+
+ /**
+ * Create an instance of {@link PDFAdditionalOptions }
+ *
+ */
+ public PDFAdditionalOptions createPDFAdditionalOptions() {
+ return new PDFAdditionalOptions();
+ }
+
+ /**
+ * Create an instance of {@link Reports }
+ *
+ */
+ public Reports createReports() {
+ return new Reports();
+ }
+
+ /**
+ * Create an instance of {@link Marker }
+ *
+ */
+ public Marker createMarker() {
+ return new Marker();
+ }
+
+ /**
+ * Create an instance of {@link FormatType }
+ *
+ */
+ public FormatType createFormatType() {
+ return new FormatType();
+ }
+
+ /**
+ * Create an instance of {@link DataColumnList }
+ *
+ */
+ public DataColumnList createDataColumnList() {
+ return new DataColumnList();
+ }
+
+ /**
+ * Create an instance of {@link FormFieldList }
+ *
+ */
+ public FormFieldList createFormFieldList() {
+ return new FormFieldList();
+ }
+
+ /**
+ * Create an instance of {@link SemaphoreType }
+ *
+ */
+ public SemaphoreType createSemaphoreType() {
+ return new SemaphoreType();
+ }
+
+ /**
+ * Create an instance of {@link ColFilterList }
+ *
+ */
+ public ColFilterList createColFilterList() {
+ return new ColFilterList();
+ }
+
+ /**
+ * Create an instance of {@link JAXBElement }{@code <}{@link CustomReportType }{@code >}}
+ *
+ */
+ @XmlElementDecl(namespace = "", name = "customReport")
+ public JAXBElement<CustomReportType> createCustomReport(CustomReportType value) {
+ return new JAXBElement<CustomReportType>(_CustomReport_QNAME, CustomReportType.class, null, value);
+ }
+
+ /**
+ * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
+ *
+ */
+ @XmlElementDecl(namespace = "", name = "comment")
+ public JAXBElement<String> createComment(String value) {
+ return new JAXBElement<String>(_Comment_QNAME, String.class, null, value);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for PDFAdditionalOptions complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="PDFAdditionalOptions">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="PDF_font" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="PDF_fontSize" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="PDF_orientation" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="PDF_logo1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="PDF_logo2" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="PDF_logo1Size" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="PDF_logo2Size" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
+ * <element name="PDF_coverPage" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ * <element name="PDF_footer1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="PDF_footer2" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "PDFAdditionalOptions", propOrder = {
+ "pdfFont",
+ "pdfFontSize",
+ "pdfOrientation",
+ "pdfLogo1",
+ "pdfLogo2",
+ "pdfLogo1Size",
+ "pdfLogo2Size",
+ "pdfCoverPage",
+ "pdfFooter1",
+ "pdfFooter2"
+})
+public class PDFAdditionalOptions {
+
+ @XmlElement(name = "PDF_font")
+ protected String pdfFont;
+ @XmlElement(name = "PDF_fontSize")
+ protected Integer pdfFontSize;
+ @XmlElement(name = "PDF_orientation")
+ protected String pdfOrientation;
+ @XmlElement(name = "PDF_logo1")
+ protected String pdfLogo1;
+ @XmlElement(name = "PDF_logo2")
+ protected String pdfLogo2;
+ @XmlElement(name = "PDF_logo1Size")
+ protected Integer pdfLogo1Size;
+ @XmlElement(name = "PDF_logo2Size")
+ protected Integer pdfLogo2Size;
+ @XmlElement(name = "PDF_coverPage", defaultValue = "false")
+ protected Boolean pdfCoverPage;
+ @XmlElement(name = "PDF_footer1")
+ protected String pdfFooter1;
+ @XmlElement(name = "PDF_footer2")
+ protected String pdfFooter2;
+
+ /**
+ * Gets the value of the pdfFont property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getPDFFont() {
+ return pdfFont;
+ }
+
+ /**
+ * Sets the value of the pdfFont property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setPDFFont(String value) {
+ this.pdfFont = value;
+ }
+
+ /**
+ * Gets the value of the pdfFontSize property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getPDFFontSize() {
+ return pdfFontSize;
+ }
+
+ /**
+ * Sets the value of the pdfFontSize property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setPDFFontSize(Integer value) {
+ this.pdfFontSize = value;
+ }
+
+ /**
+ * Gets the value of the pdfOrientation property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getPDFOrientation() {
+ return pdfOrientation;
+ }
+
+ /**
+ * Sets the value of the pdfOrientation property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setPDFOrientation(String value) {
+ this.pdfOrientation = value;
+ }
+
+ /**
+ * Gets the value of the pdfLogo1 property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getPDFLogo1() {
+ return pdfLogo1;
+ }
+
+ /**
+ * Sets the value of the pdfLogo1 property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setPDFLogo1(String value) {
+ this.pdfLogo1 = value;
+ }
+
+ /**
+ * Gets the value of the pdfLogo2 property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getPDFLogo2() {
+ return pdfLogo2;
+ }
+
+ /**
+ * Sets the value of the pdfLogo2 property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setPDFLogo2(String value) {
+ this.pdfLogo2 = value;
+ }
+
+ /**
+ * Gets the value of the pdfLogo1Size property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getPDFLogo1Size() {
+ return pdfLogo1Size;
+ }
+
+ /**
+ * Sets the value of the pdfLogo1Size property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setPDFLogo1Size(Integer value) {
+ this.pdfLogo1Size = value;
+ }
+
+ /**
+ * Gets the value of the pdfLogo2Size property.
+ *
+ * @return
+ * possible object is
+ * {@link Integer }
+ *
+ */
+ public Integer getPDFLogo2Size() {
+ return pdfLogo2Size;
+ }
+
+ /**
+ * Sets the value of the pdfLogo2Size property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Integer }
+ *
+ */
+ public void setPDFLogo2Size(Integer value) {
+ this.pdfLogo2Size = value;
+ }
+
+ /**
+ * Gets the value of the pdfCoverPage property.
+ *
+ * @return
+ * possible object is
+ * {@link Boolean }
+ *
+ */
+ public Boolean isPDFCoverPage() {
+ return pdfCoverPage;
+ }
+
+ /**
+ * Sets the value of the pdfCoverPage property.
+ *
+ * @param value
+ * allowed object is
+ * {@link Boolean }
+ *
+ */
+ public void setPDFCoverPage(Boolean value) {
+ this.pdfCoverPage = value;
+ }
+
+ /**
+ * Gets the value of the pdfFooter1 property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getPDFFooter1() {
+ return pdfFooter1;
+ }
+
+ /**
+ * Sets the value of the pdfFooter1 property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setPDFFooter1(String value) {
+ this.pdfFooter1 = value;
+ }
+
+ /**
+ * Gets the value of the pdfFooter2 property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getPDFFooter2() {
+ return pdfFooter2;
+ }
+
+ /**
+ * Sets the value of the pdfFooter2 property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setPDFFooter2(String value) {
+ this.pdfFooter2 = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for PredefinedValueList complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="PredefinedValueList">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="predefinedValue" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "PredefinedValueList", propOrder = {
+ "predefinedValue"
+})
+public class PredefinedValueList {
+
+ protected List<String> predefinedValue;
+
+ /**
+ * Gets the value of the predefinedValue property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the predefinedValue property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getPredefinedValue().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link String }
+ *
+ *
+ */
+ public List<String> getPredefinedValue() {
+ if (predefinedValue == null) {
+ predefinedValue = new ArrayList<String>();
+ }
+ return this.predefinedValue;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for ReportMap complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="ReportMap">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="markerColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="useDefaultSize" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="height" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="width" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="isMapAllowedYN" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="addAddressInDataYN" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="addressColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="dataColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="defaultMapType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="latColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="longColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="colorColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="legendColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="markers" type="{}Marker" maxOccurs="unbounded" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "ReportMap", propOrder = {
+ "markerColor",
+ "useDefaultSize",
+ "height",
+ "width",
+ "isMapAllowedYN",
+ "addAddressInDataYN",
+ "addressColumn",
+ "dataColumn",
+ "defaultMapType",
+ "latColumn",
+ "longColumn",
+ "colorColumn",
+ "legendColumn",
+ "markers"
+})
+public class ReportMap {
+
+ protected String markerColor;
+ protected String useDefaultSize;
+ protected String height;
+ protected String width;
+ protected String isMapAllowedYN;
+ protected String addAddressInDataYN;
+ protected String addressColumn;
+ protected String dataColumn;
+ protected String defaultMapType;
+ protected String latColumn;
+ protected String longColumn;
+ protected String colorColumn;
+ protected String legendColumn;
+ protected List<Marker> markers;
+
+ /**
+ * Gets the value of the markerColor property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getMarkerColor() {
+ return markerColor;
+ }
+
+ /**
+ * Sets the value of the markerColor property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setMarkerColor(String value) {
+ this.markerColor = value;
+ }
+
+ /**
+ * Gets the value of the useDefaultSize property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getUseDefaultSize() {
+ return useDefaultSize;
+ }
+
+ /**
+ * Sets the value of the useDefaultSize property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setUseDefaultSize(String value) {
+ this.useDefaultSize = value;
+ }
+
+ /**
+ * Gets the value of the height property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getHeight() {
+ return height;
+ }
+
+ /**
+ * Sets the value of the height property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setHeight(String value) {
+ this.height = value;
+ }
+
+ /**
+ * Gets the value of the width property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getWidth() {
+ return width;
+ }
+
+ /**
+ * Sets the value of the width property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setWidth(String value) {
+ this.width = value;
+ }
+
+ /**
+ * Gets the value of the isMapAllowedYN property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getIsMapAllowedYN() {
+ return isMapAllowedYN;
+ }
+
+ /**
+ * Sets the value of the isMapAllowedYN property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setIsMapAllowedYN(String value) {
+ this.isMapAllowedYN = value;
+ }
+
+ /**
+ * Gets the value of the addAddressInDataYN property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getAddAddressInDataYN() {
+ return addAddressInDataYN;
+ }
+
+ /**
+ * Sets the value of the addAddressInDataYN property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setAddAddressInDataYN(String value) {
+ this.addAddressInDataYN = value;
+ }
+
+ /**
+ * Gets the value of the addressColumn property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getAddressColumn() {
+ return addressColumn;
+ }
+
+ /**
+ * Sets the value of the addressColumn property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setAddressColumn(String value) {
+ this.addressColumn = value;
+ }
+
+ /**
+ * Gets the value of the dataColumn property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDataColumn() {
+ return dataColumn;
+ }
+
+ /**
+ * Sets the value of the dataColumn property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDataColumn(String value) {
+ this.dataColumn = value;
+ }
+
+ /**
+ * Gets the value of the defaultMapType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getDefaultMapType() {
+ return defaultMapType;
+ }
+
+ /**
+ * Sets the value of the defaultMapType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setDefaultMapType(String value) {
+ this.defaultMapType = value;
+ }
+
+ /**
+ * Gets the value of the latColumn property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getLatColumn() {
+ return latColumn;
+ }
+
+ /**
+ * Sets the value of the latColumn property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setLatColumn(String value) {
+ this.latColumn = value;
+ }
+
+ /**
+ * Gets the value of the longColumn property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getLongColumn() {
+ return longColumn;
+ }
+
+ /**
+ * Sets the value of the longColumn property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setLongColumn(String value) {
+ this.longColumn = value;
+ }
+
+ /**
+ * Gets the value of the colorColumn property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getColorColumn() {
+ return colorColumn;
+ }
+
+ /**
+ * Sets the value of the colorColumn property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setColorColumn(String value) {
+ this.colorColumn = value;
+ }
+
+ /**
+ * Gets the value of the legendColumn property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getLegendColumn() {
+ return legendColumn;
+ }
+
+ /**
+ * Sets the value of the legendColumn property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setLegendColumn(String value) {
+ this.legendColumn = value;
+ }
+
+ /**
+ * Gets the value of the markers property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the markers property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getMarkers().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link Marker }
+ *
+ *
+ */
+ public List<Marker> getMarkers() {
+ if (markers == null) {
+ markers = new ArrayList<Marker>();
+ }
+ return this.markers;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for Reports complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="Reports">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="reportId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * <element name="bgcolor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "Reports", propOrder = {
+ "reportId",
+ "bgcolor"
+})
+public class Reports {
+
+ protected String reportId;
+ protected String bgcolor;
+
+ /**
+ * Gets the value of the reportId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getReportId() {
+ return reportId;
+ }
+
+ /**
+ * Sets the value of the reportId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setReportId(String value) {
+ this.reportId = value;
+ }
+
+ /**
+ * Gets the value of the bgcolor property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getBgcolor() {
+ return bgcolor;
+ }
+
+ /**
+ * Sets the value of the bgcolor property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setBgcolor(String value) {
+ this.bgcolor = value;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for SemaphoreList complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="SemaphoreList">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="semaphore" type="{}SemaphoreType" maxOccurs="unbounded" minOccurs="0"/>
+ * </sequence>
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "SemaphoreList", propOrder = {
+ "semaphore"
+})
+public class SemaphoreList {
+
+ protected List<SemaphoreType> semaphore;
+
+ /**
+ * Gets the value of the semaphore property.
+ *
+ * <p>
+ * This accessor method returns a reference to the live list,
+ * not a snapshot. Therefore any modification you make to the
+ * returned list will be present inside the JAXB object.
+ * This is why there is not a <CODE>set</CODE> method for the semaphore property.
+ *
+ * <p>
+ * For example, to add a new item, do as follows:
+ * <pre>
+ * getSemaphore().add(newItem);
+ * </pre>
+ *
+ *
+ * <p>
+ * Objects of the following type(s) are allowed in the list
+ * {@link SemaphoreType }
+ *
+ *
+ */
+ public List<SemaphoreType> getSemaphore() {
+ if (semaphore == null) {
+ semaphore = new ArrayList<SemaphoreType>();
+ }
+ return this.semaphore;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+//
+// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
+// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
+// Any modifications to this file will be lost upon recompilation of the source schema.
+// Generated on: 2016.06.07 at 02:07:29 PM EDT
+//
+
+
+package org.onap.portalsdk.analytics.xmlobj;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+/**
+ * <p>Java class for SemaphoreType complex type.
+ *
+ * <p>The following schema fragment specifies the expected content contained within this class.
+ *
+ * <pre>
+ * <complexType name="SemaphoreType">
+ * <complexContent>
+ * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ * <sequence>
+ * <element name="semaphoreName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="semaphoreType" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element ref="{}comment" minOccurs="0"/>
+ * <element name="target" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ * <element name="formatList" type="{}FormatList"/>
+ * </sequence>
+ * <attribute name="semaphoreId" type="{http://www.w3.org/2001/XMLSchema}string" />
+ * </restriction>
+ * </complexContent>
+ * </complexType>
+ * </pre>
+ *
+ *
+ */
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "SemaphoreType", propOrder = {
+ "semaphoreName",
+ "semaphoreType",
+ "comment",
+ "target",
+ "formatList"
+})
+public class SemaphoreType {
+
+ @XmlElement(required = true)
+ protected String semaphoreName;
+ @XmlElement(required = true)
+ protected String semaphoreType;
+ protected String comment;
+ @XmlElement(required = true)
+ protected String target;
+ @XmlElement(required = true)
+ protected FormatList formatList;
+ @XmlAttribute(name = "semaphoreId")
+ protected String semaphoreId;
+
+ /**
+ * Gets the value of the semaphoreName property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getSemaphoreName() {
+ return semaphoreName;
+ }
+
+ /**
+ * Sets the value of the semaphoreName property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setSemaphoreName(String value) {
+ this.semaphoreName = value;
+ }
+
+ /**
+ * Gets the value of the semaphoreType property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getSemaphoreType() {
+ return semaphoreType;
+ }
+
+ /**
+ * Sets the value of the semaphoreType property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setSemaphoreType(String value) {
+ this.semaphoreType = value;
+ }
+
+ /**
+ * Gets the value of the comment property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getComment() {
+ return comment;
+ }
+
+ /**
+ * Sets the value of the comment property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setComment(String value) {
+ this.comment = value;
+ }
+
+ /**
+ * Gets the value of the target property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getTarget() {
+ return target;
+ }
+
+ /**
+ * Sets the value of the target property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setTarget(String value) {
+ this.target = value;
+ }
+
+ /**
+ * Gets the value of the formatList property.
+ *
+ * @return
+ * possible object is
+ * {@link FormatList }
+ *
+ */
+ public FormatList getFormatList() {
+ return formatList;
+ }
+
+ /**
+ * Sets the value of the formatList property.
+ *
+ * @param value
+ * allowed object is
+ * {@link FormatList }
+ *
+ */
+ public void setFormatList(FormatList value) {
+ this.formatList = value;
+ }
+
+ /**
+ * Gets the value of the semaphoreId property.
+ *
+ * @return
+ * possible object is
+ * {@link String }
+ *
+ */
+ public String getSemaphoreId() {
+ return semaphoreId;
+ }
+
+ /**
+ * Sets the value of the semaphoreId property.
+ *
+ * @param value
+ * allowed object is
+ * {@link String }
+ *
+ */
+ public void setSemaphoreId(String value) {
+ this.semaphoreId = value;
+ }
+
+}
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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 <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
- * 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);<UL><LI> reportFormFieldPopup iterates form field collections. </LI></UL>
- * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
- * 13-Aug-2009 : Version 8.5 (Sundar);<UL><LI> reportFormFieldPopup is changed to have effect on textfield with popup. </LI></UL>
- * 06-Aug-2009 : Version 9.0 (Sundar);<UL><LI> reportFormFieldPopupB is changed. </LI></UL>
- * 29-Jul-2009 : Version 8.4 (Sundar);<UL><LI> Previously report data for dashboard stored only page level data. This has been changed to show all the data up to the maximum specified. </LI></UL>
- * 27-Jul-2009 : Version 8.4 (Sundar);<UL><LI>Bug due to not showing back button after child report in drilldown is navigated more than
- * one page is resolved. </LI></UL>
- * 14-Jul-2009 : Version 8.4 (Sundar); <UL><LI>Dashboard reports can now be generated excel as separate sheets or group together in PDF.
- * They can also be scheduled.</LI></UL>
- *
- */
-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<String> 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; i<aL.size(); i++) {
- rr = (ReportRuntime) aL.get(i);
- if( rr!=null && rr.getReportType().equals(AppConstants.RT_DASHBOARD))
- return true;
- }
- }
- return false;
- }
- private ReportRuntime getReportRuntimeFromBackup(HttpServletRequest request) {
- ArrayList aL = (ArrayList) request.getSession().getAttribute(
- AppConstants.DRILLDOWN_REPORTS_LIST);
- ReportRuntime rr = null;
- HttpSession session = request.getSession();
- /*if(aL==null || (aL.size() <=0) ) {
- rr = (ReportRuntime) request.getSession().getAttribute(
- AppConstants.SI_REPORT_RUN_BACKUP);
- request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr);
- } else {*/
- //clearReportRuntimeBackup(request);
-
- int index = Integer.parseInt(nvl(AppUtils.getRequestValue(request, AppConstants.DRILLDOWN_INDEX), "0"));
- int form_index = Integer.parseInt(nvl(AppUtils.getRequestValue(request, AppConstants.FORM_DRILLDOWN_INDEX), "0"));
- index = index>0 ? --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 <a href=''>login</a> 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<QuickLink> 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; i<sessionParams.length; i++) {
- for (int j = 0; j < formFieldsArr.length; j++) {
- if(formFieldsArr[j].startsWith(sessionParams[i])) {
- request.setAttribute(sessionParams[i], formFieldsArr[j].substring(formFieldsArr[j].indexOf("=")+1));
- }
-
- }
- }
-
- boolean reportUpdated = false;
- WizardProcessor wp = null;
- Connection connection = null;
- try {
- connection = DbUtils.startTransaction();
- wp = new WizardProcessor();
- String toListUpdated = nvl(request.getParameter("toListUpdated"),"false" );
- reportUpdated = wp.processAdhocSchedule(request, action);
- if(reportUpdated && toListUpdated.equals("false")) {
- request.setAttribute("message", "Report has been scheduled successfully");
- reportSchedule = (ReportSchedule) request.getSession().getAttribute(AppConstants.SI_REPORT_SCHEDULE);
- //if(AppUtils.getRequestNvlValue(request, AppConstants.RI_SCHEDULE_ID).length()<=0) {
- reportSchedule.persistScheduleData(connection, request);
- DbUtils.commitTransaction(connection);
- //}
- }
- } catch (ValidationException ve) {
- (new ErrorHandler()).processError(request, ve);
- } catch (RaptorException e) {
- nextPage = (new ErrorHandler()).processFatalError(request, e);
- e.printStackTrace();
- try {
- DbUtils.rollbackTransaction(connection);
- } catch (Exception e1) {e1.printStackTrace();}
- } catch (Throwable t) {
- t.printStackTrace();
- }
- finally {
- try {
- DbUtils.clearConnection(connection);
- } catch (Exception e1) {e1.printStackTrace();}
- }
- request.setAttribute("schedule_only", "Y");
- //request.getSession().removeAttribute(AppConstants.SI_REPORT_SCHEDULE);
-
- return nextPage;
- } else {
- try {
- String scheduleID = "";
- scheduleID = AppUtils.getRequestValue(request, AppConstants.RI_SCHEDULE_ID);
- String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
- request.setAttribute("schedule_only", "Y");
- ReportHandler rh = new ReportHandler();
- ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
- ReportSchedule reportSchedule = null;
- if(rdef!=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; i<sessionParams.length; i++) {
- for (int j = 0; j < formFieldsArr.length; j++) {
- if(formFieldsArr[j].startsWith(sessionParams[i])) {
- request.setAttribute(sessionParams[i], formFieldsArr[j].substring(formFieldsArr[j].indexOf("=")+1));
- }
-
- }
- }
- request.getSession().setAttribute(AppConstants.SI_REPORT_SCHEDULE, reportSchedule);
- request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
- } catch (RaptorException e) {
- nextPage = (new ErrorHandler()).processFatalError(request, e);
- }
-
- return nextPage;
- }
- } // processSchedule
-
- /****Remove Report Data from Session when Javascript throw error on onSubmit***/
- public String removeReportDataFromSession (HttpServletRequest request, String nextPage) {
- HttpSession session = request.getSession(false);
-/* if (session.getAttribute(AppConstants.RI_REPORT_DATA)!=null)
- request.getSession().removeAttribute(AppConstants.RI_REPORT_DATA);
- if (request.getAttribute(AppConstants.RI_REPORT_DATA)!=null)
- request.removeAttribute(AppConstants.RI_REPORT_DATA);
- if (session.getAttribute(AppConstants.RI_CHART_DATA)!=null)
- request.getSession().removeAttribute(AppConstants.RI_CHART_DATA);
- if (request.getAttribute(AppConstants.RI_CHART_DATA)!=null)
- request.removeAttribute(AppConstants.RI_CHART_DATA);
-*/ /*if (session.getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null)
- request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);*/
- //request.setAttribute(AppConstants.RI_RESET_ACTION, "Y");
- return nextPage;
-
- } // processScheduleDelete
-
- /****Added to delete a schedule***/
- public String processScheduleDelete(HttpServletRequest request, String nextPage) {
-
- // Added for form field chaining in schedule tab so that setParamValues() is called
- request.setAttribute(AppConstants.SCHEDULE_ACTION, "Y");
- try {
- String scheduleID = "";
- scheduleID = AppUtils.getRequestValue(request, AppConstants.RI_SCHEDULE_ID);
- String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
- ReportHandler rh = new ReportHandler();
- ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
- String myScheduleRepID = AppUtils.getRequestNvlValue(request, "myScheduleRepId");
- if (myScheduleRepID.equals(""))
- myScheduleRepID = "2670";
- ReportSchedule reportSchedule = null;
- if(rdef!=null) {
- reportSchedule = new ReportSchedule(reportID, scheduleID, AppUtils.getUserID(request), request);
- Connection connection = null;
-
- try {
- connection = DbUtils.startTransaction();
- reportSchedule.deleteScheduleData(connection);
- DbUtils.commitTransaction(connection);
- } catch (ValidationException ve) {
- (new ErrorHandler()).processError(request, ve);
- } catch (RaptorException e) {
- nextPage = (new ErrorHandler()).processFatalError(request, e);
- e.printStackTrace();
- try {
- DbUtils.rollbackTransaction(connection);
- } catch (Exception e1) {e1.printStackTrace();}
- } catch (Throwable t) {
- t.printStackTrace();
- }
- finally {
- try {
- DbUtils.clearConnection(connection);
- } catch (Exception e1) {e1.printStackTrace();}
- }
- }
- request.setAttribute(AppConstants.RI_REPORT_ID, myScheduleRepID);
- request.setAttribute(AppConstants.RI_REFRESH, "y");
- nextPage = this.reportRun(request, nextPage);
- } catch (RaptorException e) {
- nextPage = (new ErrorHandler()).processFatalError(request, e);
- }
- return nextPage;
-
- } // processScheduleDelete
-
- public String reportWizard(HttpServletRequest request, String nextPage) {
- String action = nvl(request.getParameter(AppConstants.RI_WIZARD_ACTION),
- AppConstants.WA_BACK);
- String goToStep = nvl(request.getParameter(AppConstants.RI_GO_TO_STEP));
- try {
- (new WizardProcessor()).processWizardStep(request);
-
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
- AppConstants.SI_REPORT_DEFINITION);
- WizardSequence ws = rdef.getWizardSequence();
- //debugLogger.debug("Step Count " + ws.getStepCount());
- //debugLogger.debug("Dashboard " + ((ws instanceof WizardSequenceDashboard) ? ws.getStepCount(): "Not a Dashboard"));
- //debugLogger.debug("GO TO STEP LENGTH " + goToStep.length());
- //debugLogger.debug("NumDash Cols in Action Handler " + AppUtils.getRequestNvlValue(request, "numDashCols"));
- if (goToStep.length() > 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("<b>");
- if (idxNext > 0)
- sb.append(" ");
- sb.append(sqlClause[idxNext]);
- sb.append("</b><br>\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("<br>\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,
- "<br><b>Condition NOT satisfied</b> - email notification will NOT be send.<br><br>");
- else
- request
- .setAttribute(AppConstants.RI_FORMATTED_SQL,
- "<br><b>Condition satisfied</b> - email notification will be send.<br><br>");
- } catch (Exception e) {
- // nextPage = (new ErrorHandler()).processFatalError(request, e);
- request.setAttribute(AppConstants.RI_FORMATTED_SQL, "<br><b>SQL ERROR</b> "
- + e.getMessage() + "<br>Email notification will NOT be send.<br><br>");
- }
-
- 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 <a href=''>login</a> 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<BR>");
- messageBuffer.append("<a href=\"" + request.getContextPath() + "/raptor/dwnld/data/" +
- strFileName + "\">click here</a>.</p>");
- 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<String> 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 = "<table border=1><tr><td>[Report#123]</td><td>[Report#124]</td></tr><tr><td>[Report#125]</td><td>[Report#126]</td></tr></table>";
- 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<size; i++) {
- hashReports.put(sortedArray[i], mapValues.get(mapKeys.indexOf(sortedArray[i])));
- }*/
- return new TreeMap(hashReports);
- }
-
- public ReportData getReportData(ReportRuntime reportRuntime, HttpServletRequest request, String sql, int maxRows) throws RaptorException {
-
-
- // replace the request parameter specified in the drill down
- List reportCols = reportRuntime.getAllColumns();
- 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());
- 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
-
-/**<HR/>
- * This class is part of <B><I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I></B><BR/>
- * <HR/>
- *
- * --------------------------------------------------------------------------------------------------<BR/>
- * <B>WizardProcessor.java</B> - This class is used to process the user input provided in the wizard.<BR/>
- * It is called in creation as well as updation process. It builds report xml via JAXB using user<BR/>
- * input. This is vital one, to store meta information of each report<BR/>
- * ---------------------------------------------------------------------------------------------------<BR/>
- *
- *
- * <U>Change Log</U><BR/><BR/>
- *
- * 31-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> For Time Series multi series property is exposed. </LI></UL>
- * 28-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> If user login id is null, it would display user name when user is added for schedule. </LI></UL>
- * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
- * 12-Aug-2009 : Version 8.5 (Sundar); <UL><LI> For Line Charts too options are captured and rendering is customized. </LI></UL>
- * 29-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Maximum Excel Download size would be persisted if changed. </LI></UL>
- * 14-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Schedule feature is added to Dashboard Reports. </LI></UL>
- * 29-Jun-2009 : Version 8.4 (Sundar); <UL><LI> Options for <I>Compare to Previous year Chart</I> are processed.</LI>
- * <LI> In the Bar chart Last Occuring Series/Category can be plotted as Bar or Line Renderer. </LI>
- * </UL>
- * 22-Jun-2009 : Version 8.4 (Sundar); <UL><LI> processChart method is modified to accommodate creating
- * Bar Charts, Time Difference Charts and adding generic chart options.</LI></UL>
- *
- */
-
-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<br>Expected date format " + nvl(
- currColumn.getColFormat(),
- AppConstants.DEFAULT_DATE_FORMAT))
- : "Invalid value<br>Possible reason: use of single quotes"))
- + "<!--" + e.getMessage() + "--><br>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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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);
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String> selectionList;
- private Set<String> lineIDSet;
-
- public Line(NovaMap map) {
- this.map = map;
- lineCollection = new LineCollection();
- lineIDSet = new HashSet<String>();
- selectionList = new ArrayList<String>();
- }
-
- public ArrayList<LineInfo> lineExist(Point2D screenPoint) {
- ArrayList<LineInfo> 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<LineInfo> 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<LineInfo>();
- }
-
- existLineInfo.add(lineInfo);
- }
- }
-
- return existLineInfo;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String> selectedLine; // all selected node
- private String lineID; // last clicked node
- private ArrayList<LineInfo> lineCollection;
-
- public LineCollection() {
- lineCollection = new ArrayList<LineInfo>(20000);
- selectedLine = new HashSet<String>();
- }
-
- public void addSelectedLine(String lineID) {
- selectedLine.add(lineID);
- }
-
- public void removeSelectedLine(String lineID) {
- selectedLine.remove(lineID);
- }
-
- public Set<String> 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<LineInfo> 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<String> list = new ArrayList<String>();
-
- 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;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String, String> lineAttributes;
-
- public LineInfo(String nodeID1, String nodeID2) {
- this.nodeID1 = nodeID1;
- this.nodeID2 = nodeID2;
- lineAttributes = new HashMap<String, String>();
- }
-
- 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<String, String> lineAttributes) {
- this.lineAttributes.clear();
- Set<String> keySet = lineAttributes.keySet();
- Iterator<String> 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<String> getAttributeKeys() {
- Set<String> keySet = lineAttributes.keySet();
- List<String> keys = new ArrayList<String>(keySet.size());
- Iterator<String> iter = keySet.iterator();
-
- while (iter.hasNext()) {
- String key = iter.next();
-
- if (key.indexOf("x_") != 0) {
- keys.add(key);
- }
- }
-
- return keys;
- }
-
- public List<String> getAttributeInternalKeys() {
- Set<String> keySet = lineAttributes.keySet();
- List<String> internalKeys = new ArrayList<String>();
- Iterator<String> 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;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String, Object> colorProperties;
- private ArrayList<String> nodeLegends;
- private ArrayList<String> lineLegends;
-
- public ColorProperties(NovaMap map) {
- this.map = map;
- colorProperties = new HashMap<String, Object>();
- }
-
- 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());
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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();
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String> showList;
- private ArrayList<SwingLayer> 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<meter2pixel.length; ++i)
- meter2pixel[i] = meter2pixel[i-1]/2;
- }
-
- private static void initShapeWidth() {
- // ZOOM_MAX+1 is added to below line because of ArrayIndexOutOfException. This is Suggested by Hendra Tuty. - Sundar
- shapeWidth = new int[MapConstant.ZOOM_MAX];
- int width = 0;
- for (int i = 0; i < shapeWidth.length; i++) {
- if (i < 5) {
-
- }
- else if (i == 5) {
- width = 4;
- }
- else if (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<String>();
- swingLayers = new ArrayList<SwingLayer>();
- }
-
-
-
- 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<SwingLayer> 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<<zoomLevel),
- ( 0.5 - Math.log((1.0+sinLatitude)/(1.0-sinLatitude))
- /(4.0*Math.PI) )*256.0*(1<<zoomLevel)
- );
- }
-
- private boolean checkTransform(Rectangle2D geoArea) {
- System.out.println("%%%%%%map.checkTransform start");
- if (!this.geoArea.equals(geoArea)) {
- Point2D point1 = getPixelPos(geoArea.getMinY(), geoArea.getMinX());
- Point2D point2 = getPixelPos(geoArea.getMaxY(), geoArea.getMaxX());
- mapArea.setRect(point1.getX(), point2.getY(),
- boundingBox.getWidth(), boundingBox.getHeight());
- this.geoArea.setRect(geoArea);
- resetTransform(boundingBox, mapArea);
- System.out.println("%%%%%%map.checkTransform end 1");
- return true;
- }
-
- System.out.println("%%%%%%map.checkTransform end 2");
- return false;
- }
-
- private void resetTransform(Rectangle boundingBox, Rectangle2D mapArea) {
- System.out.println("%%%%%%map.resetTransform start");
- if (mapArea == null || boundingBox.getWidth() == 0 || boundingBox.getHeight() == 0 ) {
- System.out.println("%%%%%%map.resetTransform end 1");
- return;
- }
-
- transform = new AffineTransform(mapArea.getWidth() / boundingBox.getWidth(),
- 0.0, 0.0, mapArea.getHeight() / boundingBox.getHeight(),
- mapArea.getMinX(), mapArea.getMinY());
- System.out.println("%%%%%%map.resetTransform end 2");
- }
-
- protected AffineTransform getTransform() {
- if (transform != null) {
- return new AffineTransform(transform);
- }
-
- return null;
- }
-
- public Point2D getScreenPointFromPixel(double xPixel, double yPixel) {
- try {
- return getTransform().inverseTransform(new Point2D.Double(xPixel, yPixel), null);
- } catch (NoninvertibleTransformException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- return null;
- }
-
- public Point2D getScreenPointFromLonLat(double longitude, double latitude) {
- Point2D point = getPixelPos(latitude, longitude);
- return getScreenPointFromPixel(point.getX(), point.getY());
- }
-
- public Point2D getLonLatFromPixel(int x1, int y1) {
- double x = (double) x1 / 256;
- double y = (double) y1 / 256;
- double lon = -180; // x
- double lonWidth = 360; // width 360
-
- //double lat = -90; // y
- //double latHeight = 180; // height 180
- double lat = -1;
- double latHeight = 2;
-
- int tilesAtThisZoom = 1 << getZoomLevel();
- lonWidth = 360.0 / tilesAtThisZoom;
- lon = -180 + (x * lonWidth);
- latHeight = -2.0 / tilesAtThisZoom;
- lat = 1 + (y * latHeight);
-
- // convert lat and latHeight to degrees in a transverse mercator projection
- // note that in fact the coordinates go from about -85 to +85 not -90 to 90!
- latHeight += lat;
- latHeight = (2 * Math.atan(Math.exp(Math.PI * latHeight))) - (Math.PI / 2);
- latHeight *= (180 / Math.PI);
-
- lat = (2 * Math.atan(Math.exp(Math.PI * lat))) - (Math.PI / 2);
- lat *= (180 / Math.PI);
-
- latHeight -= lat;
-
- if (lonWidth < 0) {
- lon = lon + lonWidth;
- lonWidth = -lonWidth;
- }
-
- if (latHeight < 0) {
- lat = lat + latHeight;
- latHeight = -latHeight;
- }
-
- return new Point2D.Double(lon, lat + latHeight);
- }
-
- public ArrayList getImage(final HttpServletRequest request, Rectangle2D geoArea) {
- Object showListArr[] = ((HashSet)getShowList()).toArray();
- BufferedImage image = new BufferedImage(boundingBox.width, boundingBox.height, BufferedImage.TYPE_INT_ARGB);
- final Graphics2D g2d = image.createGraphics();
- // LEGEND INFO
- BufferedImage legendImage = null;
- Graphics2D g2Legend = null;
- if(showLegend) {
- legendImage = new BufferedImage(boundingBox.width, (int)(20*showListArr.length) + 20, BufferedImage.TYPE_INT_ARGB);
- g2Legend = legendImage.createGraphics();
- g2Legend.setBackground(Color.WHITE);
- }
-
- checkTransform(geoArea);
-
- boolean shapefileLayerPainted = false;
- boolean swingLayerPainted = false;
-
- Object object = request.getAttribute("server_process_interrupted");
- if (object != null && ((Boolean) object)) {
- System.out.println("interrupted");
- g2d.dispose();
- return null;
- }
-
- for (SwingLayer layer : swingLayers) {
- swingLayerPainted = swingLayerPainted || layer.paintLayer(request, g2d, boundingBox, mapArea, g2Legend);
- }
-
- ArrayList imageArr = new ArrayList();
- //if(showLegend) layer.paintLegend(g2Legend);
-
- g2d.dispose();
- if(showLegend)
- g2Legend.dispose();
- object = request.getAttribute("server_process_interrupted");
-
- if (object != null && ((Boolean) object)) {
- System.out.println("interrupted");
- return imageArr;
- }
- else if (!shapefileLayerPainted && !swingLayerPainted) {
- System.out.println("not painted");
- return imageArr;
- }
-
- imageArr.add(image);
- if(g2Legend!=null) {
- imageArr.add(legendImage);
- }
- return imageArr;
- }
-
- public Object singleLeftClick(double longitude, double latitude, Rectangle2D geoArea) {
- System.out.println("%%%%%%map.singleLeftClick start");
- System.out.println("%%%%%%map.singleLeftClick check transform start");
- checkTransform(geoArea);
- System.out.println("%%%%%%map.singleLeftClick check transform end");
- Point2D screenPoint = getScreenPointFromLonLat(longitude, latitude);
- System.out.println("%%%%%%map.singleLeftClick getting nodeExist array ");
- ArrayList<NodeInfo> existNodeInfo = node.nodeExist(screenPoint);
-
- if (existNodeInfo == null) {
- ArrayList<LineInfo> 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;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String,NodeInfo> hashMap = node.getNodeCollection().getNodeCollection();
- Set set = hashMap.entrySet();
- int width = map.getShapeWidth();
- ArrayList<String> visibleLabel = new ArrayList<String>(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;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String> nodeIDSet;
- private NodeCollection nodeCollection;
- private ArrayList<String> selectionList;
- private NovaMap map;
-
- public Node(NovaMap map) {
- this.map = map;
- nodeCollection = new NodeCollection();
- nodeIDSet = new HashSet<String>();
- selectionList = new ArrayList<String>();
- }
-
- 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<NodeInfo> nodeCollection = this.nodeCollection.getNodeCollection();
-
- for (NodeInfo nodeInfo : nodeCollection) {
- nodeInfo.setAttribute(NodeInfo.NUMBER_OF_T1_KEY, nodeInfo.getAttribute(currentYearMonth));
- }
- }
-*/
-/* public Set<Integer> getUniqueNumberT1(String currentYearMonth) {
- ArrayList<NodeInfo> nodeCollection = this.nodeCollection.getNodeCollection();
- Set<Integer> numberT1Set = new TreeSet<Integer>();
-
- for (NodeInfo nodeInfo : nodeCollection) {
- numberT1Set.add(Integer.parseInt(nodeInfo.getAttribute(currentYearMonth).toString()));
- }
-
- return numberT1Set;
- }
-*/
- public void updateNumberT1(String currentYearMonth) {
- HashMap<String,NodeInfo> 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<Integer> getUniqueNumberT1(String currentYearMonth) {
- HashMap<String,NodeInfo> hashMap = this.nodeCollection.getNodeCollection();
- Set set = hashMap.entrySet();
- Set<Integer> numberT1Set = new TreeSet<Integer>();
-
- 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<NodeInfo> nodeExist(Point2D screenPoint) {
- ArrayList<NodeInfo> existNodeInfo = null;
- int nearest = 9999;
- String selectedNode = null;
- String selectedType = null;
- int nodeSize = map.getShapeWidth();
- HashMap<String,NodeInfo> hashMap = nodeCollection.getNodeCollection();
- Set set = hashMap.entrySet();
- //ArrayList<NodeInfo> 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<NodeInfo>();
- }
-
- existNodeInfo.add(nodeInfo);
- }
- }
-
- return existNodeInfo;
- }
-
- public NodeCollection getNodeCollection() {
- return nodeCollection;
- }
-
- public void clearNodeIDSet() {
- nodeIDSet.clear();
- }
-
- public void clearSelectionList() {
- selectionList.clear();
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String> selectedNode; // all selected node
- private String nodeID; // last clicked node
- private HashMap<String,NodeInfo> nodeCollection;
-
- public NodeCollection() {
- selectedNode = new HashSet<String>();
- nodeCollection = new HashMap<String,NodeInfo>(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<String> 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<String,NodeInfo> 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<NodeInfo> getWildCardNode(String nodeID, String nodeType) {
- ArrayList<NodeInfo> list = new ArrayList<NodeInfo>();
-
- 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<NodeInfo> getCellsiteLocation(String location, boolean exactMatch) {
- ArrayList<NodeInfo> list = new ArrayList<NodeInfo>();
-
- 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 = "";
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String> lineIDS;
- private Map<String, String> nodeAttributes;
-
- public NodeInfo(String nodeID) {
- this.nodeID = nodeID;
- lineIDS = new ArrayList<String>();
- nodeAttributes = new TreeMap<String, String>();
- 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<String> getLineIDS() {
- return lineIDS;
- }
-
- public void printLineIDS() {
- Iterator<String> iter = lineIDS.iterator();
-
- while (iter.hasNext()) {
- System.out.println(iter.next());
- }
- }
-
- public List<String> cloneLineIDS() {
- List<String> lineIDS = new ArrayList<String>();
-
- for (String lineID : this.lineIDS) {
- lineIDS.add(lineID);
- }
-
- return lineIDS;
- }
-
- public void setLineIDS(List<String> 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<String, String> nodeAttributes) {
- this.nodeAttributes.clear();
- Set<String> keySet = nodeAttributes.keySet();
- Iterator<String> 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<String> getAttributeKeys() {
- Set<String> keySet = nodeAttributes.keySet();
- List<String> keys = new ArrayList<String>(keySet.size());
- Iterator<String> iter = keySet.iterator();
-
- while (iter.hasNext()) {
- String key = iter.next();
-
- if (key.indexOf("x_") != 0) {
- keys.add(key);
- }
- }
-
- return keys;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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);
- } */
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 <code>get</code> method.
- */
- public abstract Object construct();
-
- /**
- * Called on the event dispatching thread (not on the worker thread)
- * after the <code>construct</code> 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 <code>construct</code> 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 <code>construct</code> 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 <code>construct</code> 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();
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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_<framework>.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
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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 <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
- * 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);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
- * 14-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Signature for generating excel method has been changed to add the report name as sheet name. </LI>
- * <LI> Dashboard reports can be downloaded with each report as a separate sheet. </LI>
- * </UL>
- * 08-Jun-2009 : Version 8.3 (Sundar); <UL><LI> Short datatype is replaced with default integer datatype to create
- * row as short is not expoting more than 32768 rows. </LI></UL>
- *
- */
-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, "<BR/>", " ");
- header = Utils.replaceInString(header, "<br/>", " ");
- header = Utils.replaceInString(header, "<br>", " ");
- header = strip.stripHtml(nvl(header).trim());
- subtitle = Utils.replaceInString(subtitle, "<BR/>", " ");
- subtitle = Utils.replaceInString(subtitle, "<br/>", " ");
- subtitle = Utils.replaceInString(subtitle, "<br>", " ");
- 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());
-// <td align="center"<%= ch.getColumnWidthHtml() %><%= ch.getColSpanHtml() %><%= ch.getRowSpanHtml() %>>
-// <b class=rtableheader><%= ch.getColumnTitleHtml() %></b>
-// </td>
- } // 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<dataTypeMap.size(); tmp++){
- String dataTypeStr = (String)(dataTypeMap.get(tmp));
- if(dataTypeStr.equals("NUMBER")){
- cell.setCellStyle(styleNumber);
- }else if (dataTypeStr.equals("VARCHAR2")){
- cell.setCellStyle(styleDefault);
-
- }else if (dataTypeStr.equals("DATE")){
- cell.setCellStyle(styleDate);
- }else{
-
- }
-
- }*/
- 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
-
- // 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;
- }
- }
- }
-
- /*
- if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols!=null) {
-
- for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();) {
- rowCount++;
-
-
- DataRow dr = rd.reportDataTotalRow.getNext();
- row = sheet.createRow(rowNum);
- cellNum = -1;
- int j = 0;
- cellNum += 1;
- cell = row.createCell((short) cellNum);
- cell.setCellValue("Total");
- cell.setCellStyle(styleTotal);
-
- for (dr.resetNext(); dr.hasNext();j++) {
- DataValue dv = dr.getNext();
- if(j==0 || !dv.isVisible()) continue;
- cellNum += 1;
- styleCell = null;
- boolean bold = true;
- String value = nvl(dv.getDisplayValue());
- //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(styleTotal!=null) {
- styleTotal.setDataFormat((short) 8);//HSSFDataFormat.getBuiltinFormat("($#,##0.00_);[Red]($#,##0.00)"));
- cell.setCellStyle(styleTotal);
- } else
- cell.setCellStyle(styleCurrencyDecimalNumberTotal);
- cell.setCellValue(tempDoubleDollar);
- } catch (NumberFormatException ne) {
- if(styleTotal!=null) {
- styleTotal.setWrapText(true);
- cell.setCellStyle(styleTotal);
- } 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(styleTotal!=null) {
- styleTotal.setDataFormat((short)0x28 );//HSSFDataFormat.getBuiltinFormat("(#,##0.00_);[Red](#,##0.00)"));
- cell.setCellStyle(styleTotal);
- } else
- cell.setCellStyle(styleDecimalNumberTotal);
- cell.setCellValue(tempDouble);
- } catch (NumberFormatException ne) {
- if(styleTotal!=null) {
- styleTotal.setWrapText(true);
- cell.setCellStyle(styleTotal);
- } 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(styleTotal!=null) {
- styleTotal.setDataFormat((short) 6);//HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
- cell.setCellStyle(styleTotal);
- } else
- cell.setCellStyle(styleCurrencyNumberTotal);
- cell.setCellValue(tempIntDollar);
- } catch (NumberFormatException ne) {
- if(styleTotal!=null) {
- styleTotal.setWrapText(true);
- cell.setCellStyle(styleTotal);
- } 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(styleTotal!=null) {
- styleTotal.setDataFormat((short) 0x26);//HSSFDataFormat.getBuiltinFormat("(#,##0_);[Red](#,##0)"));
- cell.setCellStyle(styleTotal);
- } else
- cell.setCellStyle(styleNumber);
- cell.setCellValue(temp);
- } catch (NumberFormatException ne) {
- if(styleTotal!=null) {
- styleTotal.setWrapText(true);
- cell.setCellStyle(styleTotal);
- } 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(styleTotal!=null) {
- styleTotal.setWrapText(true);
- cell.setCellStyle(styleTotal);
- } else
- cell.setCellStyle(styleDefault);
- }
- }
- }
-
-
-
-
- }
- }
- }
- */
-
-
-
- } else if (rr.getReportType().equals(AppConstants.RT_CROSSTAB)) { // Linear
- int rowCount = 0;
- List l = rd.getReportDataList();
- boolean first = true;
- for (int dataRow = 0; dataRow < l.size(); dataRow++) {
-
-
- DataRow dr = (DataRow) l.get(dataRow);
- row = sheet.createRow(rowNum);
-
- cellNum = -1;
- first = true;
- Vector<DataValue> rowNames = dr.getRowValues();
- for(dr.resetNext(); dr.hasNext(); rowCount++ ) {
- if(first) {
- if(rowNames!=null) {
- for(int i=0; i<rowNames.size(); i++) {
- DataValue dv = rowNames.get(i);
- cellNum += 1;
- row.createCell((short) cellNum).setCellValue(strip.stripHtml(dv.getDisplayValue()));
- row.getCell((short) cellNum).setCellStyle(styleDefault);
- }
- }
- }
- first = false;
-
- DataValue dv = dr.getNext();
- if(dv.isVisible()) {
- String value = dv.getDisplayValue();
- if(value.indexOf("|#")!=-1)
- value = value.substring(0,value.indexOf("|"));
-
- if(dr.isRowFormat() || nvl(dv.getFormatId()).length()>0) {
- 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, "<BR/>", " ");
- footer = Utils.replaceInString(footer, "<br/>", " ");
- footer = Utils.replaceInString(footer, "<br>", " ");
- 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<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>();
- 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<ZipEntry> en = (Enumeration<ZipEntry>) 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("<?xml version=\"1.0\" encoding=\""+XML_ENCODING+"\"?>" +
- "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">" );
- _out.write("<sheetData>\n");
- }
-
- public void endSheet() throws IOException {
- _out.write("</sheetData>");
- _out.write("</worksheet>");
- }
-
- /**
- * Insert a new row
- *
- * @param rownum 0-based row number
- */
- public void insertRow(int rownum) throws IOException {
- _out.write("<row r=\""+(rownum+1)+"\">\n");
- this._rownum = rownum;
- }
-
- /**
- * Insert row end marker
- */
- public void endRow() throws IOException {
- _out.write("</row>\n");
- }
-
- public void createCell(int columnIndex, String value, int styleIndex) throws IOException {
- String ref = new CellReference(_rownum, columnIndex).formatAsString();
- _out.write("<c r=\""+ref+"\" t=\"inlineStr\"");
- if(styleIndex != -1) _out.write(" s=\""+styleIndex+"\"");
- _out.write(">");
- _out.write("<is><t>"+value+"</t></is>");
- _out.write("</c>");
- }
-
- 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("<c r=\""+ref+"\" t=\"n\"");
- if(styleIndex != -1) _out.write(" s=\""+styleIndex+"\"");
- _out.write(">");
- _out.write("<v>"+value+"</v>");
- _out.write("</c>");
- }
-
- 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<String, XSSFCellStyle> loadXSSFStyles(ReportRuntime rr, XSSFWorkbook wb, Map<String, XSSFCellStyle> 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<String, XSSFCellStyle> hashMapStyles = new HashMap<String, XSSFCellStyle>();;
- Map<String, XSSFFont> hashMapFonts = new HashMap<String, XSSFFont>();
- 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<String, XSSFCellStyle> 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, "<BR/>", " ");
- header = Utils.replaceInString(header, "<br/>", " ");
- header = Utils.replaceInString(header, "<br>", " ");
- header = strip.stripHtml(nvl(header).trim());
- subtitle = Utils.replaceInString(subtitle, "<BR/>", " ");
- subtitle = Utils.replaceInString(subtitle, "<br/>", " ");
- subtitle = Utils.replaceInString(subtitle, "<br>", " ");
- 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<String, Short> dateFormatMap = new HashMap<String, Short>();
-
- 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, "<BR/>", " ");
- footer = Utils.replaceInString(footer, "<br/>", " ");
- footer = Utils.replaceInString(footer, "<br>", " ");
- 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; tmp<dataTypeMap.size(); tmp++){
- String dataTypeStr = (String)(dataTypeMap.get(tmp));
- if(dataTypeStr.equals("NUMBER")){
- cell.setCellStyle(styleNumber);
- }else if (dataTypeStr.equals("VARCHAR2")){
- cell.setCellStyle(styleDefault);
-
- }else if (dataTypeStr.equals("DATE")){
- cell.setCellStyle(styleDate);
- }else{
-
- }
-
- }*/
- rowNum += 1;
- sw.endRow();
- } // for
-
- if (rr.getReportType().equals(AppConstants.RT_LINEAR) && rd.reportTotalRowHeaderCols!=null) {
-
- for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext();) {
- rowCount++;
- sw.insertRow(rowNum);
- cellNum = -1;
- 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());
-
- DataRow drTotal = rd.reportDataTotalRow.getNext();
- if(drTotal!=null) {
- drTotal.resetNext(); drTotal.getNext();
- for (; drTotal.hasNext();) {
- cellNum += 1;
- styleCell = null;
- DataValue dv = drTotal.getNext();
- String value = dv.getDisplayValue();
- sw.createCell(cellNum,value,styles.get(nvl(/*dv.getFormatId(),*/"","default")).getIndex());
- }
- }
-
- rowNum += 1;
- sw.endRow();
- }
-
-
- String footer = (String) session.getAttribute("FOOTER_"+index);
- if(nvl(footer).length()>0) {
- footer = Utils.replaceInString(footer, "<BR/>", " ");
- footer = Utils.replaceInString(footer, "<br/>", " ");
- footer = Utils.replaceInString(footer, "<br>", " ");
- 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("<HTML>\n" +
- "<HEAD><TITLE>" + rr.getReportName() + "</TITLE></HEAD>\n" +
- "<BODY>\n" );
- System.out.println("HTML-Excel Generation Triggered: " + new java.util.Date());
- csvOut.print("<TABLE>");
- 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("<TR><TD COLSPAN=\"2\">" + "Run-time Parameters" + "</TD></TR>");
- //strBuf.append("Run-time Parameters\n");
- }
- csvOut.println("<TR><TD>" + value.getId() +"</TD>");
- csvOut.println("<TD>" + value.getName().replaceAll("~",",")+ "</TD>");
- csvOut.println("</TR>");
-
- //strBuf.append(value.getId()+": "+ value.getName()+"\n");
- }
- } //for
- csvOut.println("<TR><TD COLSPAN=\"2\"> </TD></TR>");
- csvOut.println("<TR><TD COLSPAN=\"2\"> </TD></TR>");
- 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<ResultSet> callable = new ExecuteQuery(st, sql_whole, downloadLimit);
- ExecutorService executor = new ScheduledThreadPoolExecutor(5);
- System.out.println("Time Started" + new java.util.Date());
- Future<ResultSet> 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("<TR>");
- for (chr.resetNext(); chr.hasNext();) {
- ColumnHeader ch = chr.getNext();
- if(ch.isVisible()) {
- csvOut.print("<TD bgColor=\"8F9381\">" + ch.getColumnTitle() + "</TD>");
- //for (int i = 1; i < ch.getColSpan(); i++)
- // csvOut.print(",");
-
- }
- } // for
- csvOut.println("</TR>");
- } // for
-
-
- while(rs.next()) {
- csvOut.println("<TR>");
-/* 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("<TD>" + strip.stripCSVHtml(nvl((String)colHash.get(ch.getLinkColId().toUpperCase()))) + "</TD>");
- }
-
- }
- csvOut.println("</TR>");
- }
- System.out.println("Downloaded Rows in HTML-Excel " + rowCount + " : "+ new java.util.Date());
- if(rowCount == 0) {
- csvOut.print("<TR><TD COLSPAN=\""+ numberOfColumns + "\">No Data Found</TD></TR>");
- } else {
- }
- } else {
- csvOut.println("<TR><TD COLSPAN=\""+ numberOfColumns + "\">No Data Found</TD></TR>");
- }
- csvOut.println("</TABLE></BODY>\n</HTML>");
-
- } 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("<TR>");
- for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) {
- RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
-
- if (firstPass) {
- numberOfColumns++;
- csvOut.print("<TD bgColor=\"8F9381\">" + rhc.getColumnTitle() + "</TD>");
- }
- //csvOut.print(",");
- } // for
-
-
- for (chr.resetNext(); chr.hasNext();) {
- ColumnHeader ch = chr.getNext();
- if(ch.isVisible()) {
- if(firstPass) numberOfColumns++;
- csvOut.print("<TD bgColor=\"8F9381\">" + ch.getColumnTitle() + "</TD>");
- //for (int i = 1; i < ch.getColSpan(); i++)
- //csvOut.print(",");
- }
- } // for
- firstPass = false;
- csvOut.println("</TR>");
- } // for
-
- firstPass = true;
- for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext();) {
- DataRow dr = rd.reportDataRows.getNext();
- csvOut.println("<TR>");
- for (rd.reportRowHeaderCols.resetNext(1); rd.reportRowHeaderCols.hasNext();) {
- RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
- if (firstPass)
- rhc.resetNext();
- RowHeader rh = rhc.getNext();
-
- csvOut.print("<TD bgColor=\"8F9381\">" + strip.stripCSVHtml(rh.getRowTitle()) + "</TD>");
- } // for
- firstPass = false;
-
- for (dr.resetNext(); dr.hasNext();) {
- DataValue dv = dr.getNext();
- if(dv.isVisible())
- csvOut.print("<TD bgColor=\"8F9381\">" + strip.stripCSVHtml(dv.getDisplayValue()) + "</TD>");
- } // for
-
- csvOut.println("</TR>");
-
- } // for
- //csvOut.flush();
- } else {
- csvOut.println("<TR><TD COLSPAN=\""+ numberOfColumns + "\">No Data Found</TD></TR>");
- }
- }
- csvOut.println("</TABLE></BODY>\n</HTML>");
- 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();
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
- * 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);<UL><LI> isDashboardType is made to return false, as any report can be added to Dashboard. </LI></UL>
- * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
- * 27-Jul-2009 : Version 8.4 (Sundar);<UL><LI>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. </LI></UL>
- *
- */
-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")
- + "', '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>', "
- + 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("<a href=\"" + AppUtils.getReportExecuteActionURL() + ds.getString(i, 0));
- if(b) link.append("&PAGE_ID="+menuId+"&refresh=Y");
- link.append("\">" +ds.getString(i, 1) + "</a>" + (Globals.getShowDescrAtRuntime() ? " - " + ds.getString(i, 2) : "") );
- quickLinks.add(link.toString());
- }
-
- return quickLinks;
- } // loadQuickLinks
-
- public static ArrayList<QuickLink> 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<QuickLink> quickLinksArray = new ArrayList<QuickLink>(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 = "'<a class=\"hyperref1\" href=''#'' onClick=''document."+HTML_FORM+"."+AppConstants.RI_ACTION+".value=\"report.run\";"+
- "document."+HTML_FORM+".c_master.value=\"'|| cr.rep_id||'\";document."+HTML_FORM+".submit()''>'";
- String PRIVATE_ICON = "<img border=0 src="
- + AppUtils.getImgFolderURL()
- + "accessicon.gif alt=Private width=16 height=12> ";
-
- 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||'</a>' 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||'</a>' 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("<a href=\"" + AppUtils.getReportExecuteActionURL() + ds.getString(i, 0));
- if(b) link.append("&PAGE_ID="+menuId+"&refresh=Y");
- link.append("\">" +ds.getString(i, 2) + "</a>" + (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("<a href=\"" + AppUtils.getRaptorActionURL()+"download.data.file&filename="
- + ds.getString(i, 0)+"\">" + ds.getString(i, 1)+ "</a>" + " "+ 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("<a href=\"" + AppUtils.getRaptorActionURL()+"report.run.container&display_content=Y&fromReportLog=Y&refresh=Y&c_master="+ds.getString(i, 0)+ds.getString(i, 3)+"\">" + ds.getString(i, 1)+ "</a>");
- }
- 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(" '<a href=\"" + AppUtils.getRaptorActionURL() +"report.run.container&c_master='||x.rep_id||'&'||x.form_fields||'&fromReportLog=Y&display_content=Y&noFormFields=Y&refresh=Y\">'||x.action||'</a>'");
- 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 '<a href=\"" + AppUtils.getRaptorActionURL() +"report.run.container&c_master='||x.rep_id||'&'||x.form_fields||'&fromReportLog=Y&display_content=Y&noFormFields=Y&refresh=Y\"><img src=\""+AppUtils.getImgFolderURL()+ "test_run.gif\" width=\"12\" height=\"12\" border=0 alt=\"Run report\"/></a>' 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
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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 <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
- * 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);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
- * 13-Aug-2009 : Version 8.5 (Sundar);<UL><LI>Refresh is added while running report.</LI>
- * </UL>
- * 27-Jul-2009 : Version 8.4 (Sundar);<UL><LI> A new sort order PUBLIC is added.</LI>
- * <LI> 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".</LI>
- * </UL>
- *
- */
-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 = "<img border=0 src="
- + AppUtils.getImgFolderURL()
- + "accessicon.gif alt=Private width=16 height=12> ";
-
- 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 = "'<a class=\"hyperref1\" href=''#'' onClick=''document."+HTML_FORM+"."+AppConstants.RI_ACTION+".value=\"report.run\";"+
- "document."+HTML_FORM+".c_master.value=\"'|| cr.rep_id||'\";document."+HTML_FORM+".refresh.value=\"Y\";document."+HTML_FORM+".submit();return false;''>'";
- for (Iterator iter = AppUtils.getUserRoles(request).iterator(); iter.hasNext();)
- roleList.append("," + ((String) iter.next()));
- //<a href="#" alt="Run report" onClick="document.forma.r_action.value='report.run'; document.forma.c_master.value='1073';">
- /*String sql = "SELECT cr.rep_id, "
- + "cr.rep_id report_id, "
- + rep_title_sql+
- "||DECODE(cr.public_yn, 'Y', '', '"
- + PRIVATE_ICON
- + "')||cr.title||'</a>' 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 '%<allowSchedule>N</allowSchedule>%' "
- + "then 'N' "
- + "when report_xml like '%<allowSchedule>Y</allowSchedule>%' "
- + "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 = "'<a class=\"hyperref1\" href=''#'' onClick=''document."+HTML_FORM+"."+AppConstants.RI_ACTION+".value=\"report.run\";"+
- "document."+HTML_FORM+".c_master.value=\"'|| cr.rep_id||'\";document."+HTML_FORM+".submit();return false;''>'";
- for (Iterator iter = AppUtils.getUserRoles(request).iterator(); iter.hasNext();)
- roleList.append("," + ((String) iter.next()));
- //<a href="#" alt="Run report" onClick="document.forma.r_action.value='report.run'; document.forma.c_master.value='1073';">
- /*String sql = "SELECT cr.rep_id, "
- + "cr.rep_id report_id, "
- + rep_title_sql+
- "||DECODE(cr.public_yn, 'Y', '', '"
- + PRIVATE_ICON
- + "')||cr.title||'</a>' 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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 <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-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;
-
-@Entity
-public class ReportUserRole extends org.openecomp.portalsdk.analytics.RaptorObject implements Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- @Id
- private Long repId = null;
-
- @Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- private Long orderNo = null;
-
- private Long roleId = null;
-
- private Long userId = null;
-
- private String readOnlyYn = null;
-
- public ReportUserRole() {
- super();
- }
-
- public ReportUserRole(Long repId, Long orderNo, Long roleId, Long userId, String readOnlyYn) {
- super();
- this.repId = repId;
- this.orderNo = orderNo;
- this.roleId = roleId;
- this.userId = userId;
- this.readOnlyYn = readOnlyYn;
- }
-
- public Long getRepId() {
- return repId;
- }
-
- public void setRepId(Long repId) {
- this.repId = repId;
- }
-
- public Long getOrderNo() {
- return orderNo;
- }
-
- public void setOrderNo(Long orderNo) {
- this.orderNo = orderNo;
- }
-
- public Long getRoleId() {
- return roleId;
- }
-
- public void setRoleId(Long roleId) {
- this.roleId = roleId;
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public void setUserId(Long userId) {
- this.userId = userId;
- }
-
- public String getReadOnlyYn() {
- return readOnlyYn;
- }
-
- public void setReadOnlyYn(String readOnlyYn) {
- this.readOnlyYn = readOnlyYn;
- }
-
-
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
-
-/**<HR/>
- * This class is part of <B><I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I></B><BR/>
- * <HR/>
- *
- * --------------------------------------------------------------------------------------------------<BR/>
- * <B>ReportWrapper.java</B> - This is the base class for the RAPTOR. This involves in creating,<BR/>
- * modifying, running RAPTOR reports.<BR/>
- * --------------------------------------------------------------------------------------------------<BR/>
- *
- *
- * <U>Change Log</U><BR/><BR/>
- *
- * 31-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> All the elements in the meta xml is copied to the target reports. </LI></UL>
- * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
- * 27-Jul-2009 : Version 8.4 (Sundar); <UL><LI> verifySQLBasedReportAccess method checks for Admin user instead of super user. </LI></UL>
- * 09-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Bug due to parsing and removing formfields from "and" is bulletproofed to the right "and" to which the formfield is associated. </LI></UL>
- * 08-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Bug due to parsing and removing formfields when there is no parameter for Daytona specific database is resolved. </LI></UL>
- * 29-Jun-2009 : Version 8.4 (Sundar); <UL><LI> isLastSeriesALineChart() and setLastSeriesALineChart(String value) method have been added for the Bar Chart enhancements. </LI></UL>
- * 23-Jun-2009 : Version 8.4 (Sundar); <UL><LI> check for cr.getChartAdditionalOptions() for null value is added.</LI></UL>
- * 22-Jun-2009 : Version 8.4 (Sundar); <UL><LI> 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.</LI></UL>
- *
- */
-
-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<Item> getChartValueColumnsListModelList( int filter, HashMap formValues) { / *filter; all=0;create without new chart =1; createNewChart=2 * /
- List reportCols = getAllColumns();
-
- ArrayList chartValueCols = new ArrayList();
- ListModelList<Item> chartValueListModelList = new ListModelList<Item>();
- 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<DataColumnType> 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<ds.getColumnCount(); k++) {
- if(dct.getColId().toUpperCase().trim().equals(ds.getColumnName(k).trim())) {
- reportCols.add(dct);
- continue outer;
- }
- }
- }
-
- if (getFormFieldList() != null) {
- String paramValue = "";
- for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
- FormFieldType fft = (FormFieldType) iter.next();
- if(fft.isGroupFormField()!=null && fft.isGroupFormField().booleanValue()) {
- paramValue = Utils.oracleSafe(nvl(paramValues
- .getParamValue(fft.getFieldId())));
- outer:
- for (Iterator iter1 = reportCols1.iterator(); iter1.hasNext();) {
- DataColumnType dct = (DataColumnType) iter1.next();
- if(("["+fft.getFieldName()+ "]").equals(dct.getColName().trim())) {
- dct.setDisplayName(paramValue);
- continue outer;
- }
- }
-
-
- }
- }
- }
-
- }
-
- for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
- DataColumnType dc = (DataColumnType) iter.next();
- //TODO: commented if (dc.isVisible()) {
- if (colNames.length() > 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<CustomReportType> doc = (javax.xml.bind.JAXBElement<CustomReportType>) 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
-
-/**<HR/>
- * This class is part of <B><I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I></B><BR/>
- * <HR/>
- *
- * --------------------------------------------------------------------------------------------------<BR/>
- * <B>ReportDefinition.java</B> - This involves in creating and modifying RAPTOR reports.
- * --------------------------------------------------------------------------------------------------<BR/>
- *
- *
- * <U>Change Log</U><BR/><BR/>
- *
- * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>
- * 27-Jul-2009 : Version 8.4 (Sundar); <UL><LI>userIsAuthorizedToSeeLog is checked for Admin User instead of Super User.</LI></UL>
- * 22-Jun-2009 : Version 8.4 (Sundar); <UL><LI>A new type ChartAdditionalOptions is introduced in RAPTOR XSD.
- * For this type a create procedure is added to this class.</LI></UL>
- *
- */
-
-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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- }
-
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<IdNameValue> 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<IdNameValue> 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- private String errorMessage;
- private String errorStackTrace;
-
- public String getTabId() {
- return tabId;
- }
- public String getErrorMessage() {
- return errorMessage;
- }
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
- public String getErrorStackTrace() {
- return errorStackTrace;
- }
- public void setErrorStackTrace(String errorStackTrace) {
- this.errorStackTrace = errorStackTrace;
- }
- 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;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 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<IdNameBooleanJSON> 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<NameBooleanJSON> 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<IdNameBooleanJSON> getDisplayArea() {
- return displayArea;
- }
-
- public void setDisplayArea(List<IdNameBooleanJSON> 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<NameBooleanJSON> getDisplayOptions() {
- return displayOptions;
- }
-
- public void setDisplayOptions(List<NameBooleanJSON> 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;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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();
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<IdNameBooleanJSON> predefinedValueList;
- private String message;
- private String errorMessage;
- private String errorStackTrace;
-
-
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
- public String getErrorMessage() {
- return errorMessage;
- }
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
- public String getErrorStackTrace() {
- return errorStackTrace;
- }
- public void setErrorStackTrace(String errorStackTrace) {
- this.errorStackTrace = errorStackTrace;
- }
- 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<IdNameBooleanJSON> getPredefinedValueList() {
- return predefinedValueList;
- }
- public void setPredefinedValueList(List<IdNameBooleanJSON> predefinedValueList) {
- this.predefinedValueList = predefinedValueList;
- }
- public String getFieldSQL() {
- return fieldSQL;
- }
- public void setFieldSQL(String fieldSQL) {
- this.fieldSQL = fieldSQL;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 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;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- }
-
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<ElementJSON> elements;
-
- public ArrayList<ElementJSON> getElements() {
- return elements;
- }
-
- public void setElements(ArrayList<ElementJSON> elements) {
- this.elements = elements;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 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;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String> reportDataColumns;
- private ArrayList<Map<String,String>> 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<String> getReportDataColumns() {
- return reportDataColumns;
- }
-
- public void setReportDataColumns(ArrayList<String> reportDataColumns) {
- this.reportDataColumns = reportDataColumns;
- }
-
- public ArrayList<Map<String, String>> getReportDataRows() {
- return reportDataRows;
- }
-
- public void setReportDataRows(ArrayList<Map<String, String>> reportDataRows) {
- this.reportDataRows = reportDataRows;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 RaptorError extends RaptorResponse{
- public RaptorError(String theMessage) {
- error().put("message", theMessage);
- }
-
- public RaptorError(String theMessage, Throwable theError) {
- error().put("message", theMessage)
- .put("exception", theError.toString());
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 org.json.JSONObject;
-
-import com.fasterxml.jackson.annotation.JsonRawValue;
-
-public class RaptorResponse {
- private JSONObject data = new JSONObject(),
- error = new JSONObject();
-
- public RaptorResponse() {
- }
-
- public JSONObject data() {
- return this.data;
- }
-
- @JsonRawValue
- public String getData() {
- return this.data.toString();
- }
-
- public JSONObject error() {
- return this.error;
- }
-
- @JsonRawValue
- public String getError() {
- return this.error.toString();
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 interface WizardJSON {
-
- public String getTabName();
- public void setTabName(String tabName);
- public String getTabId();
- public void setTabId(String tabId);
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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("<no logo>"))
- howManyLogos ++;
-
- if(AppUtils.isNotEmpty(pb.getLogo2Url()) && !pb.getLogo2Url().equalsIgnoreCase("<no logo>"))
- 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("<no logo>"))
- 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("<no logo>"))
- 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
- * 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); <UL>
- * <LI> Dashboard reports can be downloaded with each report occupying separate page including its charts. </LI>
- * </UL>
- *
- */
-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 ; i<paraList.size(); i++) {
- reportDescrBuf.append(paraList.get(i));
- }
-
- }
- add2Cells(table,"Description : ",reportDescrBuf.toString());
- 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 : ",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; i<rows; i++)
- for(int j=0;j<table.getAbsoluteWidths().length;j++)
- table.addCell(new Paragraph(" "));
-
- }
-
- private void add2Cells(PdfPTable table, String key, String value) {
-
- PdfPCell cell;
- cell = new PdfPCell(new Paragraph(key));
- cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
- cell.setBorderWidth(0f);
- table.addCell(cell);
-
- cell = new PdfPCell(new Paragraph(value));
- cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
- cell.setBorderWidth(0f);
- table.addCell(cell);
- }
-
- private void paintPdfImage(HttpServletRequest request, Document document, String fileName, ReportRuntime rr)
- throws DocumentException
- {
-
- ArrayList images = getImage(request, fileName,pb.isAttachmentOfEmail()?true:false, rr);
- //Image image = getImage(request, fileName,pb.isAttachmentOfEmail()?true:false);
- PdfPTable table = null;
- PdfPCell cellValue = null;
- if(images!=null) {
-
- for (int i = 0; i < images.size(); i++) {
- table = new PdfPTable(1);
- cellValue = new PdfPCell();
- cellValue.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
- Image image = (Image) images.get(i);
- image.setAlignment(Image.ALIGN_CENTER);
- //System.out.println("Document 3 " + document + " i-" + i);
- if(i%2 ==0)
- document.newPage();
- //System.out.println("Document 31 " + document);
- cellValue.setImage(image);
- //table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
- table.addCell(cellValue);
- //System.out.println("Document 32 " + document + "table " + table);
- document.add(table);
- //System.out.println("Document 33 " + document);
- }
- }
- }
-
- private ArrayList getImage(HttpServletRequest request, String fileName, boolean isGenerateNewImage, ReportRuntime rr) {
- ArrayList images = new ArrayList();
- if(!isGenerateNewImage) {
- try {
- Image image = Image.getInstance(fileName);
- images.add(image);
- return images;
- }
- catch (MalformedURLException e) {
- isGenerateNewImage = true;
- //e.printStackTrace();
- }
- catch (BadElementException e) {
- isGenerateNewImage = true;
- //e.printStackTrace();
-
- } catch (FileNotFoundException e) {
- isGenerateNewImage = true;
- //e.printStackTrace();
- } catch (IOException e) {
- isGenerateNewImage = true;
- //e.printStackTrace();
- }
- }
-
- if(isGenerateNewImage && retryCreateNewImageCount<RetryCreateNewImage){
- retryCreateNewImageCount++;
- return generateNewImage(request, rr);
- //return getImage(request,fileName, false);
- }
-
- return null;
-
- }
-
- private ArrayList generateNewImage(HttpServletRequest request, ReportRuntime rr) {
- ArrayList images = new ArrayList();
- try {
- //ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
- DataSet ds = null;
- if(request.getSession().getAttribute(AppConstants.RI_CHART_DATA)!=null) {
- ds = (DataSet) request.getSession().getAttribute(AppConstants.RI_CHART_DATA);
- } else {
- ds = rr.loadChartData(pb.getUserId(),request);
- }
- String downloadFileName = "";
- HashMap additionalChartOptionsMap = new HashMap();
- String chartType = nvl(rr.getChartType());
- if(chartType.equals(AppConstants.GT_PIE_MULTIPLE)) {
- additionalChartOptionsMap.put("multiplePieOrderRow", new Boolean((AppUtils.getRequestNvlValue(request, "multiplePieOrder").length()>0?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; i<rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues).size();i++) {
- String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
- chartTitle = rr.getFormFieldFilled(chartTitle);
- downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
- filename = null;/*(String) ChartGen.generateChart( chartType,
- request.getSession(),
- ds,
- legendColumnName,
- chartLeftAxisLabel,
- chartRightAxisLabel,
- rr.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i, i+1),
- rr.getChartColumnColorsList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i, i+1),
- rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i, i+1),
- "",
- chartTitle,
- null,
- rr.getChartWidthAsInt(),
- rr.getChartHeightAsInt(),
- rr.getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, formValues).subList(i,i+1),
- 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();
- }
- }
-
- } else { /** first check the columns to be opened in new charts and loop around in ChartGen generate chart function - sundar**/
- String tempChartGroupPrev = "";
- String tempChartGroupCurrent = "";
- for (int i=0; i<lGroups.size();i++) {
- String chartGroupOrg = (String) lGroups.get(i);
- String chartYAxis = (String) mapYAxis.get(chartGroupOrg);
- //System.out.println("chartGroupOrg " + chartGroupOrg);
- if(nvl(chartGroupOrg).length()>0)
- 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<rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).size();i++) {
- //System.out.println(" rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1) " + rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1));
- //System.out.println(" rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1) " + rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i, i+1));
- //System.out.println(" rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i,i+1) " + rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS).subList(i,i+1));
-
- downloadFileName = AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
- String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
- chartTitle = rr.getFormFieldFilled(chartTitle);
-
- filename = null; /*(String) ChartGen.generateChart( chartType,
- request.getSession(),
- ds,
- legendColumnName,
- chartLeftAxisLabel,
- chartRightAxisLabel,
- (chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1),
- (chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartColumnColorsList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartColumnColorsList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1),
- (chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1),
- "",
- chartTitle,
- null,
- rr.getChartWidthAsInt(),
- rr.getChartHeightAsInt(),
- rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i,i+1),
- 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();
- }
- }
- }
- /** second rest of the columns are merged to one single chart - sundar**/
- // System.out.println(" rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
- // System.out.println(" rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
- // System.out.println(" rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
-
- if((!(lGroups!=null && lGroups.size() > 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<DataValue> 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; i<rowNames.size(); i++) {
- DataValue dv = rowNames.get(i);
- rfmt = dr.getRowFormatter();
-
- cellFont = FontFactory.getFont(FONT_FAMILY,
- FONT_SIZE,
- Font.NORMAL, Color.BLACK);
- if(rfmt != null) {
- cellFormatterFont(rfmt,cellFont);
- }
- cellValue = dv.getDisplayValue();
- if(cellValue.indexOf("|#")!=-1)
- cellValue = cellValue.substring(0,cellValue.indexOf("|"));
-
- 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);
- }
- }
- }
- first = false;
-
- if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*Globals.getMemoryThreshold()/100) ) {
- returnValue = 1;
- }
-
- //addRowHeader(table,dr,idx,rd);
-
- addRowColumns(table,dr,idx);
-
- if (idx % fragmentsize == fragmentsize - 1) {
- document.add(table);
- table.deleteBodyRows();
- table.setSkipFirstHeader(true);
- }
- }
-
- }
- }
-
- //document.add(table);
-
- }
-
- document.add(table);
- paintPdfReportFooter(request, document, rr, f);
-
- return returnValue;
- }
-
- private void addRowHeader(PdfPTable table, DataRow dr, int idx, ReportData rd) {
-
- table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
-
- for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
- RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
- if(idx==0)
- rhc.resetNext();
- RowHeader rh = rhc.getNext();
- //System.out.println(" =============== RowHeader\n "+rh);
-
- Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY,
- FONT_SIZE,
- Font.NORMAL, Color.BLACK);
- if(rh.isBold()) {
- rowHeaderFont.setStyle(Font.BOLD);
- rowHeaderFont.setSize(FONT_SIZE+1f);
- }
-
- if(rh.getColSpan()>0) {
- 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; i<relativeWidths.length; i++)
- relativeWidths[i] = 10f;
-
- int index=0;
- boolean firstPass = true;
-
- for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();)
- {
- if(firstPass) {
- /*if(rd.reportTotalRowHeaderCols!=null) {
- String columnWidth = "5";
-
- if(columnWidth != null && columnWidth.trim().endsWith("%"))
- relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
-
- index++;
- }*/
-
- for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
- String columnWidth = rd.reportRowHeaderCols.getNext().getColumnWidth();
-
- if(columnWidth != null && columnWidth.trim().endsWith("%"))
- relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
-
- index++;
- }
- firstPass = false;
- }
-
- ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
- for (chr.resetNext(); chr.hasNext();) {
-
- ColumnHeader ch = chr.getNext();
-
- if(ch.isVisible()) {
-
- String columnWidth = ch.getColumnWidth();
-
- if(ch.getColSpan() <= 1){
- if(columnWidth != null && columnWidth.trim().endsWith("%"))
- relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
- }
- else {
- for(int i=0; i<ch.getColSpan(); i++) {
- index += i;
- if(columnWidth != null && columnWidth.trim().endsWith("%"))
- relativeWidths[index] =
- (Float.parseFloat(removeLastCharacter(columnWidth)))/ch.getColSpan();
- }
- }
-
- index++;
- }
- }
- }
-
- return relativeWidths;
- }
-
- public static String removeLastCharacter(String str) {
- return str.substring(0, str.length()-1);
- }
-
- private PdfPTable paintPdfReportHeader(HttpServletRequest request, Document document, PdfPTable table, 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("TITLE_"+index);
- String subtitle = (String) session.getAttribute("SUBTITLE_"+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-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, "<BR/>", " ");
- title = Utils.replaceInString(title, "<br/>", " ");
- title = Utils.replaceInString(title, "<br>", " ");
- title = strip.stripHtml(nvl(title).trim());
- //subtitle = Utils.replaceInString(subtitle, "<BR/>", " ");
- //subtitle = Utils.replaceInString(subtitle, "<br/>", " ");
- //subtitle = Utils.replaceInString(subtitle, "<br>", " ");
- //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, "<BR/>", " ");
- title = Utils.replaceInString(title, "<br/>", " ");
- title = Utils.replaceInString(title, "<br>", " ");
- 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"));
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 {
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String, String> chartOptionsMap = new HashMap<String, String>();
- 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<String,String> chartOptionsMap = new HashMap<String, String>();
- 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<String,String> 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<String> ts1 = new HashSet();
- ArrayList<String> ts1 = new ArrayList();
- HashMap<String, String> 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("<!DOCTYPE html>\n");
- wholeScript.append("<html>\n");
- wholeScript.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF8\">\n");
- wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n");
- wholeScript.append("<link href=\""+ chartScriptsPath +"d3/css/nv.d3.css\" rel=\"stylesheet\" type=\"text/css\">\n");
- //wholeScript.append("")
- wholeScript.append("<style>\n " +
- " body { \n" +
- " overflow-y:scroll; \n" +
- " } \n" +
- " text { \n" +
- " font: 12px sans-serif; \n" +
- " } \n" +
- " svg { \n" +
- " display: block;\n" +
- " } \n" +
- " #chart"+reportRuntime.getReportID()+" svg { \n" +
- " height: "+ (nvl(height).length()>0?(height.endsWith("px")?height:height+"px"):"420px") + "; \n" +
- " width: "+ (nvl(width).length()>0?(width.endsWith("px")?width:width+"px"):"700px") + "; \n" +
- " min-width: 100px; \n" +
- " min-height: 100px; \n" +
- " } \n" +
- " tr.z-row-over > td.z-row-inner, tr.z-row-over > .z-cell {" +
- " background-color: rgb(255, 255, 255); "+
- "} \n");
-
- wholeScript.append(".nodatadiv {\n");
- wholeScript.append(" display: table-cell;\n");
- wholeScript.append(" width: 700px;\n");
- wholeScript.append(" height:370px;\n");
- wholeScript.append(" text-align:center;\n");
- wholeScript.append(" vertical-align: middle;\n");
- wholeScript.append("}\n");
- wholeScript.append(".nodatainner {\n");
- wholeScript.append(" padding: 10px;\n");
- wholeScript.append("}\n");
-
- wholeScript.append(" </style> \n" );
- wholeScript.append("<body> \n");
- if(showTitle)
- wholeScript.append("<div align=\"center\"><H3>" + title +"</H3></div>");
-
- wholeScript.append("<div id=\"chart"+reportRuntime.getReportID()+"\"> <svg></svg> </div> \n");
- //js files
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/d3.v3.min.js\"></script>");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/nv.d3.min.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/tooltip.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/utils.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/axis.min.js\"></script> \n");
- //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/discreteBar.js\"></script> \n");
- //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/discreteBarChart.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/multiChart.js\"></script> \n");
- //json
- wholeScript.append("<script> \n");
- wholeScript.append("historicalBarChart = [ \n");
- //wholeScript.append("{ \n");
- // data
- ArrayList dataSeries = new ArrayList();
-
- String uniqueElement = "";
- for (int i = 0; i < uniqueElements.length; i++) {
- uniqueElement = (String)uniqueElements[i];
- if(multipleSeries && (nvl(chartRightAxisLabel).length() > 0))
- dataSeries.add(new StringBuffer(" { \"type\":\"bar\", \"key\": \""+ (hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement) +"\", \"yAxis\": \""+(i+1)+"\", "+ (hasCustomizedChartColor?("\"color\": \""+uniqueElement.substring(uniqueElement.indexOf("|")+1) + "\","):"")+"\"values\": ["));
- else
- dataSeries.add(new StringBuffer(" { \"type\":\"bar\", \"key\": \""+ (hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement) +"\", \"yAxis\": \""+(1)+"\", "+ (hasCustomizedChartColor?("\"color\": \""+uniqueElement.substring(uniqueElement.indexOf("|")+1) + "\","):"")+"\"values\": ["));
- }
-
- // added to load all date elements
- HashMap<String, HashMap<String, String>> dataSeriesMap = new HashMap<String, HashMap<String, String>>();
-
- for (int i = 0; i < uniqueElements.length; i++) {
- if(multipleSeries && (nvl(chartRightAxisLabel).length() > 0))
- dataSeriesMap.put((String) uniqueElements[i], new HashMap<String, String>());
- //dataSeries.add(new StringBuffer(" { \"type\":\"bar\", \"key\": \""+ uniqueElements[i] +"\", \"yAxis\": \""+(i+1)+"\", \"values\": ["));
- else
- dataSeriesMap.put((String) uniqueElements[i], new HashMap<String, String>());
-
- //dataSeries.add(new StringBuffer(" { \"type\":\"bar\", \"key\": \""+ uniqueElements[i] +"\", \"yAxis\": \""+(1)+"\", \"values\": ["));
- }
-
- 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<String> dateStrList = new TreeSet<String>();
- // added to store all date elements
- SortedSet<String> sortSet = new TreeSet<String>();
- int count = 0;
- if(flag!= 1) {
- HashMap dataSeriesStrMap = new HashMap();
- HashMap dataSeriesOverAllMap = new HashMap();
- String valueDataSeries = "";
-
- for (int j = 0; j < uniqueElements.length; j++) {
- dataSeriesStrMap = new HashMap();
- for (int i = 0; i < ds.getRowCount(); i++) {
- flagNoDate = 0;
- YAXISNUM = 0;
- YAXISDOUBLENUM = 0.0;
- flagNull= 0;
- dateStr = ds.getString(i, 1);
- if(timeAxis) {
- date = getDateFromDateStr(dateStr);
- formatFlag = getFlagFromDateStr(dateStr);
- }
- uniqueElement = (String)uniqueElements[j];
- if(date==null) {
- //continue;
- flagNoDate = 1;
- int pos = 0;
- //if(!((String)uniqueElementsList.get(i)).equals(dateStr)) {
- for (int f=0 ; f< uniqueXAxisElements.length; f++) {
- if(uniqueXAxisElements[f].equals(dateStr)){
- pos = f ;
- break;
- }
- }
- /*for(int f=0; f<uniqueElementsList.size() && f < pos; f++)
- {
- StringBuffer strBuf = ((StringBuffer)dataSeries.get(j));
- if(strBuf.indexOf((String)uniqueElementsList.get(f)) < 0 ) {
- dataSeriesStrMap.put((String)uniqueElementsList.get(f), value);
- //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + (String)uniqueElementsList.get(f) + "\" , \"y\": null },");
- }
- }*/
- //}
-
- dateStrList.add("'"+dateStr+"'");
- //uniqueElement = (String)uniqueElements[j];
- try {
- YAXISNUM = Integer.parseInt(ds.getString(i, columnMap.get((hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement))));
- //if(MAXNUM < YAXISNUM) MAXNUM = YAXISNUM;
- if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
- } catch (NumberFormatException ex) {
- try {
- YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, columnMap.get((hasCustomizedChartColor?(uniqueElement.indexOf("|")!=-1?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement):uniqueElement))));
- MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
- if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
- } catch (NumberFormatException ex1) {
- flagNull = 1;
- }
- //flagNull = 1;
- }
- /* For Non-date type value enclose with double quotes */
- // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
- if(logScale) {
- // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():(YAXISNUM>0?new Double(Math.log10(new Integer(YAXISNUM).doubleValue())).toString():null)):null) +"}, ");
- valueDataSeries = "{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ";
- dataSeriesStrMap.put(dateStr, valueDataSeries);
- } else {
- //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
- valueDataSeries = "{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ";
- dataSeriesStrMap.put(dateStr, valueDataSeries);
-
- }
-
- dataSeriesOverAllMap.put(uniqueElements[j], dataSeriesStrMap);
-
- //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":\"" + ds.getString(i, columnMap.get((String)uniqueElements[j])) +"\"}, ");
- } else {
-
- if(!barRealTimeAxis) { // true - non-time
- if(!dateStrList.contains(new Long(date.getTime()).toString())) {
- dateStrList.add(new Long(date.getTime()).toString());
- for (int k = 0; k < uniqueElements.length; k++) {
- //((StringBuffer) dataSeries.get(k)).append ("{ \"x\":" + date.getTime() + " , \"y\":null}, ");
- HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[k]);
- dataMap.put(date.getTime()+"", "null");
-
- }
- }
- }
- //if(ds.getString(i, 2).equals(uniqueElements[j])) {
- /*if(!dateStrList.contains(new Long(date.getTime()).toString())) {
- for (int k = 0; k < uniqueElements.length; k++) {
- ((StringBuffer) dataSeries.get(k)).append ("{ \"x\":" + date.getTime() + " , \"y\":null}, ");
- }
- }*/
- //dateStrList.add(new Long(date.getTime()).toString());
- try {
- YAXISNUM = Integer.parseInt(ds.getString(i, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
- dateStrList.add(new Long(date.getTime()).toString());
- //if(MAXNUM < YAXISNUM) MAXNUM = YAXISNUM;
- if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
- } catch (NumberFormatException ex) {
- try {
- YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
- MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
- if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
- } catch (NumberFormatException ex1) {
- flagNull = 1;
- }
-
- //flagNull = 1;
- }
- HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[j]);
- if(logScale) {
- dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():(YAXISNUM>0?new Double(Math.log10(new Integer(YAXISNUM).doubleValue())).toString():null)): "null"));
- } else {
- dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(YAXISDOUBLENUM).toString():new Integer(YAXISNUM).toString()): "null"));
- }
-
-
- // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
-
- //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + ds.getString(i, columnMap.get((String)uniqueElements[j])) +"}, ");
- }
- //}
- }
- }
- for(int kI = 0; kI < uniqueElements.length; kI++) {
- HashMap dataSeriesStrMap1 = (HashMap) dataSeriesOverAllMap.get(uniqueElements[kI]);
- for (int kL = 0; kL < uniqueXAxisElements.length; kL++) {
- if(dataSeriesStrMap1.containsKey(uniqueXAxisElements[kL])) {
- ((StringBuffer) dataSeries.get(kI)).append ((String)dataSeriesStrMap1.get(uniqueXAxisElements[kL]));
- } else {
- ((StringBuffer) dataSeries.get(kI)).append ("{ \"x\":\"" + uniqueXAxisElements[kL] + "\" , \"y\": null }, ");
- }
- }
- }
-
- } else {
- HashMap dataSeriesStrMap = new HashMap();
- HashMap dataSeriesOverAllMap = new HashMap();
- String valueDataSeries = "";
- for (int j = 0; j < uniqueElements.length; j++) {
- dataSeriesStrMap = new HashMap();
-
- for (int i = 0; i < ds.getRowCount(); i++) {
- flagNoDate = 0;
- YAXISNUM = 0;
- YAXISDOUBLENUM = 0.0;
- flagNull= 0;
- //flagSecondNull = 0;
- dateStr = ds.getString(i, 1);
- if(timeAxis) {
- date = getDateFromDateStr(dateStr);
- formatFlag = getFlagFromDateStr(dateStr);
- }
- uniqueElement = (String)uniqueElements[j];
- if(date==null) {
- //continue;
- flagNoDate = 1;
- int pos = 0;
- //if(!((String)uniqueElementsList.get(i)).equals(dateStr)) {
- for (int f=0 ; f< uniqueXAxisElements.length; f++) {
- if(uniqueXAxisElements[f].equals(dateStr)){
- pos = f ;
- break;
- }
- }
- /*for(int f=0; f<uniqueElementsList.size() && f < pos; f++)
- {
- StringBuffer strBuf = ((StringBuffer)dataSeries.get(j));
- if(strBuf.indexOf((String)uniqueElementsList.get(f)) < 0 ) {
- dataSeriesStrMap.put((String)uniqueElementsList.get(f), value);
- //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + (String)uniqueElementsList.get(f) + "\" , \"y\": null },");
- }
- }*/
- //}
-
- if(ds.getString(i, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
- dateStrList.add("'"+dateStr+"'");
- try {
- YAXISNUM = Integer.parseInt(ds.getString(i, 3));
- if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
- } catch (NumberFormatException ex) {
- try {
- YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, 3));
- MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
- if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
- } catch (NumberFormatException ex1) {
- flagNull = 1;
- }
-
- //flagNull = 1;
- }
-
- if(logScale) {
- if(timeAxis) {
- //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + dateStr + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ");
- valueDataSeries = "{ \"x\":" + dateStr + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ";
- dataSeriesStrMap.put(dateStr, valueDataSeries);
- } else {
- // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ");
- valueDataSeries = "{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): null) +"}, ";
- dataSeriesStrMap.put(dateStr, valueDataSeries);
- }
- } else {
- if(timeAxis) {
- //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + dateStr + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ");
- valueDataSeries = "{ \"x\":" + dateStr + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ";
- dataSeriesStrMap.put(dateStr, valueDataSeries);
-
- } else {
- //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ");
- valueDataSeries = "{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ";
- dataSeriesStrMap.put(dateStr, valueDataSeries);
-
- }
- }
-
- /*if(ds.getString(i, 2).equals(uniqueElements[j])) {
- dateStrList.add("'"+dateStr+"'");
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":\"" + ds.getString(i, 3) +"\"}, ");
- */
- }
- dataSeriesOverAllMap.put(uniqueElements[j], dataSeriesStrMap);
- } else {
- //date = MMDDYYYYFormat.parse(ds.getString(i, 1), new ParsePosition(0));
- if(!barRealTimeAxis) { // true - non-time
- if(!dateStrList.contains(new Long(date.getTime()).toString())) {
- dateStrList.add(new Long(date.getTime()).toString());
- for (int k = 0; k < uniqueElements.length; k++) {
- //((StringBuffer) dataSeries.get(k)).append ("{ \"x\":" + date.getTime() + " , \"y\":null}, ");
- HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[k]);
- dataMap.put(date.getTime()+"", "null");
-
- }
- }
- }
- if(ds.getString(i, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
- dateStrList.add(new Long(date.getTime()).toString());
- try {
- YAXISNUM = Integer.parseInt(ds.getString(i, 3));
- if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
- } catch (NumberFormatException ex) {
- try {
- YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, 3));
- MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
- if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
- } catch (NumberFormatException ex1) {
- flagNull = 1;
- }
-
- //flagNull = 1;
- }
-
- //if(ds.getString(i, 2).equals(uniqueElements[j])) {
- // dateStrList.add("'"+dateStr+"'");
- HashMap<String, String> dataMap = dataSeriesMap.get((String) uniqueElements[j]);
- if(logScale) {
- dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(Math.log10(YAXISDOUBLENUM)).toString():new Double(Math.log10(new Double(YAXISNUM>0?YAXISNUM:1).doubleValue())).toString()): "null"));
- } else {
- if(dataMap.containsKey(new String(""+date.getTime())) && dataMap.get(new String(""+date.getTime())).equals("null")) {
- dataMap.remove(date.getTime());
- }
- dataMap.put(date.getTime()+"", (flagNull == 0 ? (YAXISDOUBLENUM>0?new Double(YAXISDOUBLENUM).toString():new Integer(YAXISNUM).toString()): "null"));
- //System.out
- // .println(dataMap + " " + dataSeriesMap);
- //}
- }
- // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ");
-
-
- //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + ds.getString(i, 3) +"}, ");
- } else if (AppUtils.nvl(ds.getString(i, 2)).length()<=0) {
- dateStrList.add(new Long(date.getTime()).toString());
- HashMap<String, String> dataMap1 = null;
- String uniqueElement1 = "";
- for (int j1 = 0; j1 < uniqueElements.length; j1++) {
- uniqueElement1 = (String)uniqueElements[j];
- if(ds.getString(i, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement1.lastIndexOf("|") != -1) ?uniqueElement1.substring(0, uniqueElement1.lastIndexOf("|")):uniqueElement1))) {
- dataMap1 = dataSeriesMap.get((String) uniqueElements[j1]);
- if(!dataMap1.containsKey(new String(""+date.getTime())))
- dataMap1.put(date.getTime()+"", "null");
- }
- }
- }
- }
- // dataSeriesOverAllMap.put(uniqueElements[j], dataSeriesMap);
- }
-
- }
- for(int kI = 0; kI < uniqueElements.length; kI++) {
- HashMap dataSeriesStrMap1 = (HashMap) dataSeriesOverAllMap.get(uniqueElements[kI]);
- for (int kL = 0; kL < uniqueXAxisElements.length; kL++) {
- if(dataSeriesStrMap1.containsKey(uniqueXAxisElements[kL])) {
- ((StringBuffer) dataSeries.get(kI)).append ((String)dataSeriesStrMap1.get(uniqueXAxisElements[kL]));
- } else {
- ((StringBuffer) dataSeries.get(kI)).append ("{ \"x\":\"" + uniqueXAxisElements[kL] + "\" , \"y\": null }, ");
- }
- }
- }
- }
-
- StringBuffer dateStrBuf = new StringBuffer("");
- /*if(count == 1) {
- Long initialDate = Long.parseLong((String)ds.getString(0, 0));
- Long endDate = Long.parseLong((String) ds.getString(ds.getRowCount(), 0));
- java.util.Date date1 = null;
-
- while ( initialDate <= endDate) {
- //System.out.println("********** " + df.format(initialDate));
- date1 = new java.util.Date(initialDate.longValue() * 1000);
- initialDate = initialDate + HOUR;
-
- dateStrBuf.append(initialDate+",");
- sortSet.add(""+initialDate);
- //DateUtils.addHours(date1, 1);
- }
- }*/
-
- if(dateStrList.size()>0) {
- SortedSet<String> s = Collections.synchronizedSortedSet(dateStrList);
- Object[] dateElements = (Object[]) s.toArray();
-
- String element = "";
- /* if not date value */
- if(!timeAxis) {
- for (int i = 0; i < dateElements.length; i++) {
- dateStrBuf.append(dateElements[i]+",");
- }
- } else {
- if(!barRealTimeAxis || (flagNoDate == 1)) { // non-time
- for (int i = 0; i < dateElements.length; i++) {
- dateStrBuf.append(dateElements[i]+",");
- }
- } else {
- Long initialDate = Long.parseLong((String)dateElements[0]);
- Long endDate = Long.parseLong((String) dateElements[dateElements.length-1]);
- java.util.Date date1 = null;
- //first value
- date1 = new java.util.Date(initialDate.longValue());
- /* DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss Z");
- System.out.println(formatter.format(new java.util.Date(initialDate.longValue())));
- */ //initialDate = initialDate + HOUR;
-
- dateStrBuf.append(initialDate+",");
- sortSet.add(""+initialDate);
-
- // DateUtils.
-
- while ( initialDate <= endDate) {
- //System.out.println("********** " + df.format(initialDate));
- //date1 = new java.util.Date(initialDate.longValue() * 1000);
- date1 = new java.util.Date(initialDate.longValue());
- if(formatFlag==HOURFLAG)
- date1 = DateUtils.addHours(date1, 1);
- else if(formatFlag==MINFLAG)
- date1 = DateUtils.addMinutes(date1, 30);
- else if (formatFlag == DAYFLAG)
- date1 = DateUtils.addDays(date1, 1);
- else if (formatFlag == MONTHFLAG)
- date1 = DateUtils.addMonths(date1, 1);
- else if (formatFlag == YEARFLAG)
- date1 = DateUtils.addMonths(date1, 1);
- initialDate = date1.getTime();
-
- if(initialDate <= endDate) {
- dateStrBuf.append(initialDate+",");
- sortSet.add(""+initialDate);
- }
- //DateUtils.addHours(date1, 1);
- }
- //DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
- //df.setTimeZone(TimeZone.getTimeZone("UTC"));
- //java.util.Date date1 = new java.util.Date(initialDate.longValue() * 1000);
- //java.util.Date d = df.
- //for ()
- }
- }
- dateStrBuf.deleteCharAt(dateStrBuf.length()-1);
- }
-
- if(timeAxis) {
- //if(!barRealTimeAxis) { // false - non-time
- Object[] dateAllElements = (Object[]) sortSet.toArray();
-
- for (int i = 0; i < uniqueElements.length; i++) {
- HashMap<String, String> dataMap = dataSeriesMap.get((String)uniqueElements[i]);
- for (int j=0; j<dateAllElements.length;j++) {
- //if(strBuf.toString().indexOf((String) dateAllElements[j]) == -1) {
- if(!dataMap.containsKey((String) dateAllElements[j])) {
- dataMap.put((String) dateAllElements[j], "null");
- //((StringBuffer) dataSeries.get(i)).append ("{ \"x\":" + dateAllElements[j] + " , \"y\":null}, ");
- }
- }
- }
- //}
- }
- String valueStr = "";
- for (int i = 0; i < uniqueElements.length; i++) {
- HashMap<String, String> dataMap = dataSeriesMap.get((String)uniqueElements[i]);
- Set<String> keySet = dataMap.keySet();
- ArrayList<String> keySortedList = new ArrayList<String>(new TreeSet<String>(keySet));
-
- for (int k=0; k < keySortedList.size(); k++) {
- valueStr = dataSeriesMap.get((String)uniqueElements[i]).get(keySortedList.get(k));
- if(valueStr.equals("null"))
- valueStr = null;
- else {
- //if(logScale)
- //valueStr = new Double(Math.log10(new Double(valueStr).doubleValue())).toString();
- }
- ((StringBuffer) dataSeries.get(i)).append ("{ \"x\":" + keySortedList.get(k) + " , \"y\":" + valueStr +"}, ");
- // ((StringBuffer) dataSeries.get(i)).append ("{ \"x\":" + keySortedList.get(k) + " , \"y\":" + valueStr +"}, ");
- }
-
- // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + (flagNull == 0 ? (YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM): null) +"}, ");
- }
-
- for (int i = 0; i < uniqueElements.length; i++) {
- StringBuffer strBuf = ((StringBuffer) dataSeries.get(i));
- ((StringBuffer) dataSeries.get(i)).deleteCharAt(((StringBuffer) dataSeries.get(i)).lastIndexOf(","));
- if(i < (uniqueElements.length -1) ) {
- ((StringBuffer) dataSeries.get(i)).append("] } , \n");
- }
- else {
- ((StringBuffer) dataSeries.get(i)).append("] } \n");
- }
- }
- if(ds.getRowCount() > 0) {
- for (int i = 0; i < uniqueElements.length; i++) {
- wholeScript.append((StringBuffer)dataSeries.get(i));
- }
- }
-
-
- wholeScript.append("]; \n");
-
- //add global variable
- wholeScript.append("var chart; \n");
- //javascript to create Bar Chart
- wholeScript.append("nv.addGraph(function() { \n");
- if(horizontalBar /*&& flagNoDate == 1*/)
- wholeScript.append(" chart = nv.models.multiBarHorizontalChart() \n");
- else /*if (flagNoDate == 1)*/
- wholeScript.append(" chart = nv.models.multiBarChart() \n");
- /*else
- wholeScript.append(" var chart = nv.models.multiBarTimeSeriesChart() \n");*/
-
- wholeScript.append(" .margin({top: "+ topMargin +", right: "+ rightMargin +", bottom: "+ bottomMargin +", left: " + leftMargin +"}) \n");
- if(showLegend) {
- wholeScript.append(" .showLegend(true) \n ");
- } else {
- wholeScript.append(" .showLegend(false) \n ");
- }
- if(!horizontalBar && barReduceXAxisLabels)
- wholeScript.append(" .reduceXTicks(true) \n ");
- else if (!horizontalBar) {
- wholeScript.append(" .reduceXTicks(false) \n ");
- //wholeScript.append(" chart.lines1.forceY(["+(nvl(reportRuntime.getRangeAxisLowerLimit()).length()<=0?"0":reportRuntime.getRangeAxisLowerLimit()) +", "+ (nvl(reportRuntime.getRangeAxisUpperLimit()).length()<=0?UPPER_RANGE:reportRuntime.getRangeAxisUpperLimit()) + "]); \n" +
- double UPPER_RANGE = 0;
- if(Math.ceil((MAXDOUBLENUM+(MAXDOUBLENUM*25/100))/100) * 100 >= 1) {
- UPPER_RANGE = Math.ceil(MAXDOUBLENUM+(MAXDOUBLENUM*25/100));
- } else UPPER_RANGE = 1;
- wholeScript.append(" .forceY(["+(nvl(reportRuntime.getRangeAxisLowerLimit()).length()<=0?"0":reportRuntime.getRangeAxisLowerLimit()) +", "+ (nvl(reportRuntime.getRangeAxisUpperLimit()).length()<=0?UPPER_RANGE:reportRuntime.getRangeAxisUpperLimit()) + "])\n");
- }
- if(!animation) {
- wholeScript.append(" .delay(0) \n ");
- }
- if(showControls) {
- wholeScript.append(" .showControls(true) \n ");
- } else if (!showControls){
- wholeScript.append(" .showControls(false) \n ");
- }
- if(stacked && !logScale)
- wholeScript.append(" .stacked(true)\n ");
- else if(!stacked || logScale)
- wholeScript.append(" .stacked(false)\n ");
- if(logScale) {
- wholeScript.append(" .logScale(true)\n ");
- } else {
- wholeScript.append(" .logScale(false)\n ");
- }
-
- if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
- wholeScript.append(" .legendPos('right')\n" );
- } else {
- wholeScript.append(" .legendPos('top')\n" );
- }
- if(uniqueElements.length <= 10) {
- wholeScript.append(" .color(d3.scale.category10().range()); \n" +
- " chart.xAxis\n");
- } else if (uniqueElements.length <= 20) {
- wholeScript.append(" .color(d3.scale.category50().range()); \n" +
- " chart.xAxis\n");
- } else {
- wholeScript.append(" .color(d3.scale.category50().range()); \n" +
- " chart.xAxis\n");
-
- }
-
- if(flagNoDate == 0)
- wholeScript.append(" .tickValues(["+ dateStrBuf.toString() + "])\n ");
- else {
- wholeScript.append(" .tickValues(["+ dateStrBuf.toString() + "])\n ");
- }
- if(staggerLabels) {
- wholeScript.append(" .staggerLabels(true) \n");
- } else {
- wholeScript.append(" .staggerLabels(false) \n");
- }
- if(!horizontalBar) {
- if(showMaxMin) {
- wholeScript.append(" .showMaxMin(true) \n ");
- } else {
- wholeScript.append(" .showMaxMin(false) \n ");
- }
- }
- if(nvl(rotateLabels).length()>0) {
- wholeScript.append(" .rotateLabels("+ rotateLabels+ ") \n ");
- } else {
- wholeScript.append(" .rotateLabels(\"0\") \n ");
- }
- wholeScript.append(" .axisLabel('" + legendColumnName + "')");
- if(flagNoDate == 1 || !timeAxis) {
- wholeScript.append(";\n");
- } else {
- wholeScript.append("\n .tickFormat(function(d) { \n");
- if(timeAxis) {
- if(formatFlag==HOURFLAG)
- wholeScript.append(" return d3.time.format('%x %H')(new Date(d)) }); \n");
- else if(formatFlag==MINFLAG)
- wholeScript.append(" return d3.time.format('%x %H:%M')(new Date(d)) }); \n");
- else if(formatFlag==SECFLAG)
- wholeScript.append(" return d3.time.format('%X')(new Date(d)) }); \n");
- else if(formatFlag==MONTHFLAG)
- wholeScript.append(" return d3.time.format('%b %y')(new Date(d)) }); \n");
- else
- wholeScript.append(" return d3.time.format('%x')(new Date(d)) }); \n");
-
- } else {
- wholeScript.append(" return d; }); \n");
- }
- }
-
- if(nvl(chartRightAxisLabel).length() > 0) {
- //if(flagNoDate == 1)
- wholeScript.append(" chart.yAxis\n");
- //else
- // wholeScript.append(" chart.yAxis1\n");
- if(logScale) {
- wholeScript.append(" .logScale(true)\n ");
- } else {
- wholeScript.append(" .logScale(false)\n ");
- }
-
- wholeScript.append(" .axisLabel('" + chartLeftAxisLabel + "') \n" +
- " .tickFormat(d3.format(',.0f')); \n");
- /*" chart.yAxis2\n " +
- " .axisLabel('" + chartRightAxisLabel + "') \n" +
- " .tickFormat(d3.format(',.0f')); \n");*/
-
-
- } else {
- //if(flagNoDate == 1)
- wholeScript.append(" chart.yAxis\n");
- //else
- // wholeScript.append(" chart.yAxis1\n");
- if(logScale) {
- wholeScript.append(" .logScale(true)\n ");
- } else {
- wholeScript.append(" .logScale(false)\n ");
- }
- wholeScript.append(" .axisLabel('" + chartLeftAxisLabel + "') \n");
-
- if(MAXDOUBLENUM <=5 && MAXNUMDECIMALPLACES == 0 ) MAXNUMDECIMALPLACES = 2;
- if( MAXNUMDECIMALPLACES >=3 ) MAXNUMDECIMALPLACES = 2;
- if(!logScale)
- wholeScript.append(" .tickFormat(d3.format(',."+MAXNUMDECIMALPLACES+"f')); \n");
- else
- wholeScript.append(" .tickFormat(d3.format(',." + precision + "f')); \n");
- //" .tickFormat(d3.format(',.0f')); \n");
- }
- wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n" +
- " .datum(historicalBarChart) \n" );
- if(animation)
- wholeScript.append(" .transition().duration(1000) \n" );
- else
- wholeScript.append(" .transition().duration(0) \n" );
- wholeScript.append(" .call(chart); \n" +
- "nv.utils.windowResize(chart.update); \n" +
- "return chart; \n" +
- "}); \n");
- wholeScript.append("function redraw() { \n");
- //wholeScript.append(" nv.utils.windowResize(chart.update); \n");
- wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n") ;
- wholeScript.append(" .datum(historicalBarChart) \n");
- wholeScript.append(" .transition().duration(500) \n");
- wholeScript.append(" .call(chart); \n");
- wholeScript.append("} \n");
- wholeScript.append("\n");
- wholeScript.append(" setInterval(function () { \n");
- wholeScript.append(" redraw(); \n");
- wholeScript.append(" }, 1500) \n");
-
- wholeScript.append("if(historicalBarChart.length <= 0 ) {\n");
- wholeScript.append(" document.getElementById(\"chart"+reportRuntime.getReportID()+"\").innerHTML = \"<div id='noData'><b>No Data Available</b></div>\";\n");
- wholeScript.append(" document.getElementById(\"chart"+reportRuntime.getReportID()+"\").className=\"nodatadiv\";\n");
- wholeScript.append(" document.getElementById(\"nodata\").className=\"nodatainner\";\n");
- wholeScript.append("}\n");
- wholeScript.append("</script> </body></html> \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<String>();
- HashMap<String, String> 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<String> 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<String> colorList = new TreeSet<String>();
- 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<String> 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("<!DOCTYPE html>\n");
- wholeScript.append("<html>\n");
- wholeScript.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF8\">\n");
- wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n");
- wholeScript.append("<link href=\""+ chartScriptsPath +"d3/css/nv.d3.css\" rel=\"stylesheet\" type=\"text/css\">\n");
- wholeScript.append("<style>\n " +
- " body { \n" +
- " overflow-y:scroll; \n" +
- " } \n" +
- " text { \n" +
- " font: 12px sans-serif; \n" +
- " } \n" +
- " svg { \n" +
- " display: block;\n" +
- " } \n" +
- " #chart"+reportRuntime.getReportID()+" svg { \n" +
- " height: "+ (nvl(height).length()>0?(height.endsWith("px")?height:height+"px"):"420px") + "; \n" +
- " width: "+ (nvl(width).length()>0?(width.endsWith("px")?width:width+"px"):"700px") + "; \n" +
- " min-width: 100px; \n" +
- " min-height: 100px; \n" +
- " } \n" +
- " tr.z-row-over > td.z-row-inner, tr.z-row-over > .z-cell {" +
- " background-color: rgb(255, 255, 255); "+
- "}\n");
- wholeScript.append(".nodatadiv {\n");
- wholeScript.append(" display: table-cell;\n");
- wholeScript.append(" width: 700px;\n");
- wholeScript.append(" height:370px;\n");
- wholeScript.append(" text-align:center;\n");
- wholeScript.append(" vertical-align: middle;\n");
- wholeScript.append("}\n");
- wholeScript.append(".nodatainner {\n");
- wholeScript.append(" padding: 10px;\n");
- wholeScript.append("}\n");
-
- wholeScript.append(" </style> \n" );
-
- wholeScript.append("<body> \n");
-
- if(showTitle)
- wholeScript.append("<div align=\"center\"><H3>" + title +"</H3></div>");
-
-
- wholeScript.append("<div id=\"chart"+reportRuntime.getReportID()+"\"> <svg></svg> </div> \n");
- //js files
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/d3.v3.min.js\"></script>\n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/nv.d3.min.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/axis.min.js\"></script> \n");
- //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/cumulativeLineChart.js\"></script> \n");
- //if(multipleSeries)
- //wholeScript.append("<script src=\""+ AppUtils.getBaseFolderURL() +"d3/js/models/multiChart.js\"></script> \n");
-
- //json
- wholeScript.append("<script> \n");
-
- wholeScript.append("historicalBarChart = [ \n");
- //wholeScript.append("{ \n");
- ArrayList dataSeries = new ArrayList();
- String uniqueElement = "";
-
- String [] uniqueRevElements = null;
- //Added to make sure order appears same as legend
- /*if(nvl(subType).length() > 0 && subType.equals("area")) {
- uniqueRevElements = reverse((String[])uniqueElements);
- } else {*/
- uniqueRevElements = (String[])uniqueElements;
- //}
-
- int RIGHTAXISSERIES = 0;
- for (int i = 0; i < uniqueRevElements.length; i++) {
- //element.substring(element.indexOf("|")+1)
- uniqueElement = (String)uniqueRevElements[i];
- if(multipleSeries && (nvl(chartRightAxisLabel).length() > 0)) {
- if(nvl(subType).length() > 0 && subType.equals("area")) {
- if(nvl(uniqueElement).indexOf("|R") !=-1)
- dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(2)+"\", "+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1) ?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+" \"values\": ["));
- else
- dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(1)+"\", "+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1) ?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+" \"values\": ["));
- } else {
- if(nvl(uniqueElement).indexOf("|R") !=-1)
- dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(2)+"\","+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1) ?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+" \"values\": ["));
- else
- dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(1)+"\","+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1) ?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+" \"values\": ["));
- }
- RIGHTAXISSERIES = dataSeries.size()-1;
- //dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((DataColumnType)columnMap.get(i)).getDisplayName() +"\", \"yAxis\": \""+(i+1)+"\", \"values\": ["));
- }
- else {
- dataSeries.add(new StringBuffer(" { \"type\":\"line\", \"key\": \""+ ((uniqueElement.indexOf("|")!= -1)?uniqueElement.substring(0, uniqueElement.indexOf("|")):uniqueElement) +"\", \"yAxis\": \""+(1)+"\","+ (hasCustomizedChartColor && (uniqueElement.lastIndexOf("|") != -1)?("\"color\": \""+uniqueElement.substring(uniqueElement.lastIndexOf("|")+1) + "\","):"")+"\"values\": ["));
- }
-
- }
- /*StringBuffer dataSeries1 = new StringBuffer("");
- dataSeries1.append(" { key: \"Series1\",values: [");
- StringBuffer dataSeries2 = new StringBuffer("");
- dataSeries2.append(" { key: \"Series2\", values: [");
- StringBuffer dataSeries3 = new StringBuffer("");
- dataSeries3.append(" { key: \"Series3\", values: [");
- */
-
-
- //long minTime = 1000000000000000L;
- int MAXNUM = 0;
- double MAXDOUBLENUM = 0.0;
- int YAXISNUM = 0;
- double YAXISDOUBLENUM = 0.0;
- int MAXNUMDECIMALPLACES = 0;
- int flagNull = 0;
- int flagSecondNull = 0;
- TreeSet dateList = new TreeSet();
- int formatFlag = 0;
- if(flag!= 1) {
- for (int j = 0; j < uniqueRevElements.length; j++) {
- for (int i = 0; i < ds.getRowCount(); i++) {
- flagNull = 0;
- flagSecondNull=0;
- YAXISNUM = 0;
- YAXISDOUBLENUM = 0.0;
- dateStr = "";
- date = null;
- dateStr = ds.getString(i, 1);
- if(timeAxis) {
- date = getDateFromDateStr(dateStr);
- formatFlag = getFlagFromDateStr(dateStr);
- }
- if(date==null && timeAxis) continue;
-
-
- //if(ds.getString(i, 2).equals(uniqueElements[j])) {
- //if(minTime > date.getTime())
- // minTime = date.getTime();
- uniqueElement = (String)uniqueRevElements[j];
- try {
- YAXISNUM = Integer.parseInt(ds.getString(i, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
- if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
- } catch (NumberFormatException ex) {
- try {
- YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
- if(RIGHTAXISSERIES!=j) {
- MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
- if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
- }
- } catch (NumberFormatException ex1) {
- flagNull = 1;
- }
- }
-
- if(date==null) {
- dateList.add(dateStr);
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
- } else {
- dateList.add(new Long(date.getTime()).toString());
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + (flagNull==0?(YAXISDOUBLENUM>0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
- }
-
-
-
- if(nvl(subType).length() > 0 && subType.equals("area")) {
-
- if(flagNull!=1) {
- if(i<ds.getRowCount()-1) {
- try {
- YAXISNUM = Integer.parseInt(ds.getString(i+1, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1)?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
- if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
- } catch (NumberFormatException ex) {
- try {
- YAXISDOUBLENUM = Double.parseDouble(ds.getString(i+1, columnMap.get(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))));
- if(RIGHTAXISSERIES!=j) {
- MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
- if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
- }
- } catch (NumberFormatException ex1) {
- flagSecondNull = 1;
- }
- }
-
- if(flagSecondNull==1 && date == null) {
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + null +"}, ");
- } else if( flagSecondNull == 1){
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + null +"}, ");
- }
- }
- } else {
- if(i<ds.getRowCount()-1) {
- dateStr = ds.getString(i+1, 1);
-
- if(!timeAxis) {
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":\"" + dateStr + "\" , \"y\":" + null +"}, ");
- } else {
- date = getDateFromDateStr(dateStr);
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + null +"}, ");
- }
- //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + null +"}, ");
- }
- }
-
- }
-
-
- //}
- }
- //((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + minTime + " , \"y\":" + 0 +"}, ");
- }
-
- } else {
- for (int j = 0; j < uniqueRevElements.length; j++) {
- for (int i = 0; i < ds.getRowCount(); i++) {
- YAXISNUM = 0;
- YAXISDOUBLENUM = 0.0;
- flagNull= 0;
- flagSecondNull = 0;
- dateStr = ds.getString(i, 1);
- if(timeAxis) {
- date = getDateFromDateStr(dateStr);
- formatFlag = getFlagFromDateStr(dateStr);
- }
-
- if(date==null && timeAxis) continue;
-
- uniqueElement = (String)uniqueRevElements[j];
- //date = MMDDYYYYFormat.parse(ds.getString(i, 1), new ParsePosition(0));
- if(ds.getString(i, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
- //if(minTime > date.getTime())
- // minTime = date.getTime();
- try {
- YAXISNUM = Integer.parseInt(ds.getString(i, 3));
- if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
- } catch (NumberFormatException ex) {
- try {
- YAXISDOUBLENUM = Double.parseDouble(ds.getString(i, 3));
- if(RIGHTAXISSERIES!=j) {
- MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
- if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
-
- }
- } catch (NumberFormatException ex1) {
- flagNull = 1;
- }
- }
-
- if(date==null) {
- dateList.add(dateStr);
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + dateStr + " , \"y\":" + (flagNull==0?(YAXISDOUBLENUM!=0.0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
- } else {
- dateList.add(new Long(date.getTime()).toString());
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + (flagNull==0?(YAXISDOUBLENUM!=0.0?YAXISDOUBLENUM:YAXISNUM):null) +"}, ");
- }
-
-
- if(nvl(subType).length() > 0 && subType.equals("area")) {
-
- if(flagNull!=1) {
- if(i<ds.getRowCount()-1) {
- for (int k = i+1; k < ds.getRowCount(); k++) {
- if (ds.getString(k, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
- try {
- YAXISNUM = Integer.parseInt(ds.getString(k, 3));
- if(MAXDOUBLENUM < YAXISNUM) MAXDOUBLENUM = YAXISNUM;
- } catch (NumberFormatException ex) {
- try {
- YAXISDOUBLENUM = Double.parseDouble(ds.getString(k, 3));
- if(RIGHTAXISSERIES!=j) {
- MAXNUMDECIMALPLACES = getNumberOfDecimalPlaces(YAXISDOUBLENUM);
- if(MAXDOUBLENUM < YAXISDOUBLENUM) MAXDOUBLENUM = YAXISDOUBLENUM;
- }
- } catch (NumberFormatException ex1) {
- flagSecondNull = 1;
- }
- }
- break;
- }
- }
-
- if(date==null && flagSecondNull==1){
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + dateStr + " , \"y\":" + null +"}, ");
- } else if(flagSecondNull == 1){
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + null +"}, ");
- }
- //}
- }
- } else {
- if(i<ds.getRowCount()-1) {
- for (int k = i+1; k < ds.getRowCount(); k++) {
- if (ds.getString(k, 2).equals(((hasCustomizedChartColor||nvl(chartRightAxisLabel).length()>0) && (uniqueElement.lastIndexOf("|") != -1) ?uniqueElement.substring(0, uniqueElement.lastIndexOf("|")):uniqueElement))) {
- dateStr = ds.getString(k, 1);
- if(!timeAxis) {
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + null +"}, ");
- break;
- } else {
- date = getDateFromDateStr(dateStr);
- ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + date.getTime() + " , \"y\":" + null +"}, ");
- break;
- }
- }
- }
- }
- }
- }
-
- }
- }
- // ((StringBuffer) dataSeries.get(j)).append ("{ \"x\":" + minTime + " , \"y\":" + 0 +"}, ");
-
- }
-/* if(ds.getString(i, 2).equals("Series1")) {
- dataSeries1.append("[ " + date.getTime() + " , " + ds.getString(i, 3) +"], ");
- } else if (ds.getString(i, 2).equals("Series2")) {
- dataSeries2.append("[ " + date.getTime() + " , " + ds.getString(i, 3) +"], ");
- } else if (ds.getString(i, 2).equals("Series3")) {
- dataSeries3.append("[ " + date.getTime() + " , " + ds.getString(i, 3) +"], ");
- }
-*/ }
-
- for (int i = 0; i < uniqueRevElements.length; i++) {
- StringBuffer strBuf = ((StringBuffer) dataSeries.get(i));
- ((StringBuffer) dataSeries.get(i)).deleteCharAt(((StringBuffer) dataSeries.get(i)).lastIndexOf(","));
- if(i < (uniqueRevElements.length -1) ) {
- ((StringBuffer) dataSeries.get(i)).append("] } , \n");
- }
- else {
- ((StringBuffer) dataSeries.get(i)).append("] } \n");
- }
- }
-
- for (int i = 0; i < uniqueRevElements.length; i++) {
- wholeScript.append((StringBuffer)dataSeries.get(i));
- }
-/* wholeScript.append(dataSeries1);
- wholeScript.append(dataSeries2);
- wholeScript.append(dataSeries3);
-*/ wholeScript.append("];\n");
-
- /* Sorting is commented out.*/
- StringBuffer dateStrBuf = new StringBuffer("");
- if(dateList.size()>0) {
- //SortedSet<String> s = Collections.synchronizedSortedSet(dateList);
- Object[] dateElements = (Object[]) dateList.toArray();
-
- String element = "";
-
- for (int i = 0; i < dateElements.length; i++) {
- dateStrBuf.append(dateElements[i]+",");
- }
- dateStrBuf.deleteCharAt(dateStrBuf.length()-1);
- }
-
- wholeScript.append(" var chart;\n");
- wholeScript.append("nv.addGraph(function() { \n");
- //" var chart = nv.models.cumulativeLineChart() \n" + nv.models.lineWithFocusChart()
-// " chart = nv.models.lineChart() \n" +
- if(nvl(subType).length() > 0 && subType.equals("area")) {
- wholeScript.append(" chart = nv.models.stackedAreaChart() \n");
- if(showControls) {
- wholeScript.append(" .showControls(true) \n ");
- } else {
- wholeScript.append(" .showControls(false) \n ");
- }
- } else {
- wholeScript.append(" chart = nv.models.multiChart() \n");
- if(nvl(chartRightAxisLabel).length() > 0) {
- wholeScript.append(" .dualaxis(true) \n ");
- } else {
- wholeScript.append(" .dualaxis(false) \n ");
- }
-
- if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
- wholeScript.append(" .legendPos('right')\n" );
- } else {
- wholeScript.append(" .legendPos('top')\n" );
- }
-
-
- }
-
- wholeScript.append(" .margin({top: "+ topMargin +", right: "+ rightMargin +", bottom: "+ bottomMargin +", left: " + leftMargin +"}) \n");
- if(showLegend) {
- wholeScript.append(" .showLegend(true) \n ");
- } else {
- wholeScript.append(" .showLegend(false) \n ");
- }
-
- if(nvl(subType).length() > 0 && subType.equals("area")) {
- if( MAXNUMDECIMALPLACES >=3 ) {
- wholeScript.append(" .yAxisTooltipFormat(d3.format(',.3f')) \n");
- } else {
- wholeScript.append(" .yAxisTooltipFormat(d3.format(',."+MAXNUMDECIMALPLACES+ "f')) \n");
- }
-
- wholeScript.append(".x (function(d) {return d.x;}) \n" +
- ".y (function(d) {return d.y;}) \n");
- }
-
- //" .x(function(d) { return d[0] }) \n" +
- //" .y(function(d) { return d[1] }) \n" +
- //" .forceY("+(nvl(reportRuntime.getRangeAxisLowerLimit()).length()<=0?"0":reportRuntime.getRangeAxisLowerLimit()) +", "+ Math.ceil((MAXNUM+(MAXNUM*25/100))/100) * 100 + ") \n" + // reportRuntime.getRangeAxisUpperLimit()+") \n" +
- wholeScript.append(" .color(d3.scale.category10().range()); \n");
- if(!(nvl(subType).length() > 0 && subType.equals("area"))) {
- double UPPER_RANGE = 0;
- if(Math.ceil((MAXDOUBLENUM+(MAXDOUBLENUM*25/100))/100) * 100 >= 1) {
- UPPER_RANGE = Math.ceil(MAXDOUBLENUM+(MAXDOUBLENUM*25/100));
- } else UPPER_RANGE = 1;
-
- wholeScript.append(" chart.lines1.forceY(["+(nvl(reportRuntime.getRangeAxisLowerLimit()).length()<=0?"0":reportRuntime.getRangeAxisLowerLimit()) +", "+ (nvl(reportRuntime.getRangeAxisUpperLimit()).length()<=0?UPPER_RANGE:reportRuntime.getRangeAxisUpperLimit()) + "]); \n" +
- " chart.lines2.forceY([0,1]); \n");
- }
- wholeScript.append(" chart.xAxis\n");
- if(reportRuntime.isShowXaxisLabel()) {
- // X axis label is commented for time-being. This should be derived from request parameter.
- //" .axisLabel('" + legendColumnName + "') \n" +
- wholeScript.append(" .axisLabel('" + legendColumnName + "') \n");
- } else {
- wholeScript.append(" .axisLabel('') \n");
- }
- if(reportRuntime.isAddXAxisTickers()) {
- wholeScript.append(" .tickValues(["+ dateStrBuf.toString()+ "])\n ");
- } else {
- //wholeScript.append(" .tickValues([])\n ");
- }
- if(staggerLabels) {
- wholeScript.append(" .staggerLabels(true) \n");
- } else {
- wholeScript.append(" .staggerLabels(false) \n");
- }
- if(showMaxMin) {
- wholeScript.append(" .showMaxMin(true) \n ");
- } else {
- wholeScript.append(" .showMaxMin(false) \n ");
- }
-
- if(nvl(rotateLabels).length()>0) {
- wholeScript.append(" .rotateLabels("+ rotateLabels+ ") \n ");
- } else {
- wholeScript.append(" .rotateLabels(\"0\") \n ");
- }
-
- wholeScript.append(" .tickFormat(function(d) { \n");
- if(formatFlag==DAYFLAG)
- wholeScript.append(" return d3.time.format('%m/%d/%Y')(new Date(d)) }); \n");
- else if(formatFlag==HOURFLAG)
- wholeScript.append(" return d3.time.format('%x %H')(new Date(d)) }); \n");
- else if(formatFlag==MINFLAG)
- wholeScript.append(" return d3.time.format('%x %H:%M')(new Date(d)) }); \n");
- else if(formatFlag==SECFLAG)
- wholeScript.append(" return d3.time.format('%x %X')(new Date(d)) }); \n");
- else if(formatFlag==MONTHFLAG)
- wholeScript.append(" return d3.time.format('%b %y')(new Date(d)) }); \n");
-
- else if(timeAxis)
- wholeScript.append(" return d3.time.format('%x')(new Date(d)) }); \n");
- else
- wholeScript.append(" return d; }); \n");
- if(nvl(chartRightAxisLabel).length() > 0) {
- if(nvl(subType).length() > 0 && subType.equals("area")) {
- wholeScript.append(" chart.yAxis\n");
- } else {
- wholeScript.append(" chart.yAxis1\n");
- }
- wholeScript.append(" .axisLabel('" + chartLeftAxisLabel + "') \n");
- //if(nvl(subType).length() > 0 && subType.equals("area")) {
- if(MAXDOUBLENUM <=5 && MAXNUMDECIMALPLACES == 0 ) MAXNUMDECIMALPLACES = 2;
- if( MAXNUMDECIMALPLACES >=3 ) MAXNUMDECIMALPLACES = 2;
- wholeScript.append(" .tickFormat(d3.format(',."+MAXNUMDECIMALPLACES+"f')); \n");
- /*} else {
- wholeScript.append(" .tickFormat(d3.format(',.2f')); \n");
- }*/
- // " .tickFormat(function (d) {return d;} ); \n");
- //" .tickFormat(function(d) {if (d >= 1000) return Math.round(d/1000)+\"K\"; else return d;}); \n");
- if(!(nvl(subType).length() > 0 && subType.equals("area"))) {
- wholeScript.append(" chart.yAxis2\n " +
- " .axisLabel('" + chartRightAxisLabel + "') \n" +
- " .tickFormat(d3.format(',.02f')); \n");
- //" .tickFormat(function(d) {if (d >= 1000) return Math.round(d/1000)+\"K\"; else return d;}); \n");
- //" .tickFormat(function(d) {if( d <= 1) return Math.round(d*100)+\"%\"; else return d;}); \n");
- // " .tickFormat(function(d) { return d;}); \n");
- }
-
-
- } else {
- if(nvl(subType).length() > 0 && subType.equals("area")) {
- wholeScript.append(" chart.yAxis\n");
- } else {
- wholeScript.append(" chart.yAxis1\n");
- }
- wholeScript.append(" .axisLabel('" + chartLeftAxisLabel + "') \n");
- //if(nvl(subType).length() > 0 && subType.equals("area")) {
- if(MAXDOUBLENUM <=5 && MAXNUMDECIMALPLACES == 0 ) MAXNUMDECIMALPLACES = 2;
- if( MAXNUMDECIMALPLACES >=3 ) {
- MAXNUMDECIMALPLACES = 2;
- }
- wholeScript.append(" .tickFormat(d3.format(',."+MAXNUMDECIMALPLACES+"f')); \n");
- /*} else {
- wholeScript.append(" .tickFormat(d3.format(',.2f')); \n");
- }*/
- //" .tickFormat(function(d) {if (d >= 1000) return Math.round(d/1000)+\"K\"; else return d;}); \n");
- }
- wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n" +
- " .datum(historicalBarChart) \n" );
- if(animation)
- wholeScript.append(" .transition().duration(1000) \n" );
- wholeScript.append(" .call(chart); \n" +
- "nv.utils.windowResize(chart.update); \n" +
- "return chart; \n" +
- "}); \n");
-
- wholeScript.append("function redraw() { \n");
- //wholeScript.append(" nv.utils.windowResize(chart.update); \n");
- wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n") ;
- wholeScript.append(" .datum(historicalBarChart) \n");
- wholeScript.append(" .transition().duration(500) \n");
- wholeScript.append(" .call(chart); \n");
- wholeScript.append("} \n");
- wholeScript.append("\n");
- wholeScript.append(" setInterval(function () { \n");
- wholeScript.append(" redraw(); \n");
- wholeScript.append(" }, 1500) \n");
-
- wholeScript.append("if(historicalBarChart.length <= 0 ) {\n");
- wholeScript.append(" document.getElementById(\"chart"+reportRuntime.getReportID()+"\").innerHTML = \"<div id='noData'><b>No Data Available</b></div>\";\n");
- wholeScript.append(" document.getElementById(\"chart"+reportRuntime.getReportID()+"\").className=\"nodatadiv\";\n");
- wholeScript.append(" document.getElementById(\"nodata\").className=\"nodatainner\";\n");
- wholeScript.append("}\n");
-
- wholeScript.append("</script> </body> </html> \n");
-
- } else if (chartType.equals(AppConstants.GT_PIE) || chartType.equals(AppConstants.GT_PIE_3D)) {
- wholeScript.append("<!DOCTYPE html>\n");
- wholeScript.append("<html>\n");
- wholeScript.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF8\">\n");
- wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n");
- wholeScript.append("<link href=\""+ AppUtils.getBaseFolderURL() +"d3/css/nv.d3.css\" rel=\"stylesheet\" type=\"text/css\">\n");
- wholeScript.append("<style>\n " +
- " body { \n" +
- " overflow-y:scroll; \n" +
- " } \n" +
- " text { \n" +
- " font: 12px sans-serif; \n" +
- " } \n" +
- " tr.z-row-over > td.z-row-inner, tr.z-row-over > .z-cell {" +
- " background-color: rgb(255, 255, 255); "+
- "} "+
- " svg { display: block; } " +
- " #chart"+reportRuntime.getReportID()+" svg { \n" +
- " height: "+ (nvl(height).length()>0?(height.endsWith("px")?height:height+"px"):"420px") + "; \n" +
- " width: "+ (nvl(width).length()>0?(width.endsWith("px")?width:width+"px"):"700px") + "; \n" +
- " min-width: 100px; \n" +
- " min-height: 100px; \n" +
- " } \n" +
- " </style> \n" );
- wholeScript.append("<body> \n");
-
- if(showTitle)
- wholeScript.append("<div align=\"center\"><H3>" + title +"</H3></div>");
-
- wholeScript.append("<div id=\"chart"+reportRuntime.getReportID()+"\"><svg></svg></div>");
- //"<svg id=\"test2\"></svg>\n");
- //js files
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/d3.v3.min.js\"></script>\n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/nv.d3.min.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/legend.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/pie.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/pieChart.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/utils.js\"></script> \n");
- wholeScript.append("<script> \n");
-
- wholeScript.append("historicalBarChart = [ \n");
- double TOTAL = 0;
- double VALUE = 0;
- int flagNull = 0;
- String KEY = "";
- String COLOR = "";
- TreeSet<String> colorList = new TreeSet<String>();
- for (int i = 0; i < ds.getRowCount(); i++) {
- VALUE = 0;
- try {
- VALUE = Double.parseDouble(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<String> 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.lastIndexOf("|")+1)+"',");
- }
- color.deleteCharAt(color.length()-1);
- }
-
- wholeScript.append("];\n");
-
-
- wholeScript.append("var chart; \n");
- wholeScript.append("nv.addGraph(function() { \n" +
- " var width1= 700, height1=720; \n" +
- " chart = nv.models.pieChart() \n" +
- " .margin({top: "+ topMargin +", right: "+ rightMargin +", bottom: "+ bottomMargin +", left: " + leftMargin +"}) \n" +
-
- //" .x(function(d) { return d.key +\" \"+ Math.round(d.y/"+TOTAL+" *100) + \"%\" }) \n" +
- " .x(function(d) { return d.key }) \n" +
- " .y(function(d) { return d.y }) \n");
- if(colorList.size()>0) {
- wholeScript.append(" .color(["+ color.toString() + "] ) \n");
- }
- //wholeScript.append(" .values(function(d) { return d }) \n");
- //" .color(d3.scale.category10().range()); \n" +
- if(showLegend) {
- wholeScript.append(" chart.showLegend(true);\n ");
- } else {
- wholeScript.append(" chart.showLegend(false);\n ");
- }
-
- //wholeScript.append("chart.showLegend(false);\n" +
- //" .width(width1) \n" +
- //" .height(height1); \n" +
- wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n" +
- " .datum(historicalBarChart) \n");
- if(animation)
- wholeScript.append(" .transition().duration(1200) \n" );
-/* " .attr(\"width\", width1) \n" +
- " .attr(\"height\", height1) \n" +
-*/ wholeScript.append(" .call(chart); \n" +
- " nv.utils.windowResize(chart.update);\n"+
- "return chart; \n" +
- "}); \n");
-
- wholeScript.append("function redraw() { \n");
- //wholeScript.append(" nv.utils.windowResize(chart.update); \n");
- wholeScript.append(" d3.select('#chart"+reportRuntime.getReportID()+" svg') \n") ;
- wholeScript.append(" .datum(historicalBarChart) \n");
- wholeScript.append(" .transition().duration(500) \n");
- wholeScript.append(" .call(chart); \n");
- wholeScript.append("} \n");
- wholeScript.append("\n");
- wholeScript.append(" setInterval(function () { \n");
- wholeScript.append(" redraw(); \n");
- wholeScript.append(" }, 1500) \n");
-
-
-
- wholeScript.append("if(historicalBarChart.length <= 0 ) {\n");
- wholeScript.append(" document.getElementById(\"chart"+reportRuntime.getReportID()+"\").innerHTML = \"<div id='noData'><b>No Data Available</b></div>\";\n");
- wholeScript.append(" document.getElementById(\"chart"+reportRuntime.getReportID()+"\").className=\"nodatadiv\";\n");
- wholeScript.append(" document.getElementById(\"nodata\").className=\"nodatainner\";\n");
- wholeScript.append("}\n");
-
- wholeScript.append("</script> </body> </html> \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<String> dateStrList = new TreeSet<String>();
- // added to store all date elements
- SortedSet<String> sortSet = new TreeSet<String>();
- 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<ds.getColumnCount();columnIndex++) {
- columnName = ds.getColumnName(columnIndex);
- if(!timeCharts && !columnName.toLowerCase().equals("anomaly_text")) {
- columnNames.add(columnName);
- columnValues.add(AppUtils.nvls(ds.getString(i, columnIndex), "null"));
- } else if (timeCharts) {
- columnNames.add(columnName);
- columnValues.add(AppUtils.nvls(ds.getString(i, columnIndex), "null"));
- }
- }
-/* actual = ds.getString(i, "actual");
- //forecast = ds.getString(i, "forecast");
- upperBound = ds.getString(i, "upperBound");
- lowerBound = ds.getString(i, "lowerBound");
-
-*/ if(!timeCharts)
- anomalyText = ds.getString(i, "anomaly_text");
- //dataStrBuf.append(" [new Date(moment(\""+dateStr+"\")),"+ actual /*+","+ forecast*/+","+ lowerBound +","+ upperBound +"],\n");
- dataStrBuf.append(" [new Date(moment(\""+dateStr+"\"))");
- for(int c=0; c< columnNames.size(); c++ ) {
- columnName = (String) columnNames.get(c);
- columnValue = (String) columnValues.get(c);
- for (Iterator iter1 = l.iterator(); iter1.hasNext();) {
- dct = (DataColumnType) iter1.next();
- if((dct.getChartSeq()!=null && dct.getChartSeq() >=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("<!DOCTYPE html>\n");
- wholeScript.append("<html>\n");
- wholeScript.append(" <head>\n");
- //wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7; IE=EmulateIE9\">\n");
- wholeScript.append("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n");
- wholeScript.append("<script type=\"text/javascript\" src=\""+ chartScriptsPath +"dy3/js/dygraph-combined.js\"></script>\n");
- wholeScript.append("<script type=\"text/javascript\" src=\""+ chartScriptsPath +"dy3/js/moment.min.js\"></script>\n");
- wholeScript.append("<script type=\"text/javascript\" src=\""+ chartScriptsPath +"dy3/js/interaction.min.js\"></script>\n");
-
- wholeScript.append("<script type=\"text/javascript\">\n");
- if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
- wholeScript.append("var click=2;\n");
- } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
- wholeScript.append("var click=3;\n");
- } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
- wholeScript.append("var click=3;\n");
- } else
- wholeScript.append("var click=3;\n");
- //wholeScript.append(" var click=0;\n");
- wholeScript.append(" function downV3(event, g, context) { \n");
- wholeScript.append(" context.initializeMouseDown(event, g, context); \n");
- wholeScript.append(" if (event.altKey || event.shiftKey) { \n");
- wholeScript.append(" var minDate = g.xAxisRange()[0]; \n");
- wholeScript.append(" var maxDate = g.xAxisRange()[1]; \n");
- if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
- wholeScript.append(" if(((maxDate-minDate)/(1000*60*60*24)) > 6) \n");
- wholeScript.append(" Dygraph.startZoom(event, g, context); \n");
- } else if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
- wholeScript.append(" if(((maxDate-minDate)/(1000*60*60)) > 6) \n");
- wholeScript.append(" Dygraph.startZoom(event, g, context); \n");
- } else if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
- wholeScript.append(" if(((maxDate-minDate)/(1000*60*60*2)) > 6) \n");
- wholeScript.append(" Dygraph.startZoom(event, g, context); \n");
-
- } else {
- wholeScript.append(" if(((maxDate-minDate)/(1000*60*60)) > 6) \n");
- wholeScript.append(" Dygraph.startZoom(event, g, context); \n");
- }
- if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
- wholeScript.append(" click=2;\n");
- } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
- wholeScript.append(" click=3;\n");
- } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
- wholeScript.append(" click=3;\n");
- } else
- wholeScript.append(" click=3;\n");
- wholeScript.append(" } else if (event.ctrlKey) {\n");
-
-
- wholeScript.append(" click++;\n");
- wholeScript.append(" if(click == 1)\n");
- wholeScript.append(" zoom_custom(3600);\n");
- wholeScript.append(" else if(click == 2)\n");
- wholeScript.append(" zoom_custom(12*3600);\n");
- wholeScript.append(" else if(click == 3)\n");
- wholeScript.append(" zoom_custom(86400);\n");
- wholeScript.append(" else if (click == 4)\n");
- wholeScript.append(" zoom_custom(7*86400);\n");
- wholeScript.append(" else if (click == 5)\n");
- wholeScript.append(" zoom_custom(30*86400);\n");
- wholeScript.append(" else if (click == 6)\n");
- wholeScript.append(" zoom_custom(90*86400);\n");
- wholeScript.append(" else if (click == 7)\n");
- wholeScript.append(" zoom_custom(180*86400);\n");
- wholeScript.append(" else if (click == 8)\n");
- wholeScript.append(" zoom_custom(365*86400);\n");
- wholeScript.append(" else if (click == 10)\n");
- wholeScript.append(" zoom_custom(5*365*86400);\n");
- wholeScript.append(" else { \n");
- wholeScript.append(" reset();\n");
- wholeScript.append(" }\n");
- //wholeScript.append(" \n");
- wholeScript.append(" } else {\n");
- wholeScript.append(" Dygraph.startPan(event, g, context); \n");
- wholeScript.append(" } \n");
- wholeScript.append(" } \n");
- wholeScript.append("</script>\n ");
- wholeScript.append("<style type=\"text/css\">\n");
- wholeScript.append(".annotation {\n");
- wholeScript.append("}");
- wholeScript.append(".dygraph-title {\n");
- wholeScript.append("color: black;\n");
- wholeScript.append("font-weight:bold; \n");
- wholeScript.append("}\n");
- wholeScript.append(".dygraph-axis-label-x { ");
- wholeScript.append("-webkit-transform:rotate(-0deg);");
- wholeScript.append("display:block;");
- /*position:absolute;
- right:-5px;
- top:15px;*/
- wholeScript.append("}\n");
-
- int widthInt = 0;
- if(nvl(width).length() > 0) {
- try {
- widthInt = new Integer(width).intValue();
- } catch(Exception ex) {
- if(width.endsWith("px")) {
- try {
- widthInt = new Integer(width.substring(0, width.indexOf("px")));
- } catch (Exception ex1) {
- widthInt = 700;
- }
- } else {
- widthInt = 700;
- }
- }
- } else widthInt = 700;
-
- wholeScript.append(".dygraph-legend {\n");
- wholeScript.append(" left: "+(widthInt-200)+"px !important;\n");
- wholeScript.append(" top: 5px !important;\n");
- wholeScript.append("}\n");
-
- wholeScript.append(".nodatadiv {\n");
- wholeScript.append(" display: table-cell;\n");
- wholeScript.append(" width: 700px;\n");
- wholeScript.append(" height:370px;\n");
- wholeScript.append(" text-align:center;\n");
- wholeScript.append(" vertical-align: middle;\n");
- wholeScript.append("}\n");
- wholeScript.append(".nodatainner {\n");
- wholeScript.append(" padding: 10px;\n");
- wholeScript.append("}\n");
-
- wholeScript.append("canvas {\n");
- wholeScript.append(" -webkit-touch-callout: none; \n");
- wholeScript.append(" -webkit-user-select: none;\n");
- wholeScript.append(" -khtml-user-select: none;\n");
- wholeScript.append(" -moz-user-select: none;\n");
- wholeScript.append(" user-select: none;\n");
- wholeScript.append(" user-select: none;\n");
- wholeScript.append(" outline: none;\n");
- wholeScript.append(" -webkit-tap-highlight-color: rgba(255, 255, 255, 0); /* mobile webkit */\n");
- wholeScript.append("}\n");
- wholeScript.append("</style>\n");
- wholeScript.append("</head>\n");
- wholeScript.append("<body> \n");
-
-/* if(showTitle)
- wholeScript.append(" <p align=\"center\"><b> " + (AppUtils.nvl(reportRuntime.getReportTitle()).length()>0?reportRuntime.getReportTitle():reportRuntime.getReportName()) + "</b></p>\n");
-*/
- wholeScript.append(" <table>\n");
- if(showTitle) {
- wholeScript.append(" <tr> \n ");
- wholeScript.append(" <td> \n ");
- wholeScript.append(" <div class=\"dygraph-label dygraph-title\" align=\"center\">"+title+"</div> \n");
- wholeScript.append(" </td> \n ");
- }
-
- wholeScript.append(" </tr> \n ");
-
- wholeScript.append(" <tr> \n ");
- wholeScript.append(" <td> \n ");
- if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()<=0 || reportRuntime.getLegendPosition().equals("top")) {
- wholeScript.append(" <div id=\"labelDiv"+reportRuntime.getReportID()+"\"></div>\n");
- }
- wholeScript.append(" <div id=\"message"+reportRuntime.getReportID()+"\"></div> \n");
- wholeScript.append(" </td> \n ");
-
- wholeScript.append(" </tr> \n ");
- wholeScript.append(" <tr>\n");
- wholeScript.append(" <td>\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(" <div id=\"div_g"+reportRuntime.getReportID()+"\" style=\"width:"+ (widthInt-250)+ "px; \n" );
- } else {
- wholeScript.append(" <div id=\"div_g"+reportRuntime.getReportID()+"\" style=\"width:"+ (widthInt)+ "px; \n" );
- }
- wholeScript.append(" height:"+ heightInt +"px;\"></div> \n");
- wholeScript.append(" </td>\n");
- if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
- wholeScript.append(" <td valign=\"top\">\n");
- wholeScript.append(" <div id=\"labelDiv3716\" valign=\"top\" style=\"width:250px;height:"+ heightInt +"px;\"></div>\n");
- wholeScript.append(" </td>\n");
- }
- wholeScript.append(" </tr>\n");
- if(anomalyRec > 0) {
- wholeScript.append(" <tr>\n");
- wholeScript.append(" <td>\n");
- wholeScript.append(" <table>\n");
- wholeScript.append(" <tr>\n");
- wholeScript.append(" <td align=\"center\"><font size=\"2px\"><B><align=\"center\">Anomaly Description</align></B></font></td>\n");
- wholeScript.append(" </tr>\n");
- wholeScript.append(" <tr>\n");
- wholeScript.append(" <td><div id=\"list"+reportRuntime.getReportID()+"\" style=\"width:" + widthInt + "px; height:50px;\"></div></td>\n" );
- wholeScript.append(" </tr>\n");
- wholeScript.append(" </table>\n");
- wholeScript.append(" </td>\n");
- wholeScript.append(" </tr>\n");
- }
- wholeScript.append(" </table>\n");
-
- wholeScript.append(" <script type=\"text/javascript\">\n");
- wholeScript.append(" Dygraph.addEvent(document, \"mousewheel\", function() { lastClickedGraph = null; });\n");
- wholeScript.append(" Dygraph.addEvent(document, \"click\", function() { lastClickedGraph = null; });\n");
- wholeScript.append(" var data = []; \n");
- wholeScript.append(" data = [\n ");
- wholeScript.append( dataStrBuf.toString());
- wholeScript.append(" ];\n");
- wholeScript.append(" if(data.length > 0 ) { \n");
- wholeScript.append(" var orig_range = [ data[0][0].valueOf(), data[data.length - 1][0].valueOf() ];\n");
- if(!timeCharts) {
- wholeScript.append(" function nameAnnotation(ann) { \n");
- wholeScript.append(" return ann.shortText; \n");
- //wholeScript.append(" var m = moment(ann.x);\n");
- //wholeScript.append(" return \"(\" + ann.series + \", \" + m.format(\"YYYY-MM-DD HH\"); + \")\"; \n");
- wholeScript.append(" }\n");
- wholeScript.append(" anns = [];\n");
- }
- wholeScript.append(" var graph_initialized = false;\n");
- wholeScript.append(" if(navigator.platform == 'iPad') { ");
- wholeScript.append(" g = new Dygraph(\n");
- wholeScript.append(" document.getElementById(\"div_g"+reportRuntime.getReportID()+"\"),\n");
- //data here
- /*wholeScript.append(" [\n");
- wholeScript.append(dataStrBuf.toString());
- wholeScript.append(" ],\n");*/
- wholeScript.append(" data , \n");
- wholeScript.append(" {\n");
-
- //Labels here
-
- dct = null;
- StringBuffer labelStrBuf = new StringBuffer("");
- StringBuffer colorsStrBuf = new StringBuffer("");
- StringBuffer visibilityStrBuf = new StringBuffer("");
- int countChartValues = 0;
- 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().equals("anomaly_text")) {
- countChartValues++;
- labelStrBuf.append("'"+ dct.getDisplayName()+"',");
- if(!AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))
- colorsStrBuf.append("'"+ AppUtils.nvl(dct.getChartColor())+"',");
- visibilityStrBuf.append("true,");
- }
- }
- }
- if(labelStrBuf.indexOf(",")!=-1) {
- labelStrBuf.deleteCharAt(labelStrBuf.lastIndexOf(","));
- visibilityStrBuf.deleteCharAt(visibilityStrBuf.lastIndexOf(","));
- }
- if(colorsStrBuf.indexOf(",")!=-1)
- colorsStrBuf.deleteCharAt(colorsStrBuf.lastIndexOf(","));
- //if(showTitle)
- //wholeScript.append("title: '" + (AppUtils.nvl(reportRuntime.getReportTitle()).length()>0?reportRuntime.getReportTitle():reportRuntime.getReportName()) + "',\n");
- wholeScript.append("maxNumberWidth:6,\n");
- wholeScript.append("xAxisHeight: 70,\n");
- wholeScript.append("yAxisLabelWidth: 70,\n");
- wholeScript.append("xAxisLabelWidth: 45,\n");
- wholeScript.append("axes: {\n");
- wholeScript.append("x: {\n");
- wholeScript.append(" axisLabelFormatter: function(d, gran) {\n");
- wholeScript.append(" var month = d.getMonth()+1;\n");
- wholeScript.append(" var day = d.getDate();\n");
- wholeScript.append(" var year = d.getFullYear();\n");
- wholeScript.append(" var hour = d.getHours();\n");
- wholeScript.append(" var minutes = d.getMinutes();\n");
- wholeScript.append(" var seconds = d.getSeconds();\n");
- wholeScript.append(" var wholeString = Dygraph.zeropad(month)+'/'+Dygraph.zeropad(day);\n");
- // wholeScript.append(" if(hour >= 0 && minutes > 0 && seconds > 0) {\n");
- //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n");
- //wholeScript.append(" } else if (hour >= 0 && minutes > 0 && seconds == 0) {\n");
- if(AppUtils.nvl(reportRuntime.getTimeAxisType()).length()==0 || AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly"))
- wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes);\n");
- //wholeScript.append(" } else if (hour >= 0 && (minutes >= 0 && seconds > 0)) {\n");
- //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n");
- //wholeScript.append(" } else if (hour >= 0) { \n");
- //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour); \n");
- //wholeScript.append(" } \n");
- wholeScript.append(" return wholeString; \n");
- wholeScript.append(" },\n");
- wholeScript.append(" ticker: function (a, b, pixels, opts, dygraph, vals) { \n ");
- wholeScript.append(" if(((b-a)/(1000*60*60)) <= 6) { \n");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.THIRTY_MINUTELY, opts, dygraph); \n");
- wholeScript.append(" } else if(((b-a)/(1000*60*60)) <= 12) { \n");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.HOURLY, opts, dygraph); \n");
- wholeScript.append(" } else if (((b-a)/(1000*60*60)) <= 25) \n ");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.TWO_HOURLY, opts, dygraph); \n ");
- wholeScript.append(" else if(((b-a)/(1000*60*60)) <= 78) \n ");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.SIX_HOURLY, opts, dygraph); \n ");
- wholeScript.append(" else if(((b-a)/(1000*60*60*24)) <= 12)\n");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.DAILY, opts, dygraph); \n");
- wholeScript.append(" else if(((b-a)/(1000*60*60*24)) <= 90) \n");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.WEEKLY, opts, dygraph); \n");
- wholeScript.append(" else \n");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.MONTHLY, opts, dygraph); \n");
- wholeScript.append(" }, \n");
- wholeScript.append(" valueFormatter: function(ms) { \n");
- wholeScript.append(" return new Date(ms).strftime(\"%m/%d/%Y %H:%M\"); \n");
- wholeScript.append( " }\n" );
- wholeScript.append(" }\n");
- wholeScript.append("},\n");
- wholeScript.append(" interactionModel : { \n");
- wholeScript.append(" 'mousedown' : downV4,\n");
- wholeScript.append(" touchstart : newDygraphTouchstart,\n");
- wholeScript.append(" touchend : Dygraph.defaultInteractionModel.touchend,\n");
- wholeScript.append(" touchmove : Dygraph.defaultInteractionModel.touchmove\n");
- //wholeScript.append(" 'dblclick' : dblClickV3,\n");
- //wholeScript.append(" 'mousewheel' : scrollV3\n");
-
- /*wholeScript.append(" 'mousedown' : downV3,\n");
- wholeScript.append(" 'mousemove' : moveV3,\n");
- wholeScript.append(" 'mouseup' : upV3,\n");
- wholeScript.append(" 'click' : clickV3,\n");
- wholeScript.append(" 'dblclick' : dblClickV3,\n");
- wholeScript.append(" 'mousewheel' : scrollV3\n");*/
- wholeScript.append("},\n");
- /*wholeScript.append(" zoomCallback: function(minDate, maxDate, yRanges) { \n");
- if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
- wholeScript.append(" if(((maxDate-minDate)/(1000*60*60*24)) < 6) { \n");
- wholeScript.append(" maxDate = new Date(minDate).setMinutes(6*24*60);\n");
- wholeScript.append(" g.updateOptions({\n");
- wholeScript.append(" interactionModel: {},\n");
- wholeScript.append(" dateWindow: [minDate, maxDate]\n");
- wholeScript.append(" });\n");
- } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
- wholeScript.append(" if(((maxDate-minDate)/(1000*60*60)) <= 6) { \n");
- wholeScript.append(" maxDate = new Date(minDate).setMinutes(360);\n");
- wholeScript.append(" g.updateOptions({\n");
- wholeScript.append(" interactionModel: {},\n");
- wholeScript.append(" dateWindow: [minDate, maxDate]\n");
- wholeScript.append(" });\n");
- } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
- wholeScript.append(" if(((maxDate-minDate)/(1000*60*60)) <= 3) { \n");
- wholeScript.append(" maxDate = new Date(minDate).setMinutes(180);\n");
- wholeScript.append(" g.updateOptions({\n");
- wholeScript.append(" interactionModel: {},\n");
- wholeScript.append(" dateWindow: [minDate, maxDate]\n");
- wholeScript.append(" });\n");
- } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("weekly")) {
- wholeScript.append(" if(((maxDate-minDate)/(1000*60*60*24)) < 7) { \n");
- wholeScript.append(" maxDate = new Date(minDate).setMinutes(7*24*60);\n");
- wholeScript.append(" g.updateOptions({\n");
- wholeScript.append(" interactionModel: {},\n");
- wholeScript.append(" dateWindow: [minDate, maxDate]\n");
- wholeScript.append(" });\n");
- }
- wholeScript.append(" } else {\n");
- wholeScript.append(" g.updateOptions({\n");
- wholeScript.append(" interactionModel : {\n");
- wholeScript.append(" 'mousedown' : downV3,\n");
- wholeScript.append(" 'mousemove' : moveV3,\n");
- wholeScript.append(" 'mouseup' : upV3,\n");
- wholeScript.append(" 'click' : clickV3,\n");
- wholeScript.append(" 'dblclick' : dblClickV3,\n");
- wholeScript.append(" 'mousewheel' : scrollV3\n");
- wholeScript.append(" }\n");
- wholeScript.append(" });\n");
- wholeScript.append(" } \n");
- wholeScript.append(" } ,\n");*/
- wholeScript.append("dateWindow: ["+minDate+", "+maxDate+"],\n");
- wholeScript.append("labels: ["+ labelStrBuf +"],\n");
- wholeScript.append("labelsDiv: \"labelDiv"+reportRuntime.getReportID()+"\",\n");
- wholeScript.append("labelsShowZeroValues: true,\n");
- if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
- wholeScript.append("labelsSeparateLines: true,\n");
- }
- wholeScript.append("labelsDivWidth: 200,\n");
-
- wholeScript.append("animatedZooms: true,\n");
- wholeScript.append("strokeWidth: 3.0,\n");
- wholeScript.append("strokeBorderWidth: 2.0,\n");
- /*wholeScript.append(" labelsDivStyles: { \n");
- wholeScript.append(" 'backgroundColor': 'rgba(200, 200, 255, 0.75)',\n");
- wholeScript.append(" 'padding': '4px',\n");
- wholeScript.append(" 'border': '1px solid black',\n");
- wholeScript.append(" 'borderRadius': '10px',\n");
- wholeScript.append(" 'boxShadow': '4px 4px 4px #888',\n");
- wholeScript.append(" 'width': '50px'\n");
- wholeScript.append("}, \n");
- */
- wholeScript.append("visibility: ["+ visibilityStrBuf +"],\n");
- if(colorsStrBuf.length() > 0 && colorsStrBuf.length()>=(countChartValues*3+5))
- wholeScript.append("colors: ["+ colorsStrBuf +"],\n");
-
- wholeScript.append(" legend: 'always', \n");
- //Yaxis label here
- wholeScript.append(" ylabel: '"+ chartLeftAxisLabel +"' , \n");
-
- //Xaxis label here
- wholeScript.append(" xlabel: '"+ xAxisLabel +"' , \n");
-
- //draw points
- wholeScript.append(" drawPoints: true, \n");
-
- //stacked graph
- wholeScript.append(" stackedGraph: false, \n");
-
- dct = null;
- for (Iterator iter = l.iterator(); iter.hasNext();) {
- dct = (DataColumnType) iter.next();
- if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) {
- if(!AppUtils.nvl(dct.getDisplayName()).toLowerCase().equals("anomaly_text")) {
- if(dct.getChartSeq()!=null && dct.getChartSeq() >=0) {
- wholeScript.append(" '"+ dct.getDisplayName() + "': {\n");
- if(AppUtils.nvl(dct.getChartLineType()).length()>0)
- wholeScript.append(" strokePattern: Dygraph.DASHED_LINE,\n");
- if(dct.isIsRangeAxisFilled()!=null && dct.isIsRangeAxisFilled().booleanValue()) {
- wholeScript.append(" fillGraph: true\n");
- }
- wholeScript.append(" },\n");
- }
- }
- }
- }
-
-/* //each labels
- wholeScript.append(" 'Forecast': {\n");
-
- //if dashed line
- wholeScript.append(" strokePattern: Dygraph.DASHED_LINE,\n");
-
- //if fillable
- wholeScript.append(" fillGraph: true\n");
-
- // close each labels
- wholeScript.append(" }\n");
-*/
- // callback method
- if(anomalyRec > 0) {
- wholeScript.append(" drawCallback: function(g, is_initial) { \n");
- wholeScript.append(" if (is_initial) { \n");
- wholeScript.append(" graph_initialized = true; \n");
- wholeScript.append(" if (anns.length > 0) { \n");
- wholeScript.append(" g.setAnnotations(anns); \n");
- wholeScript.append(" }\n");
- wholeScript.append(" }\n");
-
- wholeScript.append(" var anns1 = g.annotations();\n");
- //wholeScript.append(" var html = \"\";\n");
- wholeScript.append(" var html = \"<select id='x' size='1' style='width: "+ widthInt +"px; font-family : courier; font-size:8pt; font-weight:bold;'>\";\n");
- wholeScript.append(" for (var i = anns1.length-1; i >= 0 ; i--) {\n");
- wholeScript.append(" var name = nameAnnotation(anns1[i]);\n");
- //wholeScript.append(" html += \"<span id='\" + name + \"'>\"\n");
- wholeScript.append(" if(i==anns1.length-1)\n");
- wholeScript.append(" html += \"<option value='\" + name + \"' selected ><font size=1>\" \n");
- wholeScript.append(" else \n");
- wholeScript.append(" html += \"<option value='\" + name + \"'><font size=1>\" \n");
- wholeScript.append(" html += name \n");
- //wholeScript.append(" html += name + \": \" + (anns1[i].shortText || '(icon)')\n");
- //wholeScript.append(" html += \" -> \" + anns1[i].text + \"</span><br/>\";\n");
- wholeScript.append(" html += \" : \" + anns1[i].text + \"</font></option>\";\n");
- wholeScript.append(" }\n");
- wholeScript.append(" html += \"</select>\" \n");
- wholeScript.append(" document.getElementById(\"list"+reportRuntime.getReportID()+"\").innerHTML = html;\n");
- wholeScript.append(" }\n");
-
-
- wholeScript.append(" }\n");
- wholeScript.append(" )\n");
-
- //push annotations
- wholeScript.append(annotationsStrBuf.toString());
-
- wholeScript.append(" if (graph_initialized) {\n");
- wholeScript.append(" g.setAnnotations(anns);\n");
- wholeScript.append(" } \n");
- //upate handler script
-
- wholeScript.append(" var saveBg = '';\n");
- wholeScript.append(" var num = 0;\n");
- wholeScript.append(" g.updateOptions( {\n");
- wholeScript.append(" annotationMouseOverHandler: function(ann) { \n");
- //wholeScript.append(" document.getElementById(nameAnnotation(ann)).style.fontWeight = 'bold';\n");
- //wholeScript.append(" saveBg = ann.div.style.backgroundColor;\n");
- //wholeScript.append(" ann.div.style.backgroundColor = '#ddd';\n");
- wholeScript.append(" var selectobject = document.getElementById(\"x\");\n");
- wholeScript.append(" for(var i=0; i<selectobject.length;i++) {\n ");
- wholeScript.append(" if(selectobject.options[i].value == nameAnnotation(ann)) {\n ");
- wholeScript.append(" selectobject.options[i].selected = true; \n ");
- wholeScript.append(" } ");
- wholeScript.append(" } ");
-
- wholeScript.append(" },\n");
- wholeScript.append(" annotationMouseOutHandler: function(ann) {\n");
- wholeScript.append(" document.getElementById(nameAnnotation(ann)).style.fontWeight = 'normal';\n");
- wholeScript.append(" ann.div.style.backgroundColor = saveBg;\n");
- //wholeScript.append(" var selectobject = document.getElementById(\"x\");\n");
- //wholeScript.append(" for(var i=0; i<selectobject.length;i++) {\n ");
- //wholeScript.append(" if(selectobject.options[i].value == nameAnnotation(ann)) {\n ");
- //wholeScript.append(" selectobject.options[i].selected = false; \n ");
- //wholeScript.append(" } ");
- //wholeScript.append(" } ");
-
- wholeScript.append(" }\n");
- }
- wholeScript.append(" });\n");
-
- //Other devices
- wholeScript.append("} else { \n");
-
- wholeScript.append(" g = new Dygraph(\n");
- wholeScript.append(" document.getElementById(\"div_g"+reportRuntime.getReportID()+"\"),\n");
- //data here
- /*wholeScript.append(" [\n");
- wholeScript.append(dataStrBuf.toString());
- wholeScript.append(" ],\n");*/
- wholeScript.append(" data , \n");
- wholeScript.append(" {\n");
-
- //Labels here
-
- dct = null;
- labelStrBuf = new StringBuffer("");
- colorsStrBuf = new StringBuffer("");
- visibilityStrBuf = new StringBuffer("");
- countChartValues = 0;
- 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().equals("anomaly_text")) {
- countChartValues++;
- labelStrBuf.append("'"+ dct.getDisplayName()+"',");
- if(!AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))
- colorsStrBuf.append("'"+ AppUtils.nvl(dct.getChartColor())+"',");
- visibilityStrBuf.append("true,");
- }
- }
- }
- if(labelStrBuf.indexOf(",")!=-1) {
- labelStrBuf.deleteCharAt(labelStrBuf.lastIndexOf(","));
- visibilityStrBuf.deleteCharAt(visibilityStrBuf.lastIndexOf(","));
- }
- if(colorsStrBuf.indexOf(",")!=-1)
- colorsStrBuf.deleteCharAt(colorsStrBuf.lastIndexOf(","));
- //if(showTitle)
- //wholeScript.append("title: '" + (AppUtils.nvl(reportRuntime.getReportTitle()).length()>0?reportRuntime.getReportTitle():reportRuntime.getReportName()) + "',\n");
- wholeScript.append("maxNumberWidth:6,\n");
- wholeScript.append("xAxisHeight: 70,\n");
- wholeScript.append("yAxisLabelWidth: 70,\n");
- wholeScript.append("xAxisLabelWidth: 45,\n");
- wholeScript.append("axes: {\n");
- wholeScript.append("x: {\n");
- wholeScript.append(" axisLabelFormatter: function(d, gran) {\n");
- wholeScript.append(" var month = d.getMonth()+1;\n");
- wholeScript.append(" var day = d.getDate();\n");
- wholeScript.append(" var year = d.getFullYear();\n");
- wholeScript.append(" var hour = d.getHours();\n");
- wholeScript.append(" var minutes = d.getMinutes();\n");
- wholeScript.append(" var seconds = d.getSeconds();\n");
- wholeScript.append(" var wholeString = Dygraph.zeropad(month)+'/'+Dygraph.zeropad(day);\n");
- // wholeScript.append(" if(hour >= 0 && minutes > 0 && seconds > 0) {\n");
- //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n");
- //wholeScript.append(" } else if (hour >= 0 && minutes > 0 && seconds == 0) {\n");
- if(AppUtils.nvl(reportRuntime.getTimeAxisType()).length()==0 || AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly"))
- wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes);\n");
- //wholeScript.append(" } else if (hour >= 0 && (minutes >= 0 && seconds > 0)) {\n");
- //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour) + ':'+Dygraph.zeropad(minutes)+':'+Dygraph.zeropad(seconds);\n");
- //wholeScript.append(" } else if (hour >= 0) { \n");
- //wholeScript.append(" wholeString += ' ' + Dygraph.zeropad(hour); \n");
- //wholeScript.append(" } \n");
- wholeScript.append(" return wholeString; \n");
- wholeScript.append(" },\n");
- wholeScript.append(" ticker: function (a, b, pixels, opts, dygraph, vals) { \n ");
- wholeScript.append(" if(((b-a)/(1000*60*60)) <= 6) { \n");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.THIRTY_MINUTELY, opts, dygraph); \n");
- wholeScript.append(" } else if(((b-a)/(1000*60*60)) <= 12) { \n");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.HOURLY, opts, dygraph); \n");
- wholeScript.append(" } else if (((b-a)/(1000*60*60)) <= 25) \n ");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.TWO_HOURLY, opts, dygraph); \n ");
- wholeScript.append(" else if(((b-a)/(1000*60*60)) <= 78) \n ");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.SIX_HOURLY, opts, dygraph); \n ");
- wholeScript.append(" else if(((b-a)/(1000*60*60*24)) <= 12)\n");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.DAILY, opts, dygraph); \n");
- wholeScript.append(" else if(((b-a)/(1000*60*60*24)) <= 90) \n");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.WEEKLY, opts, dygraph); \n");
- wholeScript.append(" else \n");
- wholeScript.append(" return Dygraph.getDateAxis(a, b, Dygraph.MONTHLY, opts, dygraph); \n");
- wholeScript.append(" }, \n");
- wholeScript.append(" valueFormatter: function(ms) { \n");
- wholeScript.append(" return new Date(ms).strftime(\"%m/%d/%Y %H:%M\"); \n");
- wholeScript.append( " }\n" );
- wholeScript.append(" }\n");
- wholeScript.append("},\n");
- wholeScript.append(" interactionModel : { \n");
-
- wholeScript.append(" 'mousedown' : downV3,\n");
- wholeScript.append(" 'mousemove' : moveV3,\n");
- wholeScript.append(" 'mouseup' : upV3,\n");
- wholeScript.append(" 'click' : clickV3,\n");
- wholeScript.append(" 'dblclick' : dblClickV3,\n");
- wholeScript.append(" 'mousewheel' : scrollV3\n");
- wholeScript.append("},\n");
- wholeScript.append(" zoomCallback: function(minDate, maxDate, yRanges) { \n");
- if(AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("daily")) {
- wholeScript.append(" if(((maxDate-minDate)/(1000*60*60*24)) < 6) { \n");
- wholeScript.append(" maxDate = new Date(minDate).setMinutes(6*24*60);\n");
- wholeScript.append(" g.updateOptions({\n");
- wholeScript.append(" interactionModel: {},\n");
- wholeScript.append(" dateWindow: [minDate, maxDate]\n");
- wholeScript.append(" });\n");
- } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("hourly")) {
- wholeScript.append(" if(((maxDate-minDate)/(1000*60*60)) <= 6) { \n");
- wholeScript.append(" maxDate = new Date(minDate).setMinutes(360);\n");
- wholeScript.append(" g.updateOptions({\n");
- wholeScript.append(" interactionModel: {},\n");
- wholeScript.append(" dateWindow: [minDate, maxDate]\n");
- wholeScript.append(" });\n");
- } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("30min")) {
- wholeScript.append(" if(((maxDate-minDate)/(1000*60*60)) <= 3) { \n");
- wholeScript.append(" maxDate = new Date(minDate).setMinutes(180);\n");
- wholeScript.append(" g.updateOptions({\n");
- wholeScript.append(" interactionModel: {},\n");
- wholeScript.append(" dateWindow: [minDate, maxDate]\n");
- wholeScript.append(" });\n");
- } else if (AppUtils.nvl(reportRuntime.getTimeAxisType()).equals("weekly")) {
- wholeScript.append(" if(((maxDate-minDate)/(1000*60*60*24)) < 7) { \n");
- wholeScript.append(" maxDate = new Date(minDate).setMinutes(7*24*60);\n");
- wholeScript.append(" g.updateOptions({\n");
- wholeScript.append(" interactionModel: {},\n");
- wholeScript.append(" dateWindow: [minDate, maxDate]\n");
- wholeScript.append(" });\n");
- }
- wholeScript.append(" } else {\n");
- wholeScript.append(" g.updateOptions({\n");
- wholeScript.append(" interactionModel : {\n");
- wholeScript.append(" 'mousedown' : downV3,\n");
- wholeScript.append(" 'mousemove' : moveV3,\n");
- wholeScript.append(" 'mouseup' : upV3,\n");
- wholeScript.append(" 'click' : clickV3,\n");
- wholeScript.append(" 'dblclick' : dblClickV3,\n");
- wholeScript.append(" 'mousewheel' : scrollV3\n");
- wholeScript.append(" }\n");
- wholeScript.append(" });\n");
- wholeScript.append(" } \n");
- wholeScript.append(" } ,\n");
- wholeScript.append("dateWindow: ["+minDate+", "+maxDate+"],\n");
- wholeScript.append("labels: ["+ labelStrBuf +"],\n");
- wholeScript.append("labelsDiv: \"labelDiv"+reportRuntime.getReportID()+"\",\n");
- wholeScript.append("labelsShowZeroValues: true,\n");
- if(AppUtils.nvl(reportRuntime.getLegendPosition()).length()>=0 && reportRuntime.getLegendPosition().equals("right")) {
- wholeScript.append("labelsSeparateLines: true,\n");
- }
- wholeScript.append("labelsDivWidth: 200,\n");
-
-
- wholeScript.append("animatedZooms: true,\n");
- wholeScript.append("strokeWidth: 3.0,\n");
- wholeScript.append("strokeBorderWidth: 2.0,\n");
-
- /*wholeScript.append(" labelsDivStyles: { \n");
- wholeScript.append(" 'backgroundColor': 'rgba(200, 200, 255, 0.75)',\n");
- wholeScript.append(" 'padding': '4px',\n");
- wholeScript.append(" 'border': '1px solid black',\n");
- wholeScript.append(" 'borderRadius': '10px',\n");
- wholeScript.append(" 'boxShadow': '4px 4px 4px #888',\n");
- wholeScript.append(" 'width': '50px'\n");
- wholeScript.append("}, \n");
- */
- wholeScript.append("visibility: ["+ visibilityStrBuf +"],\n");
- if(colorsStrBuf.length() > 0 && colorsStrBuf.length()>=(countChartValues*3+5))
- wholeScript.append("colors: ["+ colorsStrBuf +"],\n");
-
- wholeScript.append(" legend: 'always', \n");
- //Yaxis label here
- wholeScript.append(" ylabel: '"+ chartLeftAxisLabel +"' , \n");
-
- //Xaxis label here
- wholeScript.append(" xlabel: '"+ xAxisLabel +"' , \n");
-
-
- //draw points
- wholeScript.append(" drawPoints: true, \n");
-
- //stacked graph
- wholeScript.append(" stackedGraph: false, \n");
-
- dct = null;
- for (Iterator iter = l.iterator(); iter.hasNext();) {
- dct = (DataColumnType) iter.next();
- if(!(nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND))) {
- if(!AppUtils.nvl(dct.getDisplayName()).toLowerCase().equals("anomaly_text")) {
- if(dct.getChartSeq()!=null && dct.getChartSeq() >=0) {
- wholeScript.append(" '"+ dct.getDisplayName() + "': {\n");
- if(AppUtils.nvl(dct.getChartLineType()).length()>0)
- wholeScript.append(" strokePattern: Dygraph.DASHED_LINE,\n");
- if(dct.isIsRangeAxisFilled()!=null && dct.isIsRangeAxisFilled().booleanValue()) {
- wholeScript.append(" fillGraph: true\n");
- }
- wholeScript.append(" },\n");
- }
- }
- }
- }
-
-/* //each labels
- wholeScript.append(" 'Forecast': {\n");
-
- //if dashed line
- wholeScript.append(" strokePattern: Dygraph.DASHED_LINE,\n");
-
- //if fillable
- wholeScript.append(" fillGraph: true\n");
-
- // close each labels
- wholeScript.append(" }\n");
-*/
- // callback method
- if(anomalyRec > 0) {
- wholeScript.append(" drawCallback: function(g, is_initial) { \n");
- wholeScript.append(" if (is_initial) { \n");
- wholeScript.append(" graph_initialized = true; \n");
- wholeScript.append(" if (anns.length > 0) { \n");
- wholeScript.append(" g.setAnnotations(anns); \n");
- wholeScript.append(" }\n");
- wholeScript.append(" }\n");
-
- wholeScript.append(" var anns1 = g.annotations();\n");
- //wholeScript.append(" var html = \"\";\n");
- wholeScript.append(" var html = \"<select id='x' size='1' style='width: "+ widthInt +"px; font-family : courier; font-size:8pt; font-weight:bold;'>\";\n");
- wholeScript.append(" for (var i = anns1.length-1; i >= 0 ; i--) {\n");
- wholeScript.append(" var name = nameAnnotation(anns1[i]);\n");
- //wholeScript.append(" html += \"<span id='\" + name + \"'>\"\n");
- wholeScript.append(" if(i==anns1.length-1)\n");
- wholeScript.append(" html += \"<option value='\" + name + \"' selected ><font size=1>\" \n");
- wholeScript.append(" else \n");
- wholeScript.append(" html += \"<option value='\" + name + \"'><font size=1>\" \n");
- wholeScript.append(" html += name \n");
- //wholeScript.append(" html += name + \": \" + (anns1[i].shortText || '(icon)')\n");
- //wholeScript.append(" html += \" -> \" + anns1[i].text + \"</span><br/>\";\n");
- wholeScript.append(" html += \" : \" + anns1[i].text + \"</font></option>\";\n");
- wholeScript.append(" }\n");
- wholeScript.append(" html += \"</select>\" \n");
- wholeScript.append(" document.getElementById(\"list"+reportRuntime.getReportID()+"\").innerHTML = html;\n");
- wholeScript.append(" }\n");
-
-
- wholeScript.append(" }\n");
- wholeScript.append(" )\n");
-
- //push annotations
- wholeScript.append(annotationsStrBuf.toString());
-
- wholeScript.append(" if (graph_initialized) {\n");
- wholeScript.append(" g.setAnnotations(anns);\n");
- wholeScript.append(" } \n");
- //upate handler script
-
- wholeScript.append(" var saveBg = '';\n");
- wholeScript.append(" var num = 0;\n");
- wholeScript.append(" g.updateOptions( {\n");
- wholeScript.append(" annotationMouseOverHandler: function(ann) { \n");
- //wholeScript.append(" document.getElementById(nameAnnotation(ann)).style.fontWeight = 'bold';\n");
- //wholeScript.append(" saveBg = ann.div.style.backgroundColor;\n");
- //wholeScript.append(" ann.div.style.backgroundColor = '#ddd';\n");
- wholeScript.append(" var selectobject = document.getElementById(\"x\");\n");
- wholeScript.append(" for(var i=0; i<selectobject.length;i++) {\n ");
- wholeScript.append(" if(selectobject.options[i].value == nameAnnotation(ann)) {\n ");
- wholeScript.append(" selectobject.options[i].selected = true; \n ");
- wholeScript.append(" } ");
- wholeScript.append(" } ");
-
- wholeScript.append(" },\n");
- wholeScript.append(" annotationMouseOutHandler: function(ann) {\n");
- //wholeScript.append(" document.getElementById(nameAnnotation(ann)).style.fontWeight = 'normal';\n");
- wholeScript.append(" ann.div.style.backgroundColor = saveBg;\n");
- //wholeScript.append(" var selectobject = document.getElementById(\"x\");\n");
- //wholeScript.append(" for(var i=0; i<selectobject.length;i++) {\n ");
- //wholeScript.append(" if(selectobject.options[i].value == nameAnnotation(ann)) {\n ");
- //wholeScript.append(" selectobject.options[i].selected = false; \n ");
- //wholeScript.append(" } ");
- //wholeScript.append(" } ");
-
- wholeScript.append(" }\n");
- }
- wholeScript.append(" });\n");
-
-
- wholeScript.append("} \n");
- //}
- wholeScript.append("} else {\n");
- wholeScript.append("document.getElementById(\"message"+ reportRuntime.getReportID()+"\").display = \"none\";\n");
- wholeScript.append("document.getElementById(\"labelDiv"+ reportRuntime.getReportID()+"\").display=\"none\";\n");
- wholeScript.append("document.getElementById(\"div_g"+reportRuntime.getReportID()+"\").display=\"none\";\n");
-
- wholeScript.append("document.getElementById(\"div_g"+reportRuntime.getReportID()+"\").innerHTML = \"<div id='noData'><b>No Data Available</b></div>\";\n");
- wholeScript.append("document.getElementById(\"div_g"+reportRuntime.getReportID()+"\").className=\"nodatadiv\";\n");
- wholeScript.append("document.getElementById(\"nodata\").className=\"nodatainner\";\n");
- if(!timeCharts)
- wholeScript.append("document.getElementById(\"list"+reportRuntime.getReportID()+"\").display=\"none\";\n");
- wholeScript.append("}\n");
- wholeScript.append(" </script>\n");
- wholeScript.append(" </body>\n");
- wholeScript.append("</html>");
-
-
- } else if (chartType.equals(AppConstants.GT_SCATTER)) {
-
- wholeScript.append("<link href=\""+ chartScriptsPath +"d3/css/nv.d3.css\" rel=\"stylesheet\" type=\"text/css\">\n");
- wholeScript.append("<style>\n " +
- " body { \n" +
- " overflow-y:scroll; \n" +
- " } \n" +
- " text { \n" +
- " font: 12px sans-serif; \n" +
- " } \n" +
- " tr.z-row-over > td.z-row-inner, tr.z-row-over > .z-cell {" +
- " background-color: rgb(255, 255, 255); "+
- "} "+
- " svg { display: block; } " +
- " #chart1 svg { \n" +
- " height: 420px; \n" +
- " width: 800px; \n" +
- " min-width: 100px; \n" +
- " min-height: 100px; \n" +
- " } \n" +
-
- " </style> \n" );
- wholeScript.append("<body> \n");
- wholeScript.append("<div id=\"chart1\"><svg></svg></div>");
- //js files
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/d3.v2.js\"></script>\n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/nv.d3.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/tooltip.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/utils.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/legend.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/axis.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/distribution.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/scatter.js\"></script> \n");
- wholeScript.append("<script src=\""+ chartScriptsPath +"d3/js/models/scatterChart.js\"></script> \n");
- wholeScript.append("<script> \n");
- wholeScript.append("nv.addGraph(function() { \n" +
- " var width1=900, height1=220; \n" +
- " var chart = nv.models.scatterChart() \n" +
- " .showDistX(true) \n" +
- " .showDistY(true) \n" +
- " .useVoronoi(true) \n" +
- " .color(d3.scale.category10().range()); \n" +
-/* " .width(width1) \n" +
- " .height(height1); \n" +
-*/ " chart.xAxis\n" +
- " .axisLabel('" +legendColumnName + "')\n" +
- " .tickFormat(d3.format('.02f'));\n" +
- " chart.yAxis\n" +
- " .axisLabel('" + chartLeftAxisLabel + "')\n" +
- " .tickFormat(d3.format('.02f'));\n" +
- " d3.select('#chart1 svg') \n" +
- " .datum(getData()) \n" );
- if(animation)
- wholeScript.append(" .transition().duration(1200) \n" );
-/* " .attr(\"width\", width1) \n" +
- " .attr(\"height\", height1) \n" +
-*/ wholeScript.append(" .call(chart); \n" +
- " nv.utils.windowResize(chart.update);\n"+
- "return chart; \n" +
- "}); \n");
-
- String dateStr = "";
- Object uniqueElements [] = null;
- TreeSet ts = new TreeSet();
- for (int i = 0; i < ds.getRowCount(); i++) {
- dateStr = ds.getString(i, 2);
- if(dateStr.length()>0)
- ts.add(dateStr);
- }
- SortedSet s = Collections.synchronizedSortedSet(ts);
- uniqueElements = s.toArray();
-
- wholeScript.append(" function getData() { \n " +
- " var data = [];\n ");
- for (int i = 0; i < uniqueElements.length; i++) {
- wholeScript.append(" data.push( {key:'"+ uniqueElements[i]+ "', values:[]})\n");
- }
-
-
- for (int i = 0; i < ds.getRowCount(); i++) {
- for (int k = 0; k < uniqueElements.length; k++) {
- if(ds.getString(i, 2).equals(uniqueElements[k])) {
- wholeScript.append("data["+k+"].values.push({x:"+ ds.getString(i, 1) +",y:"+ds.getString(i, 3) + ", size: Math.random() });\n");
- }
- }
- }
-
- wholeScript.append("return data; } </script></body>\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)<Integer.parseInt(level))
- dataStr.append("},\n");
- dataStr.append("\""+ mid +"\": { \n");
- }
-
- mid_old = mid;
- level_old = level;
- }
- if(dataStr.toString().endsWith(","))
- dataStr.deleteCharAt(dataStr.lastIndexOf(","));
- dataStr.append("}\n");
- dataStr.append("}\n");
- try {
- String formattedReportName = new HtmlStripper().stripSpecialCharacters(reportRuntime.getReportName());
- String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new java.util.Date());
- String filename=formattedReportName+formattedDate+user_id+".json";
- String filenamepath = AppUtils.getExcelTemplatePath()+"../../json/"+filename;
- System.out.println("filenamepath " + filenamepath);
- BufferedWriter out = new BufferedWriter(new FileWriter(filenamepath));
- out.write(dataStr.toString());
- out.close();
- request.getSession().setAttribute("jsonFileName", filename);
- } catch (IOException e) {
- e.printStackTrace();
- System.out.println("Exception ");
- }
- } else if (chartType.equals(AppConstants.GT_HIERARCHICAL)) {
-
- StringBuffer dataStr = new StringBuffer("");
- StringBuffer groupBuffer = new StringBuffer("");
- StringBuffer s = new StringBuffer("");
- dataStr.append("{");
- dataStr.append(" \"groups\":[");
-
- for (int i = 0; i < ds.getRowCount(); i++) {
- if(ds.getString(i,"group_ind").equals("Y")) {
- groupBuffer.append(" { \"name\": \""+ ds.getString(i,"ei1") +"\" },\n");
- }
-
- }
- groupBuffer.deleteCharAt(groupBuffer.lastIndexOf(","));
- dataStr.append(groupBuffer.toString());
- dataStr.append("],");
- dataStr.append("\"nodes\":[");
- int rowCount = ds.getRowCount();
- for (int i = 0; i < ds.getRowCount(); i++) {
- s.append("{ \"name\": \""+ ds.getString(i,"ei1") +"\" , \"group\":"+ ds.getString(i,"groups") +", \"level\":2 }");
- if (i < (rowCount-1)) s.append(",");
- dataStr.append(s);
- s = new StringBuffer("");
- }
-
- dataStr.append("],");
- dataStr.append("\"links\":[");
- for (int i = 0; i < ds.getRowCount(); i++) {
- s.append("{ \"source\": "+ ds.getString(i,"source") +" , \"target\":"+ ds.getString(i,"target") +", \"value\":2 }");
- if (i < (rowCount-1)) s.append(",");
- dataStr.append(s);
- s = new StringBuffer("");
- }
- dataStr.append("]}");
- try {
- String formattedReportName = new HtmlStripper().stripSpecialCharacters(reportRuntime.getReportName());
- String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new java.util.Date());
- String filename=formattedReportName+formattedDate+user_id+".json";
- String filenamepath = AppUtils.getExcelTemplatePath()+"../../json/"+filename;
- System.out.println("filenamepath " + filenamepath);
- BufferedWriter out = new BufferedWriter(new FileWriter(filenamepath));
- out.write(dataStr.toString());
- out.close();
- request.getSession().setAttribute("jsonFileName", filename);
- } catch (IOException e) {
- e.printStackTrace();
- System.out.println("Exception ");
- }
- }
-
- }
- }
- try {
- BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
- out.write(wholeScript.toString());
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- System.out.println("Exception ");
- }
- return wholeScript.toString();
- }
-
- public String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- public String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
- public static String nvls(String s) {
- return (s == null) ? "" : s;
- }
-
- public static String nvls(String s, String sDefault) {
- return nvls(s).equals("") ? sDefault : s;
- }
-
- public boolean getFlagInBoolean(String s) {
- return nvl(s).toUpperCase().startsWith("Y") || nvl(s).toLowerCase().equals("true");
- }
-
- public DataSet loadChartData(String userId, HttpServletRequest request) throws RaptorException {
- if (nvl(getChartType()).length() == 0)
- return null;
- //TODO: display chart function to be added.
- //if (!getDisplayChart())
- // return null;
-
- String sql = null;
- sql = generateChartSQL(userId, request);
- logger.debug(EELFLoggerDelegate.debugLogger, ("SQL generated " + sql));
- String dbInfo = reportRuntime.getDBInfo();
- DataSet ds = ConnectionUtils.getDataSet(sql, dbInfo);
- if(ds.getRowCount()<=0) {
- logger.debug(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
- logger.debug(EELFLoggerDelegate.debugLogger, (getChartType().toUpperCase()+" - " + "Report ID : " + reportRuntime.getReportID() + " DATA IS EMPTY" ));
- logger.debug(EELFLoggerDelegate.debugLogger, ("QUERY - " + sql));
- logger.debug(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
- }
-
- return ds;
- } // loadChartData
-
- public String generateChartSQL(String userId, HttpServletRequest request ) throws RaptorException {
- List reportCols = reportRuntime.getAllColumns();
- List chartValueCols = getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, null); // parameter is 0 has this requires all columns.
- String reportSQL = reportRuntime.getWholeSQL();
-
- //Add order by clause
- Pattern re1 = Pattern.compile("(^[\r\n]*|([\\s]))[Oo][Rr][Dd][Ee][Rr](.*?[^\r\n]*)[Bb][Yy]",Pattern.DOTALL);
- //Pattern re1 = Pattern.compile("order(.*?[^\r\n]*)by", Pattern.DOTALL);
- Matcher matcher = re1.matcher(reportSQL);
- //Pattern re1 = Pattern.compile("(^[\r\n]*|([\\s]))[Oo][Rr][Dd][Ee][Rr][Tt](.*?[^\r\n]*)[Bb][Yy]",Pattern.DOTALL);
- //int startPoint = sql.length()-30;
-
- reportSQL = reportSQL + " ";
- reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" SELECT ");
- //reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ff][Rr][Oo][Mm]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" FROM ");
- reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" WHERE ");
- reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Nn]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" WHEN ");
- reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" AND ");
-
- if(!reportRuntime.getReportType().equals(AppConstants.RT_HIVE)) {
- int startPoint = reportSQL.lastIndexOf(" FROM ");
- if(startPoint <= 0) {
- startPoint = reportSQL.lastIndexOf(" from ");
- }
- if(startPoint <= 0) {
- startPoint = reportSQL.lastIndexOf("from ");
- }
- if(startPoint <= 0) {
- startPoint = reportSQL.lastIndexOf("FROM ");
- }
-
- if (!matcher.find(startPoint)) {
- reportSQL = reportSQL + " ORDER BY 1" ;
- }
- }
- reportRuntime.setWholeSQL(reportSQL);
-
- logger.debug(EELFLoggerDelegate.debugLogger, (" *************************************************************************************** "));
- logger.debug(EELFLoggerDelegate.debugLogger, ("WHOLE_SQL" + reportSQL));
- logger.debug(EELFLoggerDelegate.debugLogger, (" *************************************************************************************** "));
-
- 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);
- String paramValue = nvl(formfield_value);
- if(paramValue.length()>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<String,String>) 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<String> 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<String> 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;
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 <FormFieldJSON> formFieldList;
- private ArrayList <ChartColumnJSON> 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 <RangeAxisJSON> rangeAxisList;
- private ArrayList <RangeAxisJSON> rangeAxisRemoveList;
-
- private ArrayList <ArrayList<Row>> 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<FormFieldJSON> getFormFieldList() {
- return formFieldList;
- }
- public void setFormFieldList(ArrayList<FormFieldJSON> 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<RangeAxisJSON> getRangeAxisList() {
- return rangeAxisList;
- }
- public void setRangeAxisList(ArrayList<RangeAxisJSON> 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<Row> getRowList() {
- return rowList;
- }
- public void setRowList(ArrayList<Row> rowList) {
- this.rowList = rowList;
- }*/
-
- public ArrayList<ArrayList<Row>> getWholeList() {
- return wholeList;
- }
- public void setWholeList(ArrayList<ArrayList<Row>> wholeList) {
- this.wholeList = wholeList;
- }
- //private ArrayList<ColumnHeader> reportDataColumns;
- //private ArrayList<Map<String,Object>> reportDataRows;
- public ArrayList<ChartColumnJSON> getChartColumnJSONList() {
- return chartColumnJSONList;
- }
- public void setChartColumnJSONList(ArrayList<ChartColumnJSON> 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 "";
- }
- public ArrayList<RangeAxisJSON> getRangeAxisRemoveList() {
- return rangeAxisRemoveList;
- }
- public void setRangeAxisRemoveList(ArrayList<RangeAxisJSON> rangeAxisRemoveList) {
- this.rangeAxisRemoveList = rangeAxisRemoveList;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String, String> chartOptionsMap = new HashMap<String, String>();
- 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<String,String> chartOptionsMap = new HashMap<String, String>();
- 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<String,String> 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<DataColumnType> dcList = reportRuntime.getOnlyVisibleColumns();
- int countIndex = 0;
- ArrayList<ChartColumnJSON> chartColumnJSONList = new ArrayList<ChartColumnJSON>();
- 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<IdNameValue> formFieldValues = new ArrayList<IdNameValue>();
- ArrayList<FormFieldJSON> formFieldJSONList = new ArrayList<FormFieldJSON>();
- if(reportRuntime.getReportFormFields()!=null) {
- formFieldJSONList = new ArrayList<FormFieldJSON>(reportRuntime.getReportFormFields().size());
- for (Iterator iter = reportRuntime.getReportFormFields().iterator(); iter.hasNext();) {
- formFieldValues = new ArrayList<IdNameValue>();
- 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<DataColumnType> reportCols = reportRuntime.getAllColumns();
- boolean hasSeriesColumn = false;
- //ArrayList<Item>
- for (Iterator<DataColumnType> 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<DataColumnType> 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<RangeAxisJSON> rangeAxisJSONList = new ArrayList<RangeAxisJSON>();
- 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<ArrayList<Row>> wholeList = new ArrayList<ArrayList<Row>>();
-
- ArrayList<Row> rowList = new ArrayList<Row>();
- if(showData) {
- for (int i = 0; i < ds.getRowCount(); i++) {
- rowList = new ArrayList<Row>();
- for (int j = 0; j<ds.getColumnCount(); j++) {
- Row row = new Row();
- row.setColId(ds.getColumnName(j));
- row.setDisplayValue(ds.getString(i, j));
- row.setDataType(ds.getColumnType(j));
- rowList.add(row);
- }
- wholeList.add(rowList);
-
- }
-
- chartJSON.setWholeList(wholeList);
- }
- }
-
-
-
-
-
- }
- } else {
- // chart is not visible
- chartJSON.setReportID(reportRuntime.getReportID());
- chartJSON.setReportName(reportRuntime.getReportName());
- chartJSON.setReportDescr(reportRuntime.getReportDescr());
- chartJSON.setReportTitle(reportRuntime.getReportTitle());
- chartJSON.setReportSubTitle(reportRuntime.getReportSubTitle());
- chartJSON.setChartAvailable(displayChart);
- ChartTypeJSON chartTypeJSON = new ChartTypeJSON();
- chartTypeJSON.setIndex(0);
- chartTypeJSON.setTitle("");
- chartTypeJSON.setValue(chartType);
- chartJSON.setChartTypeJSON(chartTypeJSON);
- }
- //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(chartJSON);
- } catch (Exception ex) {
- ex.printStackTrace();
-
- }
-
- return jsonInString;
- }
-
- public String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- public String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
- public static String nvls(String s) {
- return (s == null) ? "" : s;
- }
-
- public static String nvls(String s, String sDefault) {
- return nvls(s).equals("") ? sDefault : s;
- }
-
- public boolean getFlagInBoolean(String s) {
- return nvl(s).toUpperCase().startsWith("Y") || nvl(s).toLowerCase().equals("true");
- }
-
- public DataSet loadChartData(String userId, HttpServletRequest request) throws RaptorException {
- if (nvl(getChartType()).length() == 0)
- return null;
- //TODO: display chart function to be added.
- //if (!getDisplayChart())
- // return null;
-
- String sql = null;
- sql = generateChartSQL(userId, request);
- logger.debug(EELFLoggerDelegate.debugLogger, ("SQL generated " + sql));
- String dbInfo = reportRuntime.getDBInfo();
- DataSet ds = ConnectionUtils.getDataSet(sql, dbInfo);
- if(ds.getRowCount()<=0) {
- logger.info(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
- logger.info(EELFLoggerDelegate.debugLogger, (getChartType().toUpperCase()+" - " + "Report ID : " + reportRuntime.getReportID() + " DATA IS EMPTY"));
- logger.info(EELFLoggerDelegate.debugLogger, ("QUERY - " + sql));
- logger.info(EELFLoggerDelegate.debugLogger, ("********************************************************************************"));
- }
-
- return ds;
- } // loadChartData
-
- public String generateChartSQL(String userId, HttpServletRequest request ) throws RaptorException {
- List reportCols = reportRuntime.getAllColumns();
- List chartValueCols = getChartValueColumnsList(AppConstants.CHART_ALL_COLUMNS, null); // parameter is 0 has this requires all columns.
- String reportSQL = reportRuntime.getWholeSQL();
-
- //Add order by clause
- Pattern re1 = Pattern.compile("(^[\r\n]*|([\\s]))[Oo][Rr][Dd][Ee][Rr](.*?[^\r\n]*)[Bb][Yy]",Pattern.DOTALL);
- //Pattern re1 = Pattern.compile("order(.*?[^\r\n]*)by", Pattern.DOTALL);
- Matcher matcher = re1.matcher(reportSQL);
- //Pattern re1 = Pattern.compile("(^[\r\n]*|([\\s]))[Oo][Rr][Dd][Ee][Rr][Tt](.*?[^\r\n]*)[Bb][Yy]",Pattern.DOTALL);
- //int startPoint = sql.length()-30;
-
- reportSQL = reportSQL + " ";
- reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" SELECT ");
- //reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ff][Rr][Oo][Mm]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" FROM ");
- reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" WHERE ");
- reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Nn]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" WHEN ");
- reportSQL = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(reportSQL).replaceAll(" AND ");
-
- if(!reportRuntime.getReportType().equals(AppConstants.RT_HIVE)) {
- int startPoint = reportSQL.lastIndexOf(" FROM ");
- if(startPoint <= 0) {
- startPoint = reportSQL.lastIndexOf(" from ");
- }
- if(startPoint <= 0) {
- startPoint = reportSQL.lastIndexOf("from ");
- }
- if(startPoint <= 0) {
- startPoint = reportSQL.lastIndexOf("FROM ");
- }
-
- if (!matcher.find(startPoint)) {
- reportSQL = reportSQL + " ORDER BY 1" ;
- }
- }
- reportRuntime.setWholeSQL(reportSQL);
-
- logger.debug(EELFLoggerDelegate.debugLogger, (" *************************************************************************************** "));
- logger.debug(EELFLoggerDelegate.debugLogger, ("WHOLE_SQL" + reportSQL));
- logger.debug(EELFLoggerDelegate.debugLogger, (" *************************************************************************************** "));
-
- 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);
- String paramValue = nvl(formfield_value);
- if(paramValue.length()>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 "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<String,String>) 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<String> 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<String> 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;
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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<String, Object> params = new HashMap<String, Object>();
-
- //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<String, Object> params = new HashMap<String, Object>();
- 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<String, String> chartOptionsMap = new HashMap<String, String>();
-
- 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<String> 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<String,String> chartOptionsMap) {
- drawD3Charts(chartOptionsMap);
-
- }
- */
-
- public String drawD3Charts(HashMap<String,String> 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<String,String> 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 "";
-
- }
-
- }
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- }
-
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
- * 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 "<a title=\"" + helpText + "\">" + fieldDisplayName + "</a>";
- 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 "<a href=\"#\" onclick=\"javascript:ShowContent('" + fieldName + "_div')\"><img src=\""+AppUtils.getBaseFolderURL()+"images/quickhelp_dk.gif\" width=\"12\" height=\"12\" alt=\"\" border=\"0\" class=\"qh-element\" /></a>";
- return ((getHelpText()!=null && getHelpText().length()>0)? "tooltipText=\""+ getHelpText()+"\">": ">");
- //return ((getHelpText()!=null && getHelpText().length()>0)? "<img src=\"static/fusion/raptor/images/quickhelp_lt.gif\" tooltipText=\""+ getHelpText() + "\"/>": "");
- }
-
-
- 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 "<input type=text class=\"text\" size=30 maxlength=50 id=\"" + fieldName +"\" name=\"" + fieldName + "\" value=\""
- + nvl(fieldDefValue) + "\">\n" + "<a href=\"javascript:showArgPopupNew('"
- + fieldName + "', 'document.formd." + fieldName
- + "')\"><img border=0 src=\"" + AppUtils.getImgFolderURL()
- + "shareicon.gif\" " + getHelpLink(fieldName);
- */
- return "obj.value=\""+Utils.singleQuoteEncode(nvl(fieldDefValue))+"\";";
-
- } else
- return "";
- } else if (fieldType.equals(FFT_HIDDEN) || fieldType.equals(FFT_TEXT) || fieldType.equals(FFT_TEXTAREA) ) {
- StringBuffer sb = new StringBuffer();
- String oldSQL = "";
- try {
- IdNameList lookup = getLookupList();
- //if(dependsOn != null && dependsOn != "") {
- //if(dependsOn != null && dependsOn != "" ) {
- IdNameSql lu = (IdNameSql) lookup;
- String SQL = lu.getSql();
- //System.out.println("SQL HIDDEN 1 " + SQL);
- 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(value == null || value.trim().length()<=0) {
- value = "NULL";
- }
- if(inSchedule) {
- try {
- value = java.net.URLDecoder.decode(value, "UTF-8");
- } catch (UnsupportedEncodingException ex) {
-
- }
- }
- //System.out.println("HIDDEN " + "["+entry.getKey()+"]" + "-" + value);
- SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", value);
- }
-
- lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL());
- }
- //System.out.println("SQL HIDDEN 2 " + SQL);
- //}
- lookupList = lookup;
- //}
- if(nvl(fieldValue).length()>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 "<input type=text class=\"text\" size=30 maxlength=50 id=\"" + fieldName +"\" name=\"" + fieldName + "\" value=\""
- + nvl(fieldDefValue) + "\">\n" + "<a href=\"javascript:showArgPopupNew('"
- + fieldName + "', 'document.formd." + fieldName
- + "')\"><img border=0 src=\"" + AppUtils.getImgFolderURL()
- + "shareicon.gif\" " + getHelpLink(fieldName);
- */
- String progress = "<div id=\""+fieldName+"_content\" style=\"display:none;width:100%;height:100%;align:center;\"> <img src=\""+AppUtils.getImgFolderURL()+"progress.gif\" border=\"0\" alt=\"Loading, please wait...\" /></div> ";
-
- return progress+"<input type=\"text\" class=\"text\" name=\""+getFieldName()+"_display\" readonly=true value=\""+ fieldDefDisplay +"\""+ getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName) + " \n "
- +"<input type=\"hidden\" name=\""+getFieldName()+"\" value=\""+nvl(fieldDefValue)+"\"/> \n \n"
- + "<a href=\"javascript:showArgPopupNew('"
- + fieldName + "', 'document.formd." + fieldName
- + "')\"><img border=0 src=\"" + AppUtils.getImgFolderURL()
- + "shareicon.gif\" " + getHelpLink(fieldName);
-
- } else
- return "";
- } else if (fieldType.equals(FFT_TEXT)) {
- IdNameValue value = null;
- String strValue = "";
- boolean avail_ReadOnly = false;
- try {
- IdNameList lookup = getLookupList();
- IdNameSql lu = null;
- String valueSQL = "";
- String oldSQL = "";
- if(lookup instanceof IdNameSql) {
- lu = (IdNameSql) lookup;
- if(lu.getSql().length() > 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 = "<input type=text class=\"text\" size="+(validationType.equals(VT_DATE)?"10":"30") +" maxlength=50 id=\"" + fieldName +"\" name=\""
- + fieldName + "\" id='"+ fieldName + "' "
- + (((validationType.equals(VT_DATE)||validationType.equals(VT_TIMESTAMP_HR) ||validationType.equals(VT_TIMESTAMP_MIN) ||validationType.equals(VT_TIMESTAMP_SEC))&& !inSchedule) ? "" : "")
- + getCallableJavascript(getFieldName(), rr) + " " + (readOnly?" readonly ":" ") + " value=\"";
-
-
- /*if(getFieldDefaultSQL()!=null)
- returnString += nvl(value.getId());
- else
- returnString += fieldValue;
- */
- if(fieldValue!=null && fieldValue.length()>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<a href=\"#\" onClick=\"window.dateField=document."
- + HTML_FORM
- + "."
- + fieldName
- + ";calendar=window.open('"
- + AppUtils.getRaptorActionURL()
- + "popup.calendar','cal','WIDTH=200,HEIGHT=250');return false;\">"
- + "\n\t\t\t\t<img src=\""
- + AppUtils.getImgFolderURL()
- + "calender_icon.gif\" align=absmiddle border=0 width=20 height=20></a>"
- : ""); */
-
- 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<img src='" + AppUtils.getImgFolderURL()+ "calender_icon.gif' align=absmiddle border=0 width='20' height='20' onClick=" + calendarOnClickMethodCall + " style='cursor:hand'>"
- : "");
- if(validationType.equals(VT_TIMESTAMP_HR) || validationType.equals(VT_TIMESTAMP_MIN) || validationType.equals(VT_TIMESTAMP_SEC) ) {
- //Add Hours/Minutes and Seconds.
- timeStampStr = " <font class=rtabletext>Hour </font><select id = \""+ fieldName+ "_Hr\" name=\""+ fieldName+ "_Hr\" "+ (readOnly?"disabled":"")+" >";
- int hour = 0;
- int t_hr = 0;
- try {
- hour = Integer.parseInt(nvl(rr.getParamValue(fieldName+"_Hr"),"0"));
- if(hour == 0) {
- if(inSchedule) hour = Integer.parseInt(nvl(((String)formValues.get(fieldName+"_Hr")),"0"));
- }
-// System.out.println("Hour =" + hour);
- } catch (NumberFormatException ex) { hour = 0; }
- try {
- t_hr = Integer.parseInt(timestamphr);
-// System.out.println("THR =" + t_hr);
- } catch (NumberFormatException ex) { t_hr = 0;}
-
- if(hour <= 0) hour = t_hr;
- // System.out.println("Form Values 887 " + formValues);
- /*if (formValues.containsKey(fieldDisplayName+"_Hr")){
- formValues.remove(fieldDisplayName+"_Hr");
- formValues.put(fieldDisplayName+"_Hr", hour);
- } else
- formValues.put(fieldDisplayName+"_Hr", hour);
- System.out.println("Form Values 887 " + formValues);
- */
-
- //int t_min = Integer.parseInt(timestampmin);
- //int t_sec = Integer.parseInt(timestampsec);
- for (int i = 0; i < 24; i++) {
- if(i==0) timeStampStr += "<option value=\"" + i + "\""+ ((hour==i)?" selected":"") +">00</option>";
- else if(i<10) timeStampStr += "<option value=\"" + i + "\""+ ((hour==i)?" selected":"") +">" + "0"+i + "</option>";
- else timeStampStr += "<option value=\"" + i + "\""+ ((hour==i)?" selected":"") +">" + i + "</option>";
-
- }
- timeStampStr += "</select>";
- }
- //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 += " <font class=rtabletext>Min </font><select id = \""+ fieldName+ "_Min\" name=\""+ fieldName+ "_Min\" "+ (readOnly?"disabled":"")+" >";
- for (int i = 0; i < 60; i++) {
- if(i==0) timeStampStr += "<option value=\"" + i + "\""+ ((minutes==i)?" selected":"") +">00</option>";
- else if(i<10) timeStampStr += "<option value=\"" + i + "\""+ ((minutes==i)?" selected":"") +">" + "0"+i + "</option>";
- else timeStampStr += "<option value=\"" + i + "\""+ ((minutes==i)?" selected":"") +">" + i + "</option>";
- }
- timeStampStr += "</select>";
- }
- //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 += " <font class=rtabletext>Sec </font><select id = \""+ fieldName+ "_Sec\" name=\""+ fieldName+ "_Sec\" "+ (readOnly?"disabled":"")+" >";
- for (int i = 0; i < 60; i++) {
- if(i==0) timeStampStr += "<option value=\"" + i + "\""+ ((seconds==i)?" selected":"") +">00</option>";
- else if(i<10) timeStampStr += "<option value=\"" + i + "\""+ ((seconds==i)?" selected":"") +">" + "0"+i + "</option>";
- else timeStampStr += "<option value=\"" + i + "\""+ ((seconds==i)?" selected":"") +">" + i + "</option>";
- }
- timeStampStr += "</select>";
- }
-
- 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 +" "+ */ "<input type=\"checkbox\" name=\""+getFieldName()+"_auto\" value=\"_auto\" checked/>";
- } else {
- checkboxStr = /*checkboxStr +" "+ */"<input type=\"hidden\" name=\""+getFieldName()+"_auto\" value=\"_auto\"/>";
- }
- /*if(validationType.equals(VT_TIMESTAMP_HR) || validationType.equals(VT_TIMESTAMP_MIN) || validationType.equals(VT_TIMESTAMP_SEC)) {
- checkboxStr = checkboxStr +" "+ "<input type=\"hidden\" name=\""+getFieldName()+"_Hr_auto\" value=\"_auto\"/>";
- }
- if(validationType.equals(VT_TIMESTAMP_MIN) || validationType.equals(VT_TIMESTAMP_SEC)) {
- checkboxStr = checkboxStr +" "+ "<input type=\"hidden\" name=\""+getFieldName()+"_Min_auto\" value=\"_auto\"/>";
- }
- if(validationType.equals(VT_TIMESTAMP_SEC)) {
- checkboxStr = checkboxStr +" "+ "<input type=\"hidden\" name=\""+getFieldName()+"_Sec_auto\" value=\"_auto\"/>";
- }*/
- }
- 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 "<textarea rows=4 cols=30 id=\"" + fieldName +"\" name=\"" + fieldName + "\""+ getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName) + nvl(fieldValue)
- + "</textarea>";
- else
- return "";
- } else if (fieldType.equals(FFT_COMBO_BOX)) {
- StringBuffer sb = new StringBuffer();
- //System.out.println("COMBO BOX " + fieldName);
- String oldSQL = "";
-
- IdNameList lookup = getLookupList();
- try {
- if(!hasPredefinedList) {
- //if(dependsOn != null && dependsOn != "") {
- //if(dependsOn != null && dependsOn != "" ) {
- IdNameSql lu = (IdNameSql) lookup;
- String SQL = lu.getSql();
- //System.out.println("FORMFIELD 6666667 First" + ((IdNameSql)lookup).getSql());
- 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 (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();
-
- for (lookup.resetNext(); lookup.hasNext();) {
- IdNameValue value = lookup.getNext();
- readOnly = value.isReadOnly();
- break;
- }
-
- String selectedValue = "";
- int count = 0;
- sb.append("<div id=\""+fieldName+"_content\" style=\"display:none;width:100%;height:100%;align:center;\"> <img src=\""+AppUtils.getImgFolderURL()+"progress.gif\" border=\"0\" alt=\"Loading, please wait...\" /></div>");
- sb.append("<select id=\"" + fieldName +"\" name=\"");
- sb.append(fieldName);
- sb.append("\" "+ (readOnly?"disabled":"")+" size=1 " + getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName));
- if (!required)
- sb.append("<option value=\"\">-->select value<--");
-
- 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("<option value=\"");
- sb.append(value.getId());
-
- if (nvl(fieldValue).length()>0) {
- if (fieldValue.equals(value.getId())) { // || (value.isDefaultValue()))
- sb.append("\" selected>");
- selectedValue = value.getId();
- }
- else
- sb.append("\">");
- } else {
- if(value!=null && value.isDefaultValue()) {
- sb.append("\" selected>");
- selectedValue = value.getId();
- } else {
- sb.append("\">");
- }
- }
-
- sb.append(value.getName());
- sb.append("</option>\n");
- }
- } // 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(sb.length()<=0) {
- sb.append("<div id=\""+fieldName+"_content\" style=\"display:none;width:100%;height:100%;align:center;\"> <img src=\""+AppUtils.getImgFolderURL()+"progress.gif\" border=\"0\" alt=\"Loading, please wait...\" /></div>");
- sb.append("<select id=\"" + fieldName +"\" name=\"");
- sb.append(fieldName);
- sb.append("\" "+ (readOnly?"disabled":"")+" size=1 " + getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName));
- }
-
- sb.append("</select>");
- if( isVisible())
- return sb.toString();
- else return "";
- } else if (fieldType.equals(FFT_LIST_BOX)) {
- StringBuffer sb = new StringBuffer();
- String oldSQL = "";
- IdNameList lookup = null;
-
- lookup = getLookupList();
- String selectedValue = "";
- try {
- if(!hasPredefinedList) {
- //if(dependsOn != null && dependsOn != "") {
- //if(dependsOn != null && dependsOn != "" ) {
- IdNameSql lu = (IdNameSql) lookup;
- String SQL = lu.getSql();
- 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);
- }
- 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();
-
- for (lookup.resetNext(); lookup.hasNext();) {
- IdNameValue value = lookup.getNext();
- readOnly = value.isReadOnly();
- break;
- }
-
- int iCnt = 0;
- sb.append("<select id=\"" + fieldName +"\" name=\"");
- sb.append(fieldName);
- sb.append("\" "+ (readOnly?"disabled":"")+" size=4 " + getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName));
- if (!required)
- sb.append("<option value=\"\">-->select value<--");
-
- for (lookup.resetNext(); lookup.hasNext(); iCnt++) {
- IdNameValue value = lookup.getNext();
- sb.append("<option value=\"");
- sb.append((value!=null)?value.getId():"");
- if (nvl(fieldValue).length()>0) {
- if (fieldValue.equals((value!=null)?value.getId():"") || (fieldValue.equals("") && required && iCnt == 0)) {
- sb.append("\" selected>");
- selectedValue = value.getId();
- } else {
- sb.append("\">");
- }
- } else {
- if(value!=null && value.isDefaultValue()) {
- sb.append("\" selected>");
- selectedValue = value.getId();
- } else {
- sb.append("\">");
- }
- }
- if (formValues.containsKey(fieldDisplayName)){
- formValues.remove(fieldDisplayName);
- }
- formValues.put(fieldDisplayName, selectedValue);
-
- sb.append((value!=null)?value.getName():"");
- sb.append("</option>\n");
- } // for
-
- // lookup.clearData();
- } catch (Exception e) {
- //throw new RaptorRuntimeException(e);
- }
-
- if(sb.length()<=0) {
- sb.append("<select id=\"" + fieldName +"\" name=\"");
- sb.append(fieldName);
- sb.append("\" "+ (readOnly?"disabled":"")+" size=4 " + getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName));
- }
-
- sb.append("</select>");
-
- if(!hasPredefinedList) {
- if(oldSQL != null && !oldSQL.equals("")) {
- ((IdNameSql)lookup).setSQL(oldSQL);
- }
- }
-
- if(isVisible())
- return sb.toString();
- else
- return "";
- } else if (fieldType.equals(FFT_HIDDEN)) {
- StringBuffer sb = new StringBuffer();
- String oldSQL = "";
- String progress = "<div id=\""+fieldName+"_content\" style=\"display:none;width:100%;height:100%;align:center;\"> <img src=\""+AppUtils.getImgFolderURL()+"progress.gif\" border=\"0\" alt=\"Loading, please wait...\" /></div> ";
- sb.append(progress);
- sb.append("<input id=\"" + fieldName +"\" name=\"");
- sb.append(fieldName);
- sb.append("\" type=\"hidden\"");
- IdNameList lookup = null;
-
- try {
- lookup = getLookupList();
- if(lookup != null) {
- //if(dependsOn != null && dependsOn != "") {
- //if(dependsOn != null && dependsOn != "" ) {
- IdNameSql lu = (IdNameSql) lookup;
- String SQL = lu.getSql();
- //System.out.println("SQL HIDDEN 1 " + SQL);
- 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();
- //System.out.println("HIDDEN " + "["+entry.getKey()+"]" + "-" + value);
- SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", value);
- }
-
- lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL());
- }
- //System.out.println("SQL HIDDEN 2 " + SQL);
- //}
- lookupList = lookup;
- //}
- if(nvl(fieldValue).length()>0 && (dependsOn == null || dependsOn.length()<=0)) {
- sb.append(" value=\"");
- sb.append((fieldValue!=null)?fieldValue:"");
- sb.append("\">");
- } 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=\"");
- sb.append((value!=null)?value.getId():"");
- sb.append("\">");
- break;
- } // for
- if(lookup.size()<=0) {
- sb.append(" value=\"");
- sb.append("\">");
-
- }
- } else {
- sb.append(" value=\"");
- sb.append((fieldValue!=null)?fieldValue:"");
- sb.append("\"/>");
- }
- } else {
- sb.append(" value=\"");
- sb.append((fieldValue!=null)?fieldValue:"");
- sb.append("\"/>");
- }
- if(oldSQL != null && !oldSQL.equals("")) {
- ((IdNameSql)lookup).setSQL(oldSQL);
- }
- // lookup.clearData();
- } catch (Exception e) {
- sb.append(" value=\"\"/>");
- //throw new RaptorRuntimeException(e);
- }
-
- if(!hasPredefinedList) {
- if(oldSQL != null && !oldSQL.equals("")) {
- ((IdNameSql)lookup).setSQL(oldSQL);
- }
- }
- //if(isVisible())
- return sb.toString() ;
- } else if (fieldType.equals(FFT_RADIO_BTN)) {
- StringBuffer sb = new StringBuffer();
- if (!required) {
- sb.append("<input id=\"" + fieldName +"\" type=radio name=\"");
- sb.append(fieldName);
- sb.append("\" value=\"\"");
- if (fieldValue.length() == 0)
- sb.append(" checked");
- //sb.append( getCallableJavascript(getFieldName(), rr) );
- sb.append(getHelpLink(fieldName)+ " Any<br>\n");
- }
-
- try {
- IdNameList lookup = getLookupList();
- lookup.loadUserData(0, "", getDbInfo(),getUserId());
- String selectedValue = "";
-
- int iCnt = 0;
- for (lookup.resetNext(); lookup.hasNext(); iCnt++) {
- IdNameValue value = lookup.getNext();
- sb.append("<input id=\"" + fieldName +"\" type=radio name=\"");
- sb.append(fieldName);
- sb.append("\" value=\"");
- sb.append((value!=null)?value.getId():"");
- if (nvl(fieldValue).length()>0) {
- if (fieldValue.equals((value!=null)?value.getId():"") || (fieldValue.equals("") && required && iCnt == 0)) {
- sb.append("\" checked>");
- selectedValue = value.getId();
- } else {
- sb.append("\">");
- }
- } else {
- if(value!=null && value.isDefaultValue()) {
- sb.append("\" checked>");
- selectedValue = value.getId();
- } else {
- sb.append("\">");
- }
- }
- sb.append((value!=null)?value.getName():"");
- sb.append("<br>\n");
- } // for
- if (formValues.containsKey(fieldDisplayName)){
- formValues.remove(fieldDisplayName);
- }
- formValues.put(fieldDisplayName, selectedValue);
-
- // lookup.clearData();
- } catch (Exception e) {
- throw new RaptorRuntimeException(e);
- }
- if(isVisible())
- return sb.toString() ;
- else
- return "";
- } else if (fieldType.equals(FFT_CHECK_BOX)) {
- StringBuffer sb = new StringBuffer();
-
- fieldValue = '|' + fieldValue + '|';
- int count = 0 ;
- try {
- String selectedValue = "";
- IdNameList lookup = getLookupList();
- if(lookup != null) {
- lookup.loadUserData(0, "", getDbInfo(), getUserId());
-
- for (lookup.resetNext(); lookup.hasNext();) {
- count++;
- IdNameValue value = lookup.getNext();
- sb.append("<input id=\"" + fieldName +"\" type=checkbox name=\"");
- sb.append(fieldName);
- sb.append("\" value=\"");
- sb.append((value!=null)?value.getId():"");
-
- if (!fieldValue.equals("||")) {
- if (fieldValue.indexOf('|' + ((value!=null)?value.getId():"") + '|') >= 0) { // || (value.isDefaultValue()))
- sb.append("\" checked " + getHelpLink(fieldName));
- selectedValue = value.getId();
- }
- else
- sb.append("\"" + getHelpLink(fieldName));
- } else {
- if(value!=null && value.isDefaultValue()) {
- sb.append("\" checked " + getHelpLink(fieldName));
- selectedValue = value.getId();
- } else {
- sb.append("\"" + getHelpLink(fieldName));
- }
- }
-
- if(!(/*(value.getName().equals("Y")||value.getName().equals("N")) && */(!lookup.hasNext()) && count == 1))
- sb.append((value!=null)?value.getName():"");
- sb.append("<br>\n");
- } // for
-
- if (formValues.containsKey(fieldDisplayName)){
- formValues.remove(fieldDisplayName);
- }
- formValues.put(fieldDisplayName, selectedValue);
- }
-
- // lookup.clearData();
- } catch (Exception e) {
- throw new RaptorRuntimeException(e);
- }
- 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 = lu.getSql();
- 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);
- }
- lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL());
- }
- //}
- lookupList = lookup;
- //}
-
- lookup.loadUserData(0, "", getDbInfo(),getUserId());
- }
- for (lookup.resetNext(); lookup.hasNext();) {
- IdNameValue value = lookup.getNext();
- readOnly = value.isReadOnly();
- break;
- }
-
- sb.append("<div id=\""+fieldName+"_content\" style=\"display:none;width:100%;height:100%;align:center;\"> <img src=\""+AppUtils.getImgFolderURL()+"progress.gif\" border=\"0\" alt=\"Loading, please wait...\" /></div>");
- sb.append("<select id=\"" + fieldName +"\" name=\"");
- sb.append(fieldName);
- sb.append("\" "+ (readOnly?"disabled":"")+" size=\""+ multiSelectListSize +"\" multiple " + getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName));
-
- for (lookup.resetNext(); lookup.hasNext();) {
- IdNameValue value = lookup.getNext();
- sb.append("<option value=\"");
- sb.append((value!=null)?value.getId():"");
- if (!fieldValue.equals("||")) {
- if (fieldValue.indexOf('|' + ((value!=null)?value.getId():"") + '|') >= 0) // || (value.isDefaultValue()))
- sb.append("\" selected>");
- else
- sb.append("\">");
- } else {
- if(value!=null && value.isDefaultValue()) {
- sb.append("\" selected>");
- } else {
- sb.append("\">");
- }
- }
- sb.append((value!=null)?value.getName():"");
- sb.append("</option>\n");
- } // for
-
- // lookup.clearData();
- } catch (Exception e) {
- //throw new RaptorRuntimeException(e);
- }
- if(!hasPredefinedList) {
- if(oldSQL != null && !oldSQL.equals("")) {
- ((IdNameSql)lookup).setSQL(oldSQL);
- }
- }
- if(sb.length()<=0) {
- sb.append("<div id=\""+fieldName+"_content\" style=\"display:none;width:100%;height:100%;align:center;\"> <img src=\""+AppUtils.getImgFolderURL()+"progress.gif\" border=\"0\" alt=\"Loading, please wait...\" /></div>");
- sb.append("<select id=\"" + fieldName +"\" name=\"");
- sb.append(fieldName);
- sb.append("\" "+ (readOnly?"disabled":"")+" size=\""+ multiSelectListSize +"\" multiple " + getCallableJavascript(getFieldName(), rr) + getHelpLink(fieldName));
- }
- sb.append("</select>");
- if(isVisible())
- return sb.toString();
- else
- return "";
- } else if (fieldType.equals(FFT_BLANK)) {
- StringBuffer sb = new StringBuffer();
- sb.append(" ");
- return sb.toString();
- } else
- throw new org.openecomp.portalsdk.analytics.error.RaptorRuntimeException("FormField.getHtml: Unsupported form field type");
- } // getHtml
-
- public String getValidateJavaScript() {
- StringBuffer javaScript = new StringBuffer();
-
- if (fieldType.equals(FFT_TEXT_W_POPUP) || fieldType.equals(FFT_TEXT)
- || fieldType.equals(FFT_TEXTAREA)) {
- if (required) {
- javaScript.append("\n\tif(document.");
- javaScript.append(HTML_FORM);
- javaScript.append(".");
- javaScript.append(fieldName);
- javaScript.append(".value==\"\") {\n\t\talert(\"Please enter value for ");
- javaScript.append(fieldDisplayName);
- javaScript.append("\");\n\t\tdocument.");
- javaScript.append(HTML_FORM);
- javaScript.append(".");
- javaScript.append(fieldName);
- javaScript.append(".focus();\n\t\tdocument.");
- javaScript.append(HTML_FORM);
- javaScript.append(".");
- javaScript.append(fieldName);
- javaScript.append(".select();\n\t\treturn false;\n\t}\n");
- } // if
-
- if (!validationType.equals(VT_NONE)) {
- javaScript.append("\n\tif(! ");
- if (validationType.equals(VT_DATE)||validationType.equals(VT_TIMESTAMP_HR)||validationType.equals(VT_TIMESTAMP_MIN)||validationType.equals(VT_TIMESTAMP_SEC))
- javaScript.append("checkDate(");
- else if (validationType.equals(VT_INT))
- javaScript.append("checkInteger(");
- else if (validationType.equals(VT_INT_POSITIVE))
- javaScript.append("checkPositiveInteger(");
- else if (validationType.equals(VT_INT_NON_NEGATIVE))
- javaScript.append("checkNonNegativeInteger(");
- else if (validationType.equals(VT_FLOAT))
- javaScript.append("checkFloat(");
- else if (validationType.equals(VT_FLOAT_POSITIVE))
- javaScript.append("checkPositiveFloat(");
- else if (validationType.equals(VT_FLOAT_NON_NEGATIVE))
- javaScript.append("checkNonNegativeFloat(");
- javaScript.append("document.");
- javaScript.append(HTML_FORM);
- javaScript.append(".");
- javaScript.append(fieldName);
- javaScript.append(".value");
- if (validationType.equals(VT_DATE)||validationType.equals(VT_TIMESTAMP_HR)||validationType.equals(VT_TIMESTAMP_MIN)||validationType.equals(VT_TIMESTAMP_SEC))
- javaScript.append(", true");
- javaScript.append(")) {\n\t\talert(\"");
- javaScript.append(fieldDisplayName);
- javaScript.append(" is not a valid ");
- if (validationType.equals(VT_DATE)||validationType.equals(VT_TIMESTAMP_HR)||validationType.equals(VT_TIMESTAMP_MIN)||validationType.equals(VT_TIMESTAMP_SEC))
- javaScript.append("date formatted "+ Globals.getCalendarOutputDateFormat());
- else if (validationType.equals(VT_INT))
- javaScript.append("integer");
- else if (validationType.equals(VT_INT_POSITIVE))
- javaScript.append("integer greater than zero");
- else if (validationType.equals(VT_INT_NON_NEGATIVE))
- javaScript.append("integer greater than or equal to zero");
- else if (validationType.equals(VT_FLOAT))
- javaScript.append("number");
- else if (validationType.equals(VT_FLOAT_POSITIVE))
- javaScript.append("number greater than zero");
- else if (validationType.equals(VT_FLOAT_NON_NEGATIVE))
- javaScript.append("number greater than or equal to zero");
- javaScript.append(".\\nPlease enter a valid value.\");\n\t\tdocument.");
- javaScript.append(HTML_FORM);
- javaScript.append(".");
- javaScript.append(fieldName);
- javaScript.append(".focus();\n\t\tdocument.");
- javaScript.append(HTML_FORM);
- javaScript.append(".");
- javaScript.append(fieldName);
- javaScript.append(".select();\n\t\treturn false;\n\t}\n");
- } // if
- } // if
- else if (fieldType.equals(FFT_CHECK_BOX)) {
- if (required) {
- javaScript.append("\n\tvar isChecked = false;");
- javaScript.append("\n\tfor (var i=0; i < document.");
- javaScript.append(HTML_FORM);
- javaScript.append(".");
- javaScript.append(fieldName);
- javaScript.append(".length; i++) { ");
- javaScript.append("\n\t\tif(document.");
- javaScript.append(HTML_FORM);
- javaScript.append(".");
- javaScript.append(fieldName);
- javaScript.append("[i].checked) {");
- javaScript.append("\n\t\t\tisChecked = true;");
- javaScript.append("\n\t\t\tbreak;");
- javaScript.append("\n\t\t}");
- javaScript.append("\n\t}");
- javaScript.append("\n\tif(!isChecked) {");
- javaScript.append("\n\t\talert(\"Please select at least one ");
- javaScript.append(fieldDisplayName);
- javaScript.append("\");\n\t\treturn false;");
- javaScript.append("\n\t}");
- } // if
- } // else if FFT_CHECK_BOX
- else if (fieldType.equals(FFT_LIST_MULTI)) {
- if (required) {
- javaScript.append("\n\tif(document.");
- javaScript.append(HTML_FORM);
- javaScript.append(".");
- javaScript.append(fieldName);
- javaScript.append(".selectedIndex == -1) {");
- javaScript.append("\n\t\talert(\"Please select at least one ");
- javaScript.append(fieldDisplayName);
- javaScript.append("\");\n\t\treturn false;");
- javaScript.append("\n\t}");
- } // if
- } // else if
-
- return javaScript.toString();
- } // getValidateJavaScript
-
- public void setDbInfo(String dbInfo) {
- this.dbInfo = dbInfo;
- }
-
- public String getDbInfo() {
- return dbInfo;
- }
-
- public void setUserId(String userId) {
- this.userId = userId;
- }
-
- public String getUserId() {
- return userId;
- }
-
-
- public String getFieldDefaultSQL() {
-
- return fieldDefaultSQL;
- }
-
-
- public void setFieldDefaultSQL(String fieldDefaultSQL) {
-
- this.fieldDefaultSQL = fieldDefaultSQL;
- }
-
-
- public boolean isVisible() {
-
- return visible;
- }
-
-
- public void setVisible(boolean visible) {
-
- this.visible = visible;
- }
-
- public String getDependsOn() {
- return dependsOn;
- }
-
- public void setDependsOn(String dependsOn) {
- this.dependsOn = dependsOn;
- }
-
- public Calendar getRangeEndDate() {
- if(rangeEndDate != null)
- rangeEndDate.add(Calendar.DATE, 1);
- return rangeEndDate;
- }
-
- public void setRangeEndDate(Calendar rangeEndDate) {
- this.rangeEndDate = rangeEndDate;
- }
-
- public Calendar getRangeStartDate() {
- if(rangeStartDate != null)
- rangeStartDate.add(Calendar.DATE, -1);
- return rangeStartDate;
- }
-
- public void setRangeStartDate(Calendar rangeStartDate) {
- this.rangeStartDate = rangeStartDate;
- }
-
- public String getRangeEndDateSQL() {
- return rangeEndDateSQL;
- }
-
- public void setRangeEndDateSQL(String rangeEndDateSQL) {
- this.rangeEndDateSQL = rangeEndDateSQL;
- }
-
- public void setMultiSelectListSize(String multiSelectListSize) {
- this.multiSelectListSize = multiSelectListSize;
- }
-
- public String getRangeStartDateSQL() {
- return rangeStartDateSQL;
- }
-
- public void setRangeStartDateSQL(String rangeStartDateSQL) {
- this.rangeStartDateSQL = rangeStartDateSQL;
- }
-
- public boolean isHasPredefinedList() {
- return hasPredefinedList;
- }
-
- public void setHasPredefinedList(boolean hasPredefinedList) {
- this.hasPredefinedList = hasPredefinedList;
- }
-
- public boolean isTriggerOtherFormFields() {
- return triggerOtherFormFields;
- }
-
- public void setTriggerOtherFormFields(boolean triggerOtherFormFields) {
- this.triggerOtherFormFields = triggerOtherFormFields;
- }
-
- public boolean isTriggerThisFormfield() {
- return triggerThisFormfield;
- }
-
- public void setTriggerThisFormfield(boolean triggerThisFormfield) {
- this.triggerThisFormfield = triggerThisFormfield;
- }
-
-
-} // FormField
+++ /dev/null
-/*-
- * ================================================================================
- * 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.*;
-
-import org.openecomp.portalsdk.analytics.*;
-import org.openecomp.portalsdk.analytics.system.*;
-import org.openecomp.portalsdk.analytics.util.*;
-import org.openecomp.portalsdk.analytics.view.*;
-import org.openecomp.portalsdk.analytics.xmlobj.*;
-
-public class FormatProcessor extends RaptorObject {
-
-
- private SemaphoreType semaphore = null;
-
- private String colType = null;
-
- private String dateFormat = null;
-
- private HtmlFormatter defaultFormatter = null;
-
- private HashMap formatters = null;
-
- private HashMap convertedValues = null;
-
- private boolean attemptNumericConversion = false;
-
- public FormatProcessor(SemaphoreType sem, String colType, String dateFormat,
- boolean attemptNumericConversion) {
-
- super();
-
- if (sem == null)
- return;
-
- this.semaphore = sem;
- this.colType = colType;
- this.dateFormat = dateFormat;
-
- this.attemptNumericConversion = attemptNumericConversion;
- if (attemptNumericConversion)
- for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter
- .hasNext();) {
- FormatType fmt = (FormatType) iter.next();
- if (!isNumber(fmt.getLessThanValue())) {
- this.attemptNumericConversion = false;
- break;
- } // if
- } // for
-
- formatters = new HashMap(semaphore.getFormatList().getFormat().size() * 4 / 3);
- convertedValues = new HashMap(semaphore.getFormatList().getFormat().size() * 4 / 3);
-
- for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter.hasNext();) {
- FormatType fmt = (FormatType) iter.next();
- if ((fmt.getFormatId() == null) || (fmt.getFormatId().length() <= 0)) {
- defaultFormatter = new HtmlFormatter(fmt.isBold(), fmt.isItalic(), fmt
- .isUnderline(), fmt.getBgColor(), fmt.getFontColor(), fmt
- .getFontFace(), fmt.getFontSize(), fmt.getAlignment());
- } else {
- formatters.put(fmt.getFormatId(), new HtmlFormatter(fmt.isBold(), fmt
- .isItalic(), fmt.isUnderline(), fmt.getBgColor(), fmt.getFontColor(),
- fmt.getFontFace(), fmt.getFontSize(), fmt.getAlignment()));
- convertedValues.put(fmt.getFormatId(), convertValue(fmt.getLessThanValue()));
- }
- } // for
- } // FormatProcessor
-
- private String convertValue(String origValue) {
-
- if (colType.equals(AppConstants.CT_DATE))
- return convertDateValue(origValue);
- else if (colType.equals(AppConstants.CT_NUMBER))
- return convertNumericValue(origValue);
- else if (attemptNumericConversion)
- return convertUnknownValue(origValue);
- else
- return origValue;
- } // convertValue
-
- private String convertDateValue(String origValue) {
-
- // Converts to YYYY-MM-DD if possible
- if (nvl(dateFormat).length() == 0 || nvl(origValue).length() == 0)
- return origValue;
-
- if (dateFormat.equals("MM/DD/YYYY") && origValue.length() == 10)
- // Special processing for the default date format - for saving DB
- // calls
- return origValue.substring(6, 10) + "-" + origValue.substring(0, 2) + "-"
- + origValue.substring(3, 5);
-
- try {
- // DataSet ds = DbUtils.executeQuery("SELECT TO_CHAR(TO_DATE('" + origValue + "', '"
- // + dateFormat + "'), 'YYYY-MM-DD') val FROM DUAL");
-
- String sql = Globals.getGenerateSqlVisualDual();
- DataSet ds = DbUtils.executeQuery("SELECT TO_CHAR(TO_DATE('" + origValue + "', '"
- + dateFormat + "'), 'YYYY-MM-DD') val"+sql);
-
- if (ds.getRowCount() > 0)
- return ds.getString(0, 0);
- } catch (Exception e) {
- }
-
- return origValue;
- } // convertDateValue
-
- private String convertNumericValue(String origValue) {
-
- // Converts to [20 pos.5 pos] if possible
- if (nvl(origValue).length() == 0)
- return origValue;
- boolean isNegative = false;
-
- StringBuffer integerValue = new StringBuffer();
- StringBuffer fractionValue = new StringBuffer();
-
- boolean beforeDecimalPoint = true;
- for (int i = 0; i < origValue.length(); i++) {
- char c = origValue.charAt(i);
- if (c == '.')
- beforeDecimalPoint = false;
- else if (c == '-' && integerValue.length() == 0)
- isNegative = true;
- // else
- // if(c=='0'||c=='1'||c=='2'||c=='3'||c=='4'||c=='5'||c=='6'||c=='7'||c=='8'||c=='9')
- else if (Character.isDigit(c))
- if (beforeDecimalPoint)
- integerValue.append(c);
- else
- fractionValue.append(c);
- } // for
-
- while (integerValue.length() < 20)
- integerValue.insert(0, '0');
-
- while (fractionValue.length() < 5)
- fractionValue.append('0');
-
- integerValue.append('.');
- integerValue.append(fractionValue);
- integerValue.insert(0, (isNegative ? '-' : '+'));
-
- return integerValue.toString();
- } // convertNumericValue
-
- private boolean isNumber(String value) { // As per Raptor def, like
-
- // -$3,270.56
- value = value.trim();
- for (int i = 0; i < value.length(); i++) {
- char c = value.charAt(i);
- if (!(Character.isDigit(c) || c == '.' || c == '-' || c == '+' || c == ','
- || c == '$' || c == '%'))
- return false;
- } // for
-
- return true;
- } // isNumber
-
- private String convertUnknownValue(String origValue) {
-
- return isNumber(origValue) ? convertNumericValue(origValue) : origValue;
- } // convertUnknownValue
-
- private boolean isEqual(String value1, String value2) {
-
- return value1.trim().equals(value2.trim());
- } // isEqual
-
- private boolean isLessThan(String value1, String value2) {
-
- boolean compareAsNumbers = colType.equals(AppConstants.CT_NUMBER);
- if ((!compareAsNumbers) && attemptNumericConversion)
- compareAsNumbers = isNumber(value1) && isNumber(value2);
- if (compareAsNumbers && value1.length()>0 && value2.length()>0) {
- boolean value1IsNegative = (value1.charAt(0) == '-');
- boolean value2IsNegative = (value2.charAt(0) == '-');
- if (value1IsNegative && (!value2IsNegative)) {
- return true;
- }
- else if ((!value1IsNegative) && value2IsNegative) {
- return false;
- }
- return Double.parseDouble(value1)<Double.parseDouble(value2);
- } // if
-
- return (value1.compareTo(value2) < 0);
- } // isEqual
-
- public void setHtmlFormatters(DataValue dv, DataRow dr, boolean formatModified) {
-
- if (semaphore == null)
- return;
-
- HtmlFormatter formatter = defaultFormatter;
- HtmlFormatter anyFormatter = null;
- String sValue = convertValue(dv.getDisplayValue());
-
- String compareColId = semaphore.getComment(); // When Column Id compare is different from formatting.
-
- String targetColId = null;
- if(semaphore.getTarget()!=null)
- targetColId = semaphore.getTarget();
-
- DataValue targetDataValue = null;
- /* compare the column id which is in comment and assign to sValue */
- if(nvl(compareColId).length()>0) {
- for (dr.resetNext(); dr.hasNext();) {
- DataValue dv1 = dr.getNext();
- //add null check
- if(dv1.getColId()!=null) {
- if(dv1.getColId().equals(compareColId))
- sValue = convertValue(dv1.getDisplayValue());
- if(targetColId!=null) {
- if(dv1.getColId().equals(targetColId))
- targetDataValue = dv1;
- }
- }
- }
- }
-
- for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter
- .hasNext();) {
- FormatType fmt = (FormatType) iter.next();
- if(fmt.getLessThanValue().length() <= 0) {
- anyFormatter = (HtmlFormatter) formatters.get(fmt.getFormatId());
- anyFormatter.setFormatId(fmt.getFormatId());
- break;
- }
- }
-
- if( anyFormatter == null ) anyFormatter = formatter;
- // String sValue = convertValue(dv.getDisplayValue());
- //if (sValue.length() > 0) {
- for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter
- .hasNext();) {
- FormatType fmt = (FormatType) iter.next();
- // For Excel Download
-
- if ((fmt.getFormatId() == null) || (fmt.getFormatId().length() <= 0)) {
- // Default formatter
- continue;
- }
-
- String formatterValue = nvl((String) convertedValues.get(fmt.getFormatId()));
- boolean valueMatched = false;
- if (fmt.getExpression().equals("=")) {
- valueMatched = isEqual(sValue, formatterValue);
- }
-
- else if (fmt.getExpression().equals("<>"))
- valueMatched = (!isEqual(sValue, formatterValue));
- else if (fmt.getExpression().equals(">")) {
- valueMatched = (!(isEqual(sValue, formatterValue) || isLessThan(sValue,
- formatterValue)));
- }
- else if (fmt.getExpression().equals(">=")) {
- valueMatched = /* isEqual(sValue, formatterValue)|| */(!isLessThan(
- sValue, formatterValue));
- }
- else if (fmt.getExpression().equals("<")) {
- valueMatched = isLessThan(sValue, formatterValue);
- }
- else if (fmt.getExpression().equals("<=")) {
- valueMatched = isEqual(sValue, formatterValue)
- || isLessThan(sValue, formatterValue);
- }
- //s_logger.debug("SYSOUT " + " " +sValue +" " +fmt.getBgColor() + " " + fmt.getLessThanValue()+ " " +valueMatched);
- if (fmt.getLessThanValue().length() > 0 && valueMatched) {
- formatter = (HtmlFormatter) formatters.get(fmt.getFormatId());
- formatter.setFormatId(fmt.getFormatId());
- formatModified = true;
- //dv.setFormatId(fmt.getFormatId());
- //dr.setFormatId(fmt.getFormatId());
- //break;
- } else { // if
- if(!formatModified) formatter = anyFormatter;
- //if(!((formatter!=null && formatter!=anyFormatter) || (defaultFormatter!=null && formatter!=defaultFormatter)))
- // formatter = anyFormatter;
- //formatter.setFormatId(anyFormatter.getFormatId());
- }
- /*else if ((fmt.getLessThanValue().length() <= 0)
- && (fmt.getFormatId().length() > 0)) {
- formatter = (HtmlFormatter) formatters.get(fmt.getFormatId());
- System.out.println("---------------lesser "+ fmt.getFormatId()+ " " + fmt.getBgColor());
- dv.setFormatId(fmt.getFormatId());
- dr.setFormatId(fmt.getFormatId());
- // break;
- } // else if*/
- } // for
- /*} else {
- for (Iterator iter = semaphore.getFormatList().getFormat().iterator(); iter
- .hasNext();) {
- FormatType fmt = (FormatType) iter.next();
- if(fmt.getLessThanValue().length()<=0 && fmt.getExpression().length()<=0 && !fmt.isBold() && !fmt.isItalic() && !fmt.isUnderline() && fmt.getFontSize().equals("11")) {
- formatter = defaultFormatter;
- } else
- formatter = anyFormatter;
- }
-
- //formatter.setFormatId(anyFormatter.getFormatId());
- } */
- if(formatter != null) {
- if (semaphore.getSemaphoreType().equals(AppConstants.ST_ROW)) {
-
- if (dr.getRowFormatter() == null || formatter != defaultFormatter) {
- // Making sure the default formatter doesn't overwrite
- // valid row formatter set from another column
- dr.setRowFormatter(formatter);
- dr.setFormatId(formatter.getFormatId());
- // This is added for excel download
- //if (!formatter.equals(defaultFormatter)) {
- dr.setRowFormat(true);
- //}
-
- }
- } else {
- if(nvl(targetColId).length()>0) {
- if(targetDataValue!=null) {
- targetDataValue.setCellFormatter(formatter);
- targetDataValue.setFormatId(formatter.getFormatId());
- //if (!formatter.equals(defaultFormatter)) {
- targetDataValue.setCellFormat(true);
- int count = 0;
- for (dr.resetNext(); dr.hasNext();) {
- DataValue dv1 = dr.getNext();
- //add null check
- if(targetColId!=null) {
- if(dv1.getColId().equals(targetColId))
- dr.setDataValue(count, targetDataValue);
- }
- count++;
- }
- }
- //}
-
- } else {
- dv.setCellFormatter(formatter);
- dv.setFormatId(formatter.getFormatId());
- //if (!formatter.equals(defaultFormatter)) {
- dv.setCellFormat(true);
- //}
- }
- }// else
- }
- } // setHtmlFormatters
-
-} // FormatProcessor
+++ /dev/null
-/*-
- * ================================================================================
- * 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 Item {
- private String _id;
- private String _name;
-
- public Item() {
- }
-
- public Item(String id, String name) {
- this._id = id;
- this._name = 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;
- }
-
- public String toString() {
- return _name;
- }
-}
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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 org.openecomp.portalsdk.analytics.RaptorObject;
-
-public class LookupDBInfo extends RaptorObject {
- private String tableName = null;
-
- private String fieldName = null;
-
- private String lookupTable = null;
-
- private String lookupIdField = null;
-
- private String lookupNameField = null;
-
- public LookupDBInfo() {
- }
-
- public LookupDBInfo(String tableName, String fieldName, String lookupTable,
- String lookupIdField, String lookupNameField) {
- this();
-
- setTableName(tableName);
- setFieldName(fieldName);
- setLookupTable(lookupTable);
- setLookupIdField(lookupIdField);
- setLookupNameField(lookupNameField);
- } // LookupDBInfo
-
- public String getTableName() {
- return tableName;
- }
-
- public String getFieldName() {
- return fieldName;
- }
-
- public String getLookupTable() {
- return lookupTable;
- }
-
- public String getLookupIdField() {
- return lookupIdField;
- }
-
- public String getLookupNameField() {
- return lookupNameField;
- }
-
- public void setTableName(String tableName) {
- this.tableName = tableName;
- }
-
- public void setFieldName(String fieldName) {
- this.fieldName = fieldName;
- }
-
- public void setLookupTable(String lookupTable) {
- this.lookupTable = lookupTable;
- }
-
- public void setLookupIdField(String lookupIdField) {
- this.lookupIdField = lookupIdField;
- }
-
- public void setLookupNameField(String lookupNameField) {
- this.lookupNameField = lookupNameField;
- }
-
-} // LookupDBInfo
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
-
-class RangeColorJSON extends IndexValueJSON {}
-class RangeAxisLabelJSON extends IndexValueJSON {}
-class RangeLineTypeJSON extends IndexValueJSON {}
-
-public class RangeAxisJSON {
-
- private RangeAxisLabelJSON rangeAxisLabelJSON;
- private RangeColorJSON rangeColorJSON;
- private RangeLineTypeJSON rangeLineTypeJSON;
- private String rangeChartGroup;
- private String rangeYAxis;
- private boolean showAsArea;
-
- public RangeAxisLabelJSON getRangeAxisLabelJSON() {
- return rangeAxisLabelJSON;
- }
- public void setRangeAxisLabelJSON(RangeAxisLabelJSON rangeAxisLabelJSON) {
- this.rangeAxisLabelJSON = rangeAxisLabelJSON;
- }
- public RangeColorJSON getRangeColorJSON() {
- return rangeColorJSON;
- }
- public void setRangeColorJSON(RangeColorJSON rangeColorJSON) {
- this.rangeColorJSON = rangeColorJSON;
- }
- public RangeLineTypeJSON getRangeLineTypeJSON() {
- return rangeLineTypeJSON;
- }
- public void setRangeLineTypeJSON(RangeLineTypeJSON rangeLineTypeJSON) {
- this.rangeLineTypeJSON = rangeLineTypeJSON;
- }
- public String getRangeChartGroup() {
- return rangeChartGroup;
- }
- public void setRangeChartGroup(String rangeChartGroup) {
- this.rangeChartGroup = rangeChartGroup;
- }
- public String getRangeYAxis() {
- return rangeYAxis;
- }
- public void setRangeYAxis(String rangeYAxis) {
- this.rangeYAxis = rangeYAxis;
- }
- public boolean isShowAsArea() {
- return showAsArea;
- }
- public void setShowAsArea(boolean showAsArea) {
- this.showAsArea = showAsArea;
- }
-
- public String getRangeAxis() {
- if(getRangeAxisLabelJSON()!=null)
- return getRangeAxisLabelJSON().getValue();
- else
- return "";
- }
-
- public String getRangeColor(){
- if(getRangeColorJSON()!=null)
- return getRangeColorJSON().getValue();
- else
- return "";
- }
-
- public String getRangeLineType(){
- if(getRangeLineTypeJSON()!=null)
- return getRangeLineTypeJSON().getValue();
- else
- return "";
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.*;
-import javax.servlet.http.*;
-
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.model.*;
-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.analytics.xmlobj.*;
-
-public class ReportFormFields extends Vector {
- private int nextElemIdx = 0;
-
- public ReportFormFields(ReportWrapper rw, HttpServletRequest request) throws RaptorException {
- super();
-
- if (rw.getFormFieldList() != null)
- for (Iterator iter = rw.getFormFieldList().getFormField().iterator(); iter
- .hasNext();) {
- FormFieldType fft = (FormFieldType) iter.next();
-
- String fieldName = fft.getFieldId();
- String fieldDisplayName = fft.getFieldName();
- String fieldType = fft.getFieldType();
- String validationType = fft.getValidationType();
- String mandatory = nvl(fft.getMandatory(), "N");
- String defaultValue = fft.getDefaultValue();
- String fieldSQL = fft.getFieldSQL();
- String fieldDefaultSQL = fft.getFieldDefaultSQL();
- String[] reqParameters = Globals.getRequestParams().split(",");
- String[] sessionParameters = Globals.getSessionParams().split(",");
- String[] scheduleSessionParameters = Globals.getSessionParamsForScheduling().split(",");
- javax.servlet.http.HttpSession session = request.getSession();
- String visible = nvl(fft.getVisible(),"Y");
- String dependsOn = nvl(fft.getDependsOn(), "");
- Calendar rangeStartDate = (fft.getRangeStartDate()==null)?null:fft.getRangeStartDate().toGregorianCalendar();
- Calendar rangeEndDate = (fft.getRangeEndDate()==null)?null:fft.getRangeEndDate().toGregorianCalendar();
- //Calendar rangeEndDate = fft.getRangeEndDate().toGregorianCalendar();
- String rangeStartDateSQL = fft.getRangeStartDateSQL();
- String rangeEndDateSQL = fft.getRangeEndDateSQL();
- String user_id = AppUtils.getUserID(request);
- String multiSelectListSize = fft.getMultiSelectListSize();
-
- //s_logger.debug("ranges are : " + fft.getRangeStartDate() + fft.getRangeEndDate());
- //s_logger.debug("fieldSQL B4" + fieldSQL);
- if(fieldSQL!=null) {
- for (int i = 0; i < reqParameters.length; i++) {
- if(!reqParameters[i].startsWith("ff") && (request.getParameter(reqParameters[i].toUpperCase())!=null && request.getParameter(reqParameters[i].toUpperCase()).length() > 0))
- fieldSQL = Utils.replaceInString(fieldSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
- else if (request.getParameter(reqParameters[i])!=null && request.getParameter(reqParameters[i]).length() > 0)
- fieldSQL = Utils.replaceInString(fieldSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
- }
-
- for (int i = 0; i < scheduleSessionParameters.length; i++) {
- //s_logger.debug(" Session " + " scheduleSessionParameters[i] " + scheduleSessionParameters[i].toUpperCase() + " " + request.getParameter(scheduleSessionParameters[i]));
- if(request.getParameter(scheduleSessionParameters[i])!=null && request.getParameter(scheduleSessionParameters[i]).trim().length()>0 )
- fieldSQL = Utils.replaceInString(fieldSQL, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) );
- if(request.getAttribute(scheduleSessionParameters[i])!=null && ((String)request.getAttribute(scheduleSessionParameters[i])).trim().length()>0 )
- fieldSQL = Utils.replaceInString(fieldSQL, "[" + scheduleSessionParameters[i].toUpperCase()+"]", (String) request.getAttribute(scheduleSessionParameters[i]) );
-
- }
-
- for (int i = 0; i < sessionParameters.length; i++) {
- //if(!sessionParameters[i].startsWith("ff"))
- //fieldSQL = Utils.replaceInString(fieldSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) );
- //else {
- if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0) {
- //s_logger.debug(" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i]));
- fieldSQL = Utils.replaceInString(fieldSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
- }
- // }
- }
- fieldSQL = Utils.replaceInString(fieldSQL, "[USERID]", user_id);
- fieldSQL = Utils.replaceInString(fieldSQL, "[USER_ID]", user_id);
- fieldSQL = Utils.replaceInString(fieldSQL, "[LOGGED_USERID]", user_id);
-
- }
-
- if(fieldDefaultSQL!=null) {
- for (int i = 0; i < reqParameters.length; i++) {
- if(!reqParameters[i].startsWith("ff") && (request.getParameter(reqParameters[i].toUpperCase())!=null && request.getParameter(reqParameters[i].toUpperCase()).length() > 0))
- fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
- else if (request.getParameter(reqParameters[i])!=null && request.getParameter(reqParameters[i]).length() > 0)
- fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
- }
- for (int i = 0; i < scheduleSessionParameters.length; i++) {
- //s_logger.debug(" Session " + " scheduleSessionParameters[i] " + scheduleSessionParameters[i].toUpperCase() + " " + request.getParameter(scheduleSessionParameters[i]));
- if(request.getParameter(scheduleSessionParameters[i])!=null && request.getParameter(scheduleSessionParameters[i]).trim().length()>0 )
- fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) );
- if(request.getAttribute(scheduleSessionParameters[i])!=null && ((String)request.getAttribute(scheduleSessionParameters[i])).trim().length()>0 )
- fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + scheduleSessionParameters[i].toUpperCase()+"]", (String) request.getAttribute(scheduleSessionParameters[i]) );
-
- }
-
- for (int i = 0; i < sessionParameters.length; i++) {
- //if(!sessionParameters[i].startsWith("ff"))
- //fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) );
- //else
- if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0)
- fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
- }
-
- fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[USERID]", user_id);
- fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[USER_ID]", user_id);
- fieldDefaultSQL = Utils.replaceInString(fieldDefaultSQL, "[LOGGED_USERID]", user_id);
- }
- //s_logger.debug("fieldSQL After" + fieldSQL);
- if(rangeStartDateSQL!=null) {
- for (int i = 0; i < reqParameters.length; i++) {
- if(!reqParameters[i].startsWith("ff") && (request.getParameter(reqParameters[i].toUpperCase())!=null && request.getParameter(reqParameters[i].toUpperCase()).length() > 0))
- rangeStartDateSQL = Utils.replaceInString(rangeStartDateSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
- else if (request.getParameter(reqParameters[i])!=null && request.getParameter(reqParameters[i]).length() > 0)
- rangeStartDateSQL = Utils.replaceInString(rangeStartDateSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
- }
- for (int i = 0; i < sessionParameters.length; i++) {
- if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0)
- rangeStartDateSQL = Utils.replaceInString(rangeStartDateSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
- }
- }
- if(rangeEndDateSQL!=null) {
- for (int i = 0; i < reqParameters.length; i++) {
- if(!reqParameters[i].startsWith("ff")&& (request.getParameter(reqParameters[i].toUpperCase())!=null && request.getParameter(reqParameters[i].toUpperCase()).length() > 0))
- rangeEndDateSQL = Utils.replaceInString(rangeEndDateSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
- else if (request.getParameter(reqParameters[i])!=null && request.getParameter(reqParameters[i]).length() > 0)
- rangeEndDateSQL = Utils.replaceInString(rangeEndDateSQL, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
- }
- for (int i = 0; i < sessionParameters.length; i++) {
- if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0)
- rangeEndDateSQL = Utils.replaceInString(rangeEndDateSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
- }
- }
- String helpText = fft.getComment();
-
- List predefinedValues = null;
- if (fft.getPredefinedValueList() != null) {
- predefinedValues = fft.getPredefinedValueList().getPredefinedValue();
- if (predefinedValues.size() == 0)
- predefinedValues = null;
- } // if
-
- DataColumnType dct = rw.getColumnById(nvl(fft.getColId()));
-
- boolean basedOnColumn = false;
- if (rw.getReportDefType().equals(AppConstants.RD_SQL_BASED))
- basedOnColumn = (nvl(fft.getColId()).indexOf('.') > 0);
- else
- basedOnColumn = (dct != null);
-
- if (((!basedOnColumn) && (nvl(fieldSQL).length() == 0))
- || predefinedValues != null) {
- if (predefinedValues != null)
- if (nvl(defaultValue).equals(AppConstants.FILTER_MAX_VALUE))
- defaultValue = (String) Collections.max(predefinedValues);
- else if (nvl(defaultValue).equals(AppConstants.FILTER_MIN_VALUE))
- defaultValue = (String) Collections.min(predefinedValues);
- add(new FormField(fieldName, fieldDisplayName, fieldType, validationType,
- mandatory.equals("Y"), defaultValue, helpText, predefinedValues,visible.equals("Y"), dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize));
- } else if (nvl(fieldSQL).length() > 0) {
- add(new FormField(fieldName, fieldDisplayName, fieldType, validationType,
- mandatory.equals("Y"), fieldDefaultSQL, helpText, fieldSQL,visible.equals("Y"), dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize));
- } else {
- String lTableName = null;
- String lColumnName = null;
- String lColumnType = null;
- String lColFormat = null;
- if (rw.getReportDefType().equals(AppConstants.RD_SQL_BASED)) {
- String colId = nvl(fft.getColId());
- lTableName = ReportWrapper.getSQLBasedFFTColTableName(colId); // colId.substring(0,
- // colId.indexOf('.'));
- lColumnName = ReportWrapper.getSQLBasedFFTColColumnName(colId); // colId.substring(colId.lastIndexOf('.')+1);
- lColumnType = AppConstants.CT_CHAR;
- try {
- lColumnType = nvl(DataCache.getReportTableDbColumnType(lTableName,
- lColumnName, rw.getDBInfo()), AppConstants.CT_CHAR);
- } catch (Exception e) {
- }
- lColFormat = lColumnType.equals(AppConstants.CT_DATE) ? nvl(
- ReportWrapper.getSQLBasedFFTColDisplayFormat(colId),
- AppConstants.DEFAULT_DATE_FORMAT) : "";
- } else {
- lTableName = rw.getColumnTableById(dct.getColId()).getTableName(); // should
- // be
- // same
- // as
- // rw.getTableById(dct.getTableId()).getTableName()
- lColumnName = dct.getColName();
- lColumnType = dct.getColType();
- lColFormat = nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT);
- } // else
-
- if (nvl(defaultValue).equals(AppConstants.FILTER_MAX_VALUE)
- || nvl(defaultValue).equals(AppConstants.FILTER_MIN_VALUE))
- try {
- String selectVal = (defaultValue
- .equals(AppConstants.FILTER_MAX_VALUE) ? "MAX" : "MIN")
- + "(" + lColumnName + ")";
- if (lColumnType.equals(AppConstants.CT_DATE))
- selectVal = "TO_CHAR(" + selectVal + ", '"
- + AppConstants.DEFAULT_DATE_FORMAT + "')";
- // DataSet ds = DbUtils.executeQuery("SELECT
- // "+selectVal+" FROM "+lTableName);
- DataSet ds = ConnectionUtils.getDataSet("SELECT " + selectVal
- + " FROM " + lTableName, rw.getDBInfo());
- if (ds.getRowCount() > 0)
- defaultValue = ds.getString(0, 0);
- } catch (Exception e) {
- }
-
- LookupDBInfo lookupDBInfo = DataCache.getLookupTable(lTableName,
- lColumnName);
- String lookupTable = lookupDBInfo.getLookupTable();
- String lookupIdField = lookupDBInfo.getLookupIdField();
- String lookupNameField = lookupDBInfo.getLookupNameField();
- String lookupSortByField = lookupDBInfo.getLookupNameField();
- if (lColumnType.equals(AppConstants.CT_DATE)) {
- // Expects lookup on DATE fields will have both Id and
- // Name fields with DATE format; if not the case will
- // generate an error
- lookupIdField = "TO_CHAR(" + lookupIdField + ", '"
- + AppConstants.DEFAULT_DATE_FORMAT + "')";
- lookupSortByField = " TO_DATE(TO_CHAR("+ lookupNameField +", '" + AppConstants.DEFAULT_DATE_FORMAT+ "'),'" + AppConstants.DEFAULT_DATE_FORMAT+ "') ";
- lookupNameField = "TO_CHAR(" + lookupNameField + ", '" + lColFormat
- + "')";
- lookupSortByField += " DESC";
- } // if
- if (fieldDefaultSQL!=null && fieldDefaultSQL.length()>0 && (fieldDefaultSQL.trim().length()>10) && fieldDefaultSQL.substring(0,10).toLowerCase().startsWith("select")) {
- add(new FormField(fieldName, fieldDisplayName, fieldType, validationType,
- mandatory.equals("Y"), fieldDefaultSQL, helpText, lookupTable,
- lookupIdField, lookupNameField, lookupSortByField,visible.equals("Y"),dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize));
-
- } else {
- add(new FormField(fieldName, fieldDisplayName, fieldType, validationType,
- mandatory.equals("Y"), defaultValue, helpText, lookupTable,
- lookupIdField, lookupNameField, lookupSortByField,visible.equals("Y"), dependsOn, rangeStartDate, rangeEndDate, rangeStartDateSQL, rangeEndDateSQL, multiSelectListSize));
- }
- } // else
- } // for
-
- List reportCols = rw.getAllColumns();
- for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
- DataColumnType dct = (DataColumnType) iter.next();
-
- if (dct.getColFilterList() != null) {
- int fNo = 0;
- List fList = dct.getColFilterList().getColFilter();
- for (Iterator iterF = fList.iterator(); iterF.hasNext(); fNo++) {
- ColFilterType cft = (ColFilterType) iterF.next();
-
- if (nvl(cft.getArgType()).equals(AppConstants.AT_FORM)
- && rw.getFormFieldByDisplayValue(cft.getArgValue()) == null) {
- String fieldName = rw.getFormFieldName(cft);
- String fieldDisplayName = rw.getFormFieldDisplayName(dct, cft);
-
- LookupDBInfo lookupDBInfo = DataCache.getLookupTable(rw
- .getColumnTableById(dct.getColId()).getTableName(), dct
- .getColName());
- String lookupTable = lookupDBInfo.getLookupTable();
- String lookupIdField = lookupDBInfo.getLookupIdField();
- String lookupNameField = lookupDBInfo.getLookupNameField();
- String lookupSortByField = lookupDBInfo.getLookupNameField();
- Calendar lookupRangeStartDate = rw.getFormFieldRangeStart(cft);
- Calendar lookupRangeEndDate = rw.getFormFieldRangeEnd(cft);
- String lookupRangeStartDateSQL = rw.getFormFieldRangeStartSQL(cft);
- String lookupRangeEndDateSQL = rw.getFormFieldRangeEndSQL(cft);
- if (dct.getColType().equals(AppConstants.CT_DATE)) {
- // Expects lookup on DATE fields will have both Id
- // and Name fields with DATE format; if not the case
- // will generate an error
- lookupIdField = "TO_CHAR("
- + lookupIdField
- + ", '"
- + nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT)
- + "')";
- lookupNameField = "TO_CHAR("
- + lookupNameField
- + ", '"
- + nvl(dct.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT)
- + "')";
- lookupSortByField += " DESC";
- } // if
- add(new FormField(fieldName, fieldDisplayName,
- FormField.FFT_TEXT_W_POPUP, null, false, null, null,
- lookupTable, lookupIdField, lookupNameField, lookupSortByField,null, lookupRangeStartDate, lookupRangeEndDate, lookupRangeStartDateSQL, lookupRangeEndDateSQL, "0"));
- } // if
- } // for
- } // if
- } // for
- } // ReportFormFields
-
- public int getFieldCount() {
- return size();
- } // getFieldCount
-
- public FormField getFormField(int fieldIdx) {
- return (FormField) get(fieldIdx);
- } // getFormField
-
- public FormField getFormField(String fieldName) {
- for (int i = 0; i < getFieldCount(); i++) {
- FormField ff = (FormField) get(i);
- if (ff.getFieldName().equals(fieldName))
- return ff;
- } // for
-
- return null;
- } // getFormField
-
- public void resetNext() {
- resetNext(0);
- } // resetNext
-
- public void resetNext(int toPos) {
- nextElemIdx = toPos;
- } // resetNext
-
- public boolean hasNext() {
- return (nextElemIdx < size());
- } // hasNext
-
- public FormField getNext() {
- return hasNext() ? getFormField(nextElemIdx++) : null;
- } // getNext
-
- /** ************************************************************************************************* */
-
- private String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- private String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
-} // ReportFormFields
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
-
-/*class MetaColumn {
- private String tableId;
- private String dbColName;
- private String crossTabValue;
- private String colName;
- private String displayName;
- private Integer displayWidth;
- private String displayWidthInPxls;
- private String pdfDisplayWidthInPxls;
- private String displayAlignment;
- private String displayHeaderAlignment;
- private int orderSeq;
- private boolean visible;
- private boolean calculated;
- private String colType;
- private String hyperlinkURL;
- private String hyperlinkType;
- private String actionImg;
- private Integer groupByPos;
- private String subTotalCustomText;
- private Boolean hideRepeatedKey;
- private String colFormat;
- private boolean groupBreak;
- private Integer orderBySeq;
- private String orderByAscDesc;
- private String displayTotal;
- private String colOnChart;
- private Integer chartSeq;
- private String chartColor;
- private String chartLineType;
- private Boolean chartSeries;
- private Boolean isRangeAxisFilled;
- private Boolean createInNewChart;
- private String drillDownType;
- private Boolean drillinPoPUp;
- private String drillDownURL;
- private String drillDownParams;
- private String comment;
- private ColFilterList colFilterList;
- private String semaphoreId;
- private String dbColType;
- private String chartGroup;
- private String yAxis;
- private String dependsOnFormField;
- private String nowrap;
- private Integer indentation;
- private Boolean enhancedPagination;
- private Integer level;
- private Integer start;
- private Integer colspan;
- private String dataMiningCol;
- private String colId;
-
- public String getTableId() {
- return tableId;
- }
- public void setTableId(String tableId) {
- this.tableId = tableId;
- }
- public String getDbColName() {
- return dbColName;
- }
- public void setDbColName(String dbColName) {
- this.dbColName = dbColName;
- }
- public String getCrossTabValue() {
- return crossTabValue;
- }
- public void setCrossTabValue(String crossTabValue) {
- this.crossTabValue = crossTabValue;
- }
- public String getColName() {
- return colName;
- }
- public void setColName(String colName) {
- this.colName = colName;
- }
- public String getDisplayName() {
- return displayName;
- }
- public void setDisplayName(String displayName) {
- this.displayName = displayName;
- }
- public Integer getDisplayWidth() {
- return displayWidth;
- }
- public void setDisplayWidth(Integer displayWidth) {
- this.displayWidth = displayWidth;
- }
- public String getDisplayWidthInPxls() {
- return displayWidthInPxls;
- }
- public void setDisplayWidthInPxls(String displayWidthInPxls) {
- this.displayWidthInPxls = displayWidthInPxls;
- }
- public String getPdfDisplayWidthInPxls() {
- return pdfDisplayWidthInPxls;
- }
- public void setPdfDisplayWidthInPxls(String pdfDisplayWidthInPxls) {
- this.pdfDisplayWidthInPxls = pdfDisplayWidthInPxls;
- }
- 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 int getOrderSeq() {
- return orderSeq;
- }
- public void setOrderSeq(int orderSeq) {
- this.orderSeq = orderSeq;
- }
- public boolean isVisible() {
- return visible;
- }
- public void setVisible(boolean visible) {
- this.visible = visible;
- }
- public boolean isCalculated() {
- return calculated;
- }
- public void setCalculated(boolean calculated) {
- this.calculated = calculated;
- }
- public String getColType() {
- return colType;
- }
- public void setColType(String colType) {
- this.colType = colType;
- }
- public String getHyperlinkURL() {
- return hyperlinkURL;
- }
- public void setHyperlinkURL(String hyperlinkURL) {
- this.hyperlinkURL = hyperlinkURL;
- }
- public String getHyperlinkType() {
- return hyperlinkType;
- }
- public void setHyperlinkType(String hyperlinkType) {
- this.hyperlinkType = hyperlinkType;
- }
- public String getActionImg() {
- return actionImg;
- }
- public void setActionImg(String actionImg) {
- this.actionImg = actionImg;
- }
- public Integer getGroupByPos() {
- return groupByPos;
- }
- public void setGroupByPos(Integer groupByPos) {
- this.groupByPos = groupByPos;
- }
- public String getSubTotalCustomText() {
- return subTotalCustomText;
- }
- public void setSubTotalCustomText(String subTotalCustomText) {
- this.subTotalCustomText = subTotalCustomText;
- }
- public Boolean getHideRepeatedKey() {
- return hideRepeatedKey;
- }
- public void setHideRepeatedKey(Boolean hideRepeatedKey) {
- this.hideRepeatedKey = hideRepeatedKey;
- }
- public String getColFormat() {
- return colFormat;
- }
- public void setColFormat(String colFormat) {
- this.colFormat = colFormat;
- }
- public boolean isGroupBreak() {
- return groupBreak;
- }
- public void setGroupBreak(boolean groupBreak) {
- this.groupBreak = groupBreak;
- }
- public Integer getOrderBySeq() {
- return orderBySeq;
- }
- public void setOrderBySeq(Integer orderBySeq) {
- this.orderBySeq = orderBySeq;
- }
- public String getOrderByAscDesc() {
- return orderByAscDesc;
- }
- public void setOrderByAscDesc(String orderByAscDesc) {
- this.orderByAscDesc = orderByAscDesc;
- }
- public String getDisplayTotal() {
- return displayTotal;
- }
- public void setDisplayTotal(String displayTotal) {
- this.displayTotal = displayTotal;
- }
- public String getColOnChart() {
- return colOnChart;
- }
- public void setColOnChart(String colOnChart) {
- this.colOnChart = colOnChart;
- }
- public Integer getChartSeq() {
- return chartSeq;
- }
- public void setChartSeq(Integer chartSeq) {
- this.chartSeq = chartSeq;
- }
- public String getChartColor() {
- return chartColor;
- }
- public void setChartColor(String chartColor) {
- this.chartColor = chartColor;
- }
- public String getChartLineType() {
- return chartLineType;
- }
- public void setChartLineType(String chartLineType) {
- this.chartLineType = chartLineType;
- }
- public Boolean getChartSeries() {
- return chartSeries;
- }
- public void setChartSeries(Boolean chartSeries) {
- this.chartSeries = chartSeries;
- }
- public Boolean getIsRangeAxisFilled() {
- return isRangeAxisFilled;
- }
- public void setIsRangeAxisFilled(Boolean isRangeAxisFilled) {
- this.isRangeAxisFilled = isRangeAxisFilled;
- }
- public Boolean getCreateInNewChart() {
- return createInNewChart;
- }
- public void setCreateInNewChart(Boolean createInNewChart) {
- this.createInNewChart = createInNewChart;
- }
- public String getDrillDownType() {
- return drillDownType;
- }
- public void setDrillDownType(String drillDownType) {
- this.drillDownType = drillDownType;
- }
- public Boolean getDrillinPoPUp() {
- return drillinPoPUp;
- }
- public void setDrillinPoPUp(Boolean drillinPoPUp) {
- this.drillinPoPUp = drillinPoPUp;
- }
- 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 getComment() {
- return comment;
- }
- public void setComment(String comment) {
- this.comment = comment;
- }
- public ColFilterList getColFilterList() {
- return colFilterList;
- }
- public void setColFilterList(ColFilterList colFilterList) {
- this.colFilterList = colFilterList;
- }
- public String getSemaphoreId() {
- return semaphoreId;
- }
- public void setSemaphoreId(String semaphoreId) {
- this.semaphoreId = semaphoreId;
- }
- public String getDbColType() {
- return dbColType;
- }
- public void setDbColType(String dbColType) {
- this.dbColType = dbColType;
- }
- public String getChartGroup() {
- return chartGroup;
- }
- public void setChartGroup(String chartGroup) {
- this.chartGroup = chartGroup;
- }
- public String getyAxis() {
- return yAxis;
- }
- public void setyAxis(String yAxis) {
- this.yAxis = yAxis;
- }
- public String getDependsOnFormField() {
- return dependsOnFormField;
- }
- public void setDependsOnFormField(String dependsOnFormField) {
- this.dependsOnFormField = dependsOnFormField;
- }
- public String getNowrap() {
- return nowrap;
- }
- public void setNowrap(String nowrap) {
- this.nowrap = nowrap;
- }
- public Integer getIndentation() {
- return indentation;
- }
- public void setIndentation(Integer indentation) {
- this.indentation = indentation;
- }
- public Boolean getEnhancedPagination() {
- return enhancedPagination;
- }
- public void setEnhancedPagination(Boolean enhancedPagination) {
- this.enhancedPagination = enhancedPagination;
- }
- public Integer getLevel() {
- return level;
- }
- public void setLevel(Integer level) {
- this.level = level;
- }
- public Integer getStart() {
- return start;
- }
- public void setStart(Integer start) {
- this.start = start;
- }
- public Integer getColspan() {
- return colspan;
- }
- public void setColspan(Integer colspan) {
- this.colspan = colspan;
- }
- public String getDataMiningCol() {
- return dataMiningCol;
- }
- public void setDataMiningCol(String dataMiningCol) {
- this.dataMiningCol = dataMiningCol;
- }
- public String getColId() {
- return colId;
- }
- public void setColId(String colId) {
- this.colId = colId;
- }
-
-}*/
-
-/*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 FormFieldJSON {
- private String fieldId;
- private String fieldDisplayName;
- private String fieldType;
- private String validationType;
- private boolean required;
- //private String defaultValue;
-
- private Calendar rangeStartDate;
- private Calendar rangeEndDate;
- private String multiSelectListSize;
- private String helpText;
- private boolean visible;
- private boolean triggerOtherFormFields;
- private ArrayList<IdNameValue> formFieldValues;
-
- public String getFieldId() {
- return fieldId;
- }
- public void setFieldId(String fieldId) {
- this.fieldId = fieldId;
- }
- public String getFieldDisplayName() {
- return fieldDisplayName;
- }
- public void setFieldDisplayName(String fieldDisplayName) {
- this.fieldDisplayName = fieldDisplayName;
- }
- public String getFieldType() {
- return fieldType;
- }
- public void setFieldType(String fieldType) {
- this.fieldType = fieldType;
- }
- public String getValidationType() {
- return validationType;
- }
- public void setValidationType(String validationType) {
- this.validationType = validationType;
- }
- public boolean isRequired() {
- return required;
- }
- public void setRequired(boolean required) {
- this.required = required;
- }
- public Calendar getRangeStartDate() {
- return rangeStartDate;
- }
- public void setRangeStartDate(Calendar rangeStartDate) {
- this.rangeStartDate = rangeStartDate;
- }
- public Calendar getRangeEndDate() {
- return rangeEndDate;
- }
- public void setRangeEndDate(Calendar rangeEndDate) {
- this.rangeEndDate = rangeEndDate;
- }
- public String getMultiSelectListSize() {
- return multiSelectListSize;
- }
- public void setMultiSelectListSize(String multiSelectListSize) {
- this.multiSelectListSize = multiSelectListSize;
- }
- public String getHelpText() {
- return helpText;
- }
- public void setHelpText(String helpText) {
- this.helpText = helpText;
- }
- public boolean isVisible() {
- return visible;
- }
- public void setVisible(boolean visible) {
- this.visible = visible;
- }
- public boolean isTriggerOtherFormFields() {
- return triggerOtherFormFields;
- }
- public void setTriggerOtherFormFields(boolean triggerOtherFormFields) {
- this.triggerOtherFormFields = triggerOtherFormFields;
- }
- public ArrayList<IdNameValue> getFormFieldValues() {
- return formFieldValues;
- }
- public void setFormFieldValues(ArrayList<IdNameValue> formFieldValues) {
- this.formFieldValues = formFieldValues;
- }
-
-
-}
-public class ReportJSONRuntime {
-
- private String reportID;
- private String reportName;
- private String reportDescr;
- private String reportTitle;
- private String reportSubTitle;
- private boolean allowSchedule;
- private boolean allowEdit;
- private ArrayList <FormFieldJSON> formFieldList;
- private String formfield_comments;
- private ArrayList<ColumnHeader> reportDataColumns;
- private ArrayList<Map<String,Object>> reportDataRows;
- private int totalRows;
- private int pageSize;
- private String sqlWhole;
- private boolean chartAvailable;
- private boolean chartWizardAvailable;
- private boolean displayData;
- private boolean displayForm;
- private boolean displayExcel;
- private boolean displayPDF;
- private String backBtnURL;
- private String colIdxTobeFreezed;
- private int numFormCols;
- private String message;
- private boolean hideFormFieldsAfterRun;
-
-
- public boolean isChartAvailable() {
- return chartAvailable;
- }
- public void setChartAvailable(boolean chartAvailable) {
- this.chartAvailable = chartAvailable;
- }
- public ArrayList<Map<String,Object>> getReportDataRows() {
- return reportDataRows;
- }
- public void setReportDataRows(ArrayList<Map<String,Object>> reportDataRows) {
- this.reportDataRows = reportDataRows;
- }
- 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 boolean isAllowSchedule() {
- return allowSchedule;
- }
- public void setAllowSchedule(boolean allowSchedule) {
- this.allowSchedule = allowSchedule;
- }
- 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 ArrayList<ColumnHeader> getReportDataColumns() {
- return reportDataColumns;
- }
- public void setReportDataColumns(ArrayList<ColumnHeader> reportDataColumns) {
- this.reportDataColumns = reportDataColumns;
- }
-
- public int getTotalRows() {
- return totalRows;
- }
- public void setTotalRows(int totalRows) {
- this.totalRows = totalRows;
- }
- public int getPageSize() {
- return pageSize;
- }
- public void setPageSize(int pageSize) {
- this.pageSize = pageSize;
- }
- public String getSqlWhole() {
- return sqlWhole;
- }
- public void setSqlWhole(String sqlWhole) {
- this.sqlWhole = sqlWhole;
- }
-
- public boolean isAllowEdit() {
- return allowEdit;
- }
- public void setAllowEdit(boolean allowEdit) {
- this.allowEdit = allowEdit;
- }
- public String getBackBtnURL() {
- return backBtnURL;
- }
- public void setBackBtnURL(String backBtnURL) {
- this.backBtnURL = backBtnURL;
- }
- public String getColIdxTobeFreezed() {
- return colIdxTobeFreezed;
- }
- public void setColIdxTobeFreezed(String colIdxTobeFreezed) {
- this.colIdxTobeFreezed = colIdxTobeFreezed;
- }
- public int getNumFormCols() {
- return numFormCols;
- }
- public void setNumFormCols(int numFormCols) {
- this.numFormCols = numFormCols;
- }
- public boolean isDisplayData() {
- return displayData;
- }
- public void setDisplayData(boolean displayData) {
- this.displayData = displayData;
- }
- public boolean isDisplayForm() {
- return displayForm;
- }
- public void setDisplayForm(boolean displayForm) {
- this.displayForm = displayForm;
- }
- public boolean isDisplayExcel() {
- return displayExcel;
- }
- public void setDisplayExcel(boolean displayExcel) {
- this.displayExcel = displayExcel;
- }
- public boolean isDisplayPDF() {
- return displayPDF;
- }
- public void setDisplayPDF(boolean displayPDF) {
- this.displayPDF = displayPDF;
- }
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
- public boolean isChartWizardAvailable() {
- return chartWizardAvailable;
- }
- public void setChartWizardAvailable(boolean chartWizardAvilable) {
- this.chartWizardAvailable = chartWizardAvilable;
- }
- public boolean isHideFormFieldsAfterRun() {
- return hideFormFieldsAfterRun;
- }
- public void setHideFormFieldsAfterRun(boolean hideFormFieldsAfterRun) {
- this.hideFormFieldsAfterRun = hideFormFieldsAfterRun;
- }
-
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.*;
-import javax.servlet.http.*;
-
-import org.openecomp.portalsdk.analytics.model.base.*;
-import org.openecomp.portalsdk.analytics.system.Globals;
-import org.openecomp.portalsdk.analytics.util.*;
-import org.openecomp.portalsdk.analytics.xmlobj.*;
-
-public class ReportParamDateValueParser {
-
- /*public static final SimpleDateFormat[] dateFormats;
-
- static {
- dateFormats = new SimpleDateFormat[5];
- (dateFormats[0] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MONTHYYYY))
- .setLenient(true);
- (dateFormats[1] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MONTHDDYYYY))
- .setLenient(true);
- (dateFormats[2] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMDDYYYY))
- .setLenient(true);
- (dateFormats[3] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMYYYY))
- .setLenient(true);
- (dateFormats[4] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_DDMONYYYY))
- .setLenient(true);
- }*/
-
- public static boolean isDateHrParam(String param) {
- SimpleDateFormat[] dateFormats = new SimpleDateFormat[2];
- (dateFormats[0] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMDDYYYY_HR))
- .setLenient(true);
- (dateFormats[1] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_DDMONYYYY_HR))
- .setLenient(true);
- for (int i = 0; i < dateFormats.length; i++) {
- try {
- if (dateFormats[i].parse(param) != null) {
- return true;
- }
- } catch (ParseException pe) {
- // do nothing, continue to check param against other dates
- }
- catch (NumberFormatException pe) {
- // do nothing, continue to check param against other dates
- }
- }
- return false;
- }
- public static boolean isDateParam(String param) {
- SimpleDateFormat[] dateFormats = new SimpleDateFormat[5];
- (dateFormats[0] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MONTHYYYY))
- .setLenient(true);
- (dateFormats[1] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MONTHDDYYYY))
- .setLenient(true);
- (dateFormats[2] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMDDYYYY))
- .setLenient(true);
- (dateFormats[3] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMYYYY))
- .setLenient(true);
- (dateFormats[4] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_DDMONYYYY))
- .setLenient(true);
-
- for (int i = 0; i < dateFormats.length; i++) {
- try {
- if (dateFormats[i].parse(param) != null) {
- return true;
- }
- } catch (ParseException pe) {
- // do nothing, continue to check param against other dates
- }
- catch (NumberFormatException pe) {
- // do nothing, continue to check param against other dates
- }
- }
- return false;
- }
-
- public static String formatDateParamValue(String param) {
- return ReportParamDateValueParser.formatDateParamValue(param, null);
- }
-
- public static String formatDateHrParamValue(String param) {
- return ReportParamDateValueParser.formatDateHrParamValue(param, null);
- }
-
- public static String formatDateHrParamValue(String param, String dateHrFormatPattern) {
- String formattedDate = null;
- Date parsedDate = null;
-
- dateHrFormatPattern = (dateHrFormatPattern != null) ? dateHrFormatPattern
- : "HH";
-
- SimpleDateFormat[] dateFormats = new SimpleDateFormat[2];
- (dateFormats[0] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMDDYYYY_HR))
- .setLenient(true);
- (dateFormats[1] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_DDMONYYYY_HR))
- .setLenient(true);
-
- for (int i = 0; i < dateFormats.length; i++) {
- try {
- if (dateFormats[i].parse(param) != null) {
- SimpleDateFormat newDateFormat = new SimpleDateFormat(dateHrFormatPattern);
- parsedDate = dateFormats[i].parse(param);
- formattedDate = newDateFormat.format(parsedDate);
-
-
- return formattedDate;
- }
- } catch (ParseException pe) {
- // do nothing, continue to check param against other dates and
- // format accordingly
- }
- catch (NumberFormatException pe) {
- // do nothing, continue to check param against other dates
- }
- }
- return param;
- }
-
-
- public static String formatDateParamValue(String param, String dateFormatPattern) {
- String formattedDate = null;
- Date parsedDate = null;
-
- dateFormatPattern = (dateFormatPattern != null) ? dateFormatPattern
- : AppConstants.JAVA_DATE_FORMAT_MMDDYYYY;
-
- SimpleDateFormat[] dateFormats = new SimpleDateFormat[5];
- (dateFormats[0] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MONTHYYYY))
- .setLenient(true);
- (dateFormats[1] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MONTHDDYYYY))
- .setLenient(true);
- (dateFormats[2] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMDDYYYY))
- .setLenient(true);
- (dateFormats[3] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_MMYYYY))
- .setLenient(true);
- (dateFormats[4] = new SimpleDateFormat(AppConstants.JAVA_DATE_FORMAT_DDMONYYYY))
- .setLenient(true);
-
- for (int i = 0; i < dateFormats.length; i++) {
- try {
- if (dateFormats[i].parse(param) != null) {
- SimpleDateFormat newDateFormat = new SimpleDateFormat(dateFormatPattern);
- parsedDate = dateFormats[i].parse(param);
- formattedDate = newDateFormat.format(parsedDate);
-
- if (Globals.getMonthFormatUseLastDay()
- && (dateFormats[i].toPattern().equals(
- AppConstants.JAVA_DATE_FORMAT_MMYYYY) || dateFormats[i]
- .toPattern().equals(
- AppConstants.JAVA_DATE_FORMAT_MONTHYYYY))) {
-
- GregorianCalendar gc = new GregorianCalendar();
- gc.setTime(parsedDate);
- int day = gc.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
- formattedDate = Utils.replaceInString(formattedDate, "/01/", "/"
- + String.valueOf(day) + "/");
-
- }
-
- return formattedDate;
- }
- } catch (ParseException pe) {
- // do nothing, continue to check param against other dates and
- // format accordingly
- }
- catch (NumberFormatException pe) {
- // do nothing, continue to check param against other dates
- }
- }
- return param;
- }
-
-} // ReportParamValues
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.Enumeration;
-import java.util.Hashtable;
-import java.util.Iterator;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-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.util.XSSFilter;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
-public class ReportParamValues extends Hashtable {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportParamValues.class);
-
- private Hashtable paramIsMultiValue = null;
- private Hashtable paramIsTextAreaValue = null;
- private Hashtable paramIsTextAreaDrilldownValue = null;
- private Hashtable paramIsTextAreaValueModified = null;
- private ReportFormFields rff = null;
-
- private Hashtable multiValueBaseSQL = null;
- private Hashtable textAreaValueBaseSQL = null;
-
- public ReportParamValues() {
- super();
- paramIsMultiValue = new Hashtable();
- multiValueBaseSQL = new Hashtable();
- paramIsTextAreaValue = new Hashtable();
- paramIsTextAreaDrilldownValue = new Hashtable();
- paramIsTextAreaValueModified = new Hashtable();
- } // ReportParamValues
-
- public ReportParamValues(ReportFormFields rff, String reportDefType) {
- this();
- this.rff = rff;
- for (Iterator iter = rff.iterator(); iter.hasNext();) {
- FormField ff = (FormField) iter.next();
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
- put(ff.getFieldName(), nvl(ff.getDefaultValue()));
- put(ff.getFieldName()+"_Hr", nvl(ff.getDefaultValue()));
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
- put(ff.getFieldName()+"_Min", nvl(ff.getDefaultValue()));
- }
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
- put(ff.getFieldName()+"_Sec", nvl(ff.getDefaultValue()));
- }
- } else
- put(ff.getFieldName(), nvl(ff.getDefaultValue()));
-
- boolean isMultiValue = ff.getFieldType().equals(FormField.FFT_CHECK_BOX)
- || ff.getFieldType().equals(FormField.FFT_LIST_MULTI);
- boolean isTextAreaValue = ff.getFieldType().equals(FormField.FFT_TEXTAREA) && reportDefType
- .equals(AppConstants.RD_SQL_BASED);
-
- paramIsMultiValue.put(ff.getFieldName(), new Boolean(isMultiValue));
- paramIsTextAreaValue.put(ff.getFieldName(), new Boolean(isTextAreaValue));
-
- if ((isMultiValue || isTextAreaValue) && ff.getBaseSQL() != null)
- multiValueBaseSQL.put(ff.getFieldName(), ff.getBaseSQL());
-
-
- } // for
- } // ReportParamValues
-
- /*
- * public ReportParamValues(ReportFormFields rff, HttpServletRequest
- * request) { this(rff);
- *
- * setParamValues(request); } // ReportParamValues
- */
- public boolean isParameterMultiValue(String fieldName) {
- Boolean b = (Boolean) paramIsMultiValue.get(fieldName);
- return (b != null) ? b.booleanValue() : false;
- } // isParameterMultiValue
-
- public boolean isParameterTextAreaValue(String fieldName) {
- Boolean b = (Boolean) paramIsTextAreaValue.get(fieldName);
- return (b != null) ? b.booleanValue() : false;
- } // isParameterMultiValue
-
- public boolean isParameterTextAreaValueAndModified(String fieldName) {
- Boolean b = (Boolean) paramIsTextAreaValueModified.get(fieldName);
- return (b != null) ? b.booleanValue() : false;
- } // isParameterMultiValue
-
- public boolean setParamValues(HttpServletRequest request, boolean refresh) {
- long currentTime = System.currentTimeMillis();
- //System.out.println("ReportParamValues setParamValues called " + refresh);
- boolean paramUpdated = false;
- if(refresh) clearValues();
- for (Enumeration enKeys = keys(); enKeys.hasMoreElements();) {
- String key = (String) enKeys.nextElement();
- String oldValue = XSSFilter.filterRequestOnlyScript(getParamValue(key));
- String newValue = null;
- if (isParameterMultiValue(key)) {
- String[] values = request.getParameterValues(key);
-
- if (values != null) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < values.length; i++) {
- if (sb.length() > 0)
- sb.append('|');
- sb.append(values[i]);
- } // for
-
- newValue = XSSFilter.filterRequestOnlyScript(sb.toString());
- } // if
- } else if (isParameterTextAreaValue(key)) {
-/* String[] values = request.getParameterValues(key);
-
- if (values != null) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < values.length; i++) {
- if (sb.length() > 0)
- sb.append('|');
- sb.append(values[i]);
- } // for
-*/
- String value = "";
- value = request.getParameter(key);
- value = Utils.oracleSafe(nvl(value));
- paramIsTextAreaDrilldownValue.put(key, value);
- value = value.replaceAll(",", "|");
- value = "('" + Utils.replaceInString(value, "|", "','") + "')";
- //value = Utils.replaceInString(value, "|", ",");
- newValue = XSSFilter.filterRequestOnlyScript(value);
- paramIsTextAreaValueModified.put(key, new Boolean(true));
- //} // if
-
- } else
- // newValue = nvl(request.getParameter(key));
- newValue = XSSFilter.filterRequestOnlyScript(request.getParameter(key));
- //debugLogger.debug("IN REPORTPARAM ^NEW VALUE " + newValue + " OLD VALUE " + oldValue + " KEY " + key + " isParameterMultiValue(key) " + isParameterMultiValue(key));
- if(!isParameterMultiValue(key) && !isParameterTextAreaValue(key)) {
- if(refresh && nvl(newValue).length()<=0) {
- put(key, oldValue);
- } else if ( ((newValue != null && newValue.trim().length()>0) && (oldValue!=null && oldValue.trim().length()>0) && !newValue.equals(oldValue)) ||
- ((newValue != null && newValue.trim().length()>0) && (oldValue == null || oldValue.trim().length() <= 0)) ) {
- paramUpdated = true;
- //System.out.println("paramupdated1 " +paramUpdated+ " " + newValue + " " + oldValue);
- // if(newValue.startsWith("[") && newValue.endsWith("]")) {
- // newValue = getDateAsString(newValue);
- // }
- put(key, newValue);
- } else if (((newValue == null || newValue.trim().length()<=0)) && (oldValue!=null && oldValue.trim().length()>0)) {
- paramUpdated = true;
- put(key, newValue);
- } else if (nvl(newValue).equals(nvl(oldValue)) ) {
- put(key, newValue);
- } else {
- put(key, "");
- }
- } else {
- if (((newValue != null && newValue.trim().length()>0) && (oldValue!=null && oldValue.trim().length()>0) && !newValue.equals(oldValue)) ||
- ((newValue != null && newValue.trim().length()>0) && (oldValue == null || oldValue.trim().length() <= 0)) && (isParameterMultiValue(key)||isParameterTextAreaValue(key))) {
- if(isParameterTextAreaValue(key)) {
- newValue = getParamValueforTextAreaDrilldown(key);
- if(newValue.length() > 0 && !newValue.equals(oldValue)) {
- paramUpdated = true;
- put (key, newValue);
- }
- } else {
- paramUpdated = true;
- put (key, newValue);
- }
-
- } else if (((newValue == null || newValue.trim().length()<=0)) && (oldValue!=null && oldValue.trim().length()>0) && (isParameterMultiValue(key)||isParameterTextAreaValue(key))) {
- paramUpdated = true;
- //System.out.println("paramupdated3 " +paramUpdated+ " N" + newValue + " O" + oldValue);
- put(key, "");
- }
- }
- } // for
- //printValues();
- logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] ------->Time Taken for Adding/Clearing Param Values for Search Field Display " + (System.currentTimeMillis() - currentTime)));
- return paramUpdated;
- } // setParamValues
-
- public String getParamValueforTextAreaDrilldown(String key) {
- return (String) paramIsTextAreaDrilldownValue.get(key);
- }
-
- public String getParamValue(String key) {
- //This logic below is added to avoid BLANK formfield to pass through logic - Sundar
- if (key!=null) {
- if(isParameterTextAreaValueAndModified(key)) {
- String value = "";
- value = (String) get(key);
- value = Utils.oracleSafe(nvl(value));
- value = value.replaceAll(",","|");
- if(nvl(value).length()>0) {
- if(value.indexOf("|")!= -1) { // Need option to support "|"
- value = Utils.replaceInString(value,"\r\n","~");
- }
- value = Utils.replaceInString(value, "~", "' , '");
- value = "('" + Utils.replaceInString(value, "|", "','") + "')"; // changed from "|"
- //value = Utils.replaceInString(value, "|", ",");
- value = XSSFilter.filterRequestOnlyScript(value);
- return value;
- } else return "";
-
-// if(nvl(value).length()>0) {
-// value = Utils.replaceInString(value, ",", "|");
-// value = value.indexOf("('")!=-1? value.substring(2, value.length()-2):value;
-// value = Utils.replaceInString(value, "'|'", ",");
-// }
-// return value;
-
- } else
- return (String) get(key);
- }
- else
- return "";
- } // getParamValue
-
- public String getParamDisplayValue(String key) {
- String value = getParamValue(key);
- if (isParameterMultiValue(key))
- value = "(" + Utils.replaceInString(value, "|", ",") + ")";
- return value;
- } // getParamValue
-
- public String getParamBaseSQL(String key) {
- return (String) multiValueBaseSQL.get(key);
- } // getParamBaseSQL
-
- /** ************************************************************************************************* */
-
- private String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- private String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
- private boolean isNull(String a) {
- if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null"))
- return true;
- else
- return false;
- }
-
- private void clearValues() {
- FormField ff = null;
- String defaultValue = "";
- String defaultSQL = "";
- String defaultQuery = "";
- DataSet dsDefault = null;
- if (rff!= null) {
- for (Enumeration enKeys = keys(); enKeys.hasMoreElements();) {
- String key = (String) enKeys.nextElement();
- for(rff.resetNext(); rff.hasNext(); ) {
- ff = rff.getNext();
- if(ff.getFieldName().equals(key)) {
- // Add default Value
- defaultValue = ff.getDefaultValue();
- defaultSQL = ff.getFieldDefaultSQL();
- if(nvl(defaultValue).length()>0) {
- put(key,ff.getDefaultValue());
- } else if(nvl(defaultSQL).length() > 0) {
- //defaultSQL = Utils.replaceInString(defaultSQL, "[LOGGED_USERID]", userId);
- if(!(isParameterMultiValue(key) || isParameterTextAreaValue(key))) {
- defaultQuery = "SELECT id, name FROM (SELECT rownum r, id, name FROM (" + defaultSQL
- + ") x "
- + ") xx ";
- try {
- dsDefault = ConnectionUtils.getDataSet(defaultQuery, ff.getDbInfo());
- if(dsDefault!=null && dsDefault.getRowCount()>0) {
- for (int i = 0; i < dsDefault.getRowCount(); i++) {
- put(key, dsDefault.getString(i, 0));
- }
- }
- } catch (RaptorException ex) {}
- } else put(key, "");
-
- } else put(key,"");
- break;
- }
- }
- }
- }
-
-/* for (Enumeration enKeys = keys(); enKeys.hasMoreElements();) {
- String key = (String) enKeys.nextElement();
- put(key,"");
- }
-*/
- }
-
-
- public void printValues() {
- for (Enumeration enKeys = keys(); enKeys.hasMoreElements();) {
- String key = (String) enKeys.nextElement();
- String value = (String) get(key);
- System.out.println("ReportParamValues " + key + " "+ value);
- }
- }
-
- private String getDateAsString (String keyword) {
- String sql = "";
- if (keyword.equals("[PROCESSING_DATE]")) {
- //sql = "select to_char(trunc(sysdate,'dd'), 'mm/dd/yyyy') as dateStr from dual";
- sql = "select to_char(trunc(sysdate,'dd'), 'mm/dd/yyyy') as dateStr" + Globals.getGenerateSqlVisualDual();
- } else if (keyword.equals("[PROCESSING_NEXT_DATE]")) {
- //sql = "select to_char(trunc(sysdate+1,'dd'), 'mm/dd/yyyy') as dateStr from dual";
- sql = "select to_char(trunc(sysdate+1,'dd'), 'mm/dd/yyyy') as dateStr" + Globals.getGenerateSqlVisualDual();
- } else if (keyword.equals("[PROCESSING_DAY_BEFORE_DATE]")) {
- //sql = "select to_char(trunc(sysdate-1,'dd'), 'mm/dd/yyyy') as dateStr from dual";
- sql = "select to_char(trunc(sysdate-1,'dd'), 'mm/dd/yyyy') as dateStr"+ Globals.getGenerateSqlVisualDual();
- } else if (keyword.equals("[PROCESSING_MONTH_START_DATE]")) {
- //sql = "select to_char(trunc(sysdate,'MM'), 'mm/dd/yyyy') as dateStr from dual";
- sql = "select to_char(trunc(sysdate,'MM'), 'mm/dd/yyyy') as dateStr"+ Globals.getGenerateSqlVisualDual();
- } else if (keyword.equals("[PROCESSING_MONTH_END_DATE]")) {
- //sql = "select to_char(last_day(sysdate), 'mm/dd/yyyy') as dateStr from dual";
- sql = "select to_char(last_day(sysdate), 'mm/dd/yyyy') as dateStr" + Globals.getGenerateSqlVisualDual();
- } else if (keyword.equals("[CURRENT_HOUR]")) {
- //sql = "select to_char(trunc(sysdate,'HH24'),'mm/dd/yyyy HH24') as dateStr from dual";
- sql = "select to_char(trunc(sysdate,'HH24'),'mm/dd/yyyy HH24') as dateStr"+ Globals.getGenerateSqlVisualDual();
- } else if (keyword.equals("[PREVIOUS_HOUR]")) {
- //sql = "select to_char(trunc(sysdate-1/24, 'HH24'),'mm/dd/yyyy HH24') as dateStr from dual";
- sql = "select to_char(trunc(sysdate-1/24, 'HH24'),'mm/dd/yyyy HH24') as dateStr" + Globals.getGenerateSqlVisualDual();
- } else if (keyword.equals("[NEXT_HOUR]")) {
- //sql = "select to_char(trunc(sysdate+1/24, 'HH24'),'mm/dd/yyyy HH24') as dateStr from dual";
- sql = "select to_char(trunc(sysdate+1/24, 'HH24'),'mm/dd/yyyy HH24') as dateStr" + Globals.getGenerateSqlVisualDual();
- }
- DataSet ds = null;
-
- try {
- if(sql.length()>0) {
- ds = DbUtils.executeQuery(sql);
- return ds.getString(0,0);
- }
- else
- return "";
- } catch (RaptorException ex) {
- ex.printStackTrace();
- //throw ex;
- }
- return "";
- }
-} // ReportParamValues
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.Enumeration;
-import java.util.Hashtable;
-import java.util.Iterator;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.error.ReportSQLException;
-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.Utils;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
-public class ReportParamValuesForPDFExcel extends Hashtable {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportParamValuesForPDFExcel.class);
-
- private Hashtable paramIsMultiValue = null;
- private Hashtable paramIsTextAreaValue = null;
- private ReportFormFields rff = null;
-
- private Hashtable multiValueBaseSQL = null;
-
- public ReportParamValuesForPDFExcel() {
- super();
- paramIsMultiValue = new Hashtable();
- paramIsTextAreaValue = new Hashtable();
- multiValueBaseSQL = new Hashtable();
- } // ReportParamValues
-
- public ReportParamValuesForPDFExcel(ReportFormFields rff, String reportDefType) {
- this();
- this.rff = rff;
- for (Iterator iter = rff.iterator(); iter.hasNext();) {
- FormField ff = (FormField) iter.next();
-
- put(ff.getFieldName(), nvl(ff.getDefaultValue()));
-
- boolean isMultiValue = ff.getFieldType().equals(FormField.FFT_CHECK_BOX)
- || ff.getFieldType().equals(FormField.FFT_LIST_MULTI);
- boolean isTextAreaValue = ff.getFieldType().equals(FormField.FFT_TEXTAREA) && reportDefType
- .equals(AppConstants.RD_SQL_BASED);
- paramIsMultiValue.put(ff.getFieldName(), new Boolean(isMultiValue));
- paramIsTextAreaValue.put(ff.getFieldName(), new Boolean(isTextAreaValue));
- if (isMultiValue && ff.getBaseSQL() != null)
- multiValueBaseSQL.put(ff.getFieldName(), ff.getBaseSQL());
- } // for
- } // ReportParamValues
-
- /*
- * public ReportParamValues(ReportFormFields rff, HttpServletRequest
- * request) { this(rff);
- *
- * setParamValues(request); } // ReportParamValues
- */
- public boolean isParameterMultiValue(String fieldName) {
- Boolean b = (Boolean) paramIsMultiValue.get(fieldName);
- return (b != null) ? b.booleanValue() : false;
- } // isParameterMultiValue
-
- public boolean isParameterTextAreaValue(String fieldName) {
- Boolean b = (Boolean) paramIsTextAreaValue.get(fieldName);
- return (b != null) ? b.booleanValue() : false;
- } // isParameterMultiValue
-
- public boolean setParamValues(HttpServletRequest request, boolean refresh) {
- //debugLogger.debug("ReportParamValues for PDF Excel setParamValues called " + refresh);
- long currentTime = System.currentTimeMillis();
- boolean paramUpdated = false;
- if(refresh) clearValues();
- String name = null;
- String value = null;
- String value1 = "";
- String sql = "";
- FormField ff = null;
- String dbInfo = null;
- ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
- if(rr!=null && rr.getReportType().equals(AppConstants.RT_DASHBOARD)) {
- rr = (ReportRuntime) request.getSession().getAttribute("FirstDashReport");
- if(rr!=null)
- rff = rr.getReportFormFields();
- } else if (rr == null) {
- rr = (ReportRuntime) request.getSession().getAttribute("FirstDashReport");
- if(rr!=null)
- rff = rr.getReportFormFields();
- } else {
- rff = rr.getReportFormFields();
- }
-
- if(rr!=null) {
- dbInfo = rr.getDBInfo();
- if (Utils.isNull(dbInfo)) {
- dbInfo = (String) request.getSession().getAttribute("remoteDB");
- }
- if(!Utils.isNull(dbInfo)){
- for (Iterator iter = rff.iterator(); iter.hasNext();) {
- name=""; //just added
- ff = (FormField) iter.next();
- //debugLogger.debug("ff.getFieldName " + ff.getFieldName() + " " + ff.getFieldDisplayName() + " " + ff.getFieldType()+ " " +ff.getBaseSQLForPDFExcel()+ " "+ rr.getParamValue(ff.getFieldName()));
- if(!ff.getFieldType().equals(FormField.FFT_BLANK)) {
- sql = ff.getBaseSQLForPDFExcel();
- if(sql!=null && sql.trim().length()>0)
- sql = Utils.replaceInString(sql, "[LOGGED_USERID]", AppUtils.getUserID(request));
- if(ff.getFieldType().equals(FormField.FFT_COMBO_BOX) || ff.getFieldType().equals(FormField.FFT_LIST_BOX) || ff.getFieldType().equals(FormField.FFT_TEXT_W_POPUP) || ff.getFieldType().equals(FormField.FFT_HIDDEN)) {
- for (Enumeration enum1 = rr.getParamKeys(); enum1.hasMoreElements();) {
- name = (String) enum1.nextElement();
- value = rr.getParamValue(name);
- value = getParamValueForSQL(name, value);
- if(name.startsWith("ff")) {
- for (Iterator iter1 = rff.iterator(); iter1.hasNext();) {
- FormField ff1 = (FormField) iter1.next();
-
- if(sql!=null && sql.trim().length()>0){
- if(name.equals(ff.getFieldName())){
- sql = Utils.replaceInString(sql, "[VALUE]", value);
- }
- if(name.equals(ff1.getFieldName())){
- sql = Utils.replaceInString(sql, "["+ff1.getFieldDisplayName()+"]", value);
-
- } else continue;
- }
- }
- }
- }
- } else if (ff.getFieldType().equals(ff.FFT_LIST_MULTI)||ff.getFieldType().equals(ff.FFT_CHECK_BOX)) {
- for (Enumeration enum1 = rr.getParamKeys(); enum1.hasMoreElements();) {
- name = (String) enum1.nextElement();
- value = rr.getParamValue(name);
- value = getParamValueForSQL(name, value);
- if(name.startsWith("ff")) {
- for (Iterator iter1 = rff.iterator(); iter1.hasNext();) {
- FormField ff1 = (FormField) iter1.next();
-
- if(sql!=null && sql.trim().length()>0){
- if(name.equals(ff.getFieldName())){
- sql = Utils.replaceInString(sql, "[VALUE]", value);
- }
- if(name.equals(ff1.getFieldName())){
- sql = Utils.replaceInString(sql, "["+ff1.getFieldDisplayName()+"]", value);
-
- } else continue;
- }
- }
- }
- }
- } else {
- if(nvl(ff.getFieldDefaultSQL()).length()<=0)
- sql = "";
- }
- if(sql!=null && sql.trim().length()>0){
- name = "";
- if(name.length()<=0) name = ff.getFieldName();
- value = rr.getParamValue(name);
- //debugLogger.debug("Name "+ name+ " value:" + value);
- String paramValue = getParamValueForSQL(name, value);
- //debugLogger.debug("PDFEXCEL " + name+ " " + ff.getFieldName()+ " " + value + " " + sql +" "+ paramValue);
- if(name!=null && name.equals(ff.getFieldName()))
- sql = Utils.replaceInString(sql, "[VALUE]", paramValue);
- if(paramValue == null) {
- if(sql.lastIndexOf("where id = ''")>0)
- sql = sql.substring(0, sql.lastIndexOf("where id = ''"));
- }
- //debugLogger.debug("SQL Modified " + sql);
- FormField ff2 = null;
- for (Iterator iter1 = rff.iterator(); iter1.hasNext();) {
- ff2 = (FormField)iter1.next();
- sql = Utils.replaceInString(sql, "[" + ff2.getFieldDisplayName() +"]", getParamValue(ff2.getFieldName()));
- }
- //debugLogger.debug("SQL Modified after replacing formfield" + sql);
- try {
- String[] reqParameters = Globals.getRequestParams().split(",");
- String[] sessionParameters = Globals.getSessionParams().split(",");
- String[] scheduleSessionParameters = Globals.getSessionParamsForScheduling().split(",");
- javax.servlet.http.HttpSession session = request.getSession();
- //debugLogger.debug("B4 Session " + sql);
- if(session != null ) {
- for (int i = 0; i < sessionParameters.length; i++) {
- sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
- }
- }
- //debugLogger.debug("B4 request " + sql);
- if(request != null ) {
- for (int i = 0; i < scheduleSessionParameters.length; i++) {
- sql = Utils.replaceInString(sql, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) );
- }
- for (int i = 0; i < reqParameters.length; i++) {
- if(!reqParameters[i].startsWith("ff")) {
- if (request.getParameter(reqParameters[i])!=null) {
- sql = Utils.replaceInString(sql, "[" + reqParameters[i]+"]", request.getParameter(reqParameters[i]) );
- sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
- }
- else {
- sql = Utils.replaceInString(sql, "[" + reqParameters[i]+"]", request.getParameter(reqParameters[i].toUpperCase()) );
- sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
- }
- }
- else
- sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
- }
- }
- //debugLogger.debug("After request " + sql);
- DataSet ds = null;
- try {
- ds = ConnectionUtils.getDataSet(sql, dbInfo);
- } catch (ReportSQLException ex) {
- logger.debug(EELFLoggerDelegate.debugLogger, ("sql not complete" + sql));
- }
- if(ff.getFieldType().equals(FormField.FFT_LIST_MULTI) || ff.getFieldType().equals(FormField.FFT_CHECK_BOX)) {
- StringBuffer multiValue = new StringBuffer("");
- if(ds!=null) {
- for(int i = 0; i < ds.getRowCount(); i++) {
- //if(i==0) multiValue.append("(");
- multiValue.append(ds.getString(i,1));
- if(i<ds.getRowCount()-1)
- multiValue.append("|");
- //else multiValue.append(")");
-
- }
- }
- put(ff.getFieldName(), nvl(multiValue.toString()));
- } else {
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ) {
- value1 = nvl(rr.getParamValue(ff.getFieldName())) + " "+addZero(Utils.oracleSafe(nvl(rr
- .getParamValue(ff.getFieldName()+"_Hr"))));
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ) {
- value1 = value1 + (nvl(rr
- .getParamValue(ff.getFieldName()+"_Min")).length() > 0 ? ":" + addZero(Utils.oracleSafe(nvl(rr
- .getParamValue(ff.getFieldName()+"_Min")))) : "");
- }
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ) {
- value1 = value1 + (nvl(rr
- .getParamValue(ff.getFieldName()+"_Sec")).length() > 0 ? ":"+ addZero(Utils.oracleSafe(nvl(rr
- .getParamValue(ff.getFieldName()+"_Sec")))) : "");
- }
- //debugLogger.debug("77777777777777 " + value1);
- put(ff.getFieldName(), nvl(value1));
- } else {
-
- if(ds!=null && ds.getRowCount()>0) put(ff.getFieldName(), nvl(ds.getString(0,1)));
- else put(ff.getFieldName(), nvl(value));
- }
- }
-
- paramUpdated = true;
- } catch (ReportSQLException ex) {
- logger.debug(EELFLoggerDelegate.debugLogger, ("sql not complete" + sql));
- }
- catch (Exception ex) {}
-
- //debugLogger.debug("66666666666666666 " + ff.getValidationType());
-
- //Added for TimeStamp validation
-
- } else {
- if(!ff.getFieldType().equals(FormField.FFT_BLANK)) {
- //Added for TimeStamp validation
- //debugLogger.debug("666666666666 " + ff.getValidationType());
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ) {
- value1 = nvl(rr.getParamValue(ff.getFieldName())) + " "+addZero(Utils.oracleSafe(nvl(rr
- .getParamValue(ff.getFieldName()+"_Hr"))));
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ) {
- value1 = value1 + (nvl(rr
- .getParamValue(ff.getFieldName()+"_Min")).length() > 0 ? ":" + addZero(Utils.oracleSafe(nvl(rr
- .getParamValue(ff.getFieldName()+"_Min")))) : "");
- }
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ) {
- value1 = value1 + (nvl(rr
- .getParamValue(ff.getFieldName()+"_Sec")).length() > 0 ? ":"+ addZero(Utils.oracleSafe(nvl(rr
- .getParamValue(ff.getFieldName()+"_Sec")))) : "");
- }
- //debugLogger.debug("77777777777777 " + value1);
- } else
- value1 = nvl(rr.getParamValue(ff.getFieldName()));
- if(value1.length()<=0) value1 = nvl(ff.getDefaultValue());
- put(ff.getFieldName(), nvl(value1));
-
- }
- paramUpdated = true;
- }
-
- } // BLANK
- } // for
- } // dbInfo
- } // !=null
-
- //printValues();
- logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] ------->Time Taken for Adding/Clearing Param Values for FormField Info Bar " + (System.currentTimeMillis() - currentTime)));
- return paramUpdated;
- } // setParamValues
-
- public String getParamValue(String key) {
- if (key!=null)
- return (String) get(key);
- else
- return "NULL";
- } // getParamValue
-
- public String getParamValueForSQL(String key, String value) {
- value = Utils.oracleSafe(value);
- if (isParameterMultiValue(key))
- value = "('" + Utils.replaceInString(value, "|", "','") + "')";
- return value;
- } // getParamValue
-
- public String getParamDisplayValue(String key) {
- //debugLogger.debug("Key is " + key +" Value is " + getParamValue(key));
- String value = getParamValue(key);
- if (isParameterMultiValue(key))
- value = "(" + Utils.replaceInString(value, "|", ",") + ")";
- return value;
- } // getParamValue
-
- public String getParamBaseSQL(String key) {
- return (String) multiValueBaseSQL.get(key);
- } // getParamBaseSQL
-
- /** ************************************************************************************************* */
-
- private String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- private String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
- private boolean isNull(String a) {
- if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null"))
- return true;
- else
- return false;
- }
-
- private void clearValues() {
- FormField ff = null;
- String defaultValue = "";
- String defaultSQL = "";
- String defaultQuery = "";
- DataSet dsDefault = null;
- if (rff!= null) {
- for (Enumeration enKeys = keys(); enKeys.hasMoreElements();) {
- String key = (String) enKeys.nextElement();
- for(rff.resetNext(); rff.hasNext(); ) {
- ff = rff.getNext();
- if(ff.getFieldName().equals(key)) {
- // Add default Value
- defaultValue = ff.getDefaultValue();
- defaultSQL = ff.getFieldDefaultSQL();
- if(nvl(defaultValue).length()>0) {
- put(key,ff.getDefaultValue());
- } else if(nvl(defaultSQL).length() > 0) {
- //defaultSQL = Utils.replaceInString(defaultSQL, "[LOGGED_USERID]", userId);
- if(!(isParameterMultiValue(key) || isParameterTextAreaValue(key))) {
- defaultQuery = "SELECT id, name FROM (SELECT rownum r, id, name FROM (" + defaultSQL
- + ") x "
- + ") xx ";
- try {
- dsDefault = ConnectionUtils.getDataSet(defaultQuery, ff.getDbInfo());
- if(dsDefault!=null && dsDefault.getRowCount()>0) {
- for (int i = 0; i < dsDefault.getRowCount(); i++) {
- put(key, dsDefault.getString(i, 1));
- }
- }
- } catch (RaptorException ex) {}
- } else put(key, "");
-
- } else put(key,"");
- break;
- }
- }
- }
- }
-
- }
-
- public void printValues() {
- for (Enumeration enKeys = keys(); enKeys.hasMoreElements();) {
- String key = (String) enKeys.nextElement();
- String value = (String) get(key);
- logger.debug(EELFLoggerDelegate.debugLogger, ("ReportParamValuesForPDFEXCEL " + key + " "+ value));
- }
- }
- 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;
- }
-
-} // ReportParamValues
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.sql.Connection;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-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.StringTokenizer;
-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.model.DataCache;
-import org.openecomp.portalsdk.analytics.model.ReportHandler;
-import org.openecomp.portalsdk.analytics.model.ReportLoader;
-import org.openecomp.portalsdk.analytics.model.base.IdNameList;
-import org.openecomp.portalsdk.analytics.model.base.IdNameSql;
-import org.openecomp.portalsdk.analytics.model.base.IdNameValue;
-import org.openecomp.portalsdk.analytics.model.base.ReportWrapper;
-import org.openecomp.portalsdk.analytics.model.definition.Marker;
-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.view.ColumnHeader;
-import org.openecomp.portalsdk.analytics.view.ColumnHeaderRow;
-import org.openecomp.portalsdk.analytics.view.CrossTabOrderManager;
-import org.openecomp.portalsdk.analytics.view.CrossTabTotalValue;
-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.view.RowHeaderCol;
-import org.openecomp.portalsdk.analytics.xmlobj.CustomReportType;
-import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType;
-import org.openecomp.portalsdk.analytics.xmlobj.FormFieldType;
-import org.openecomp.portalsdk.analytics.xmlobj.ObjectFactory;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-
-/**<HR/>
- * This class is part of <B><I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I></B><BR/>
- * <HR/>
- *
- * --------------------------------------------------------------------------------------------------<BR/>
- * <B>ReportRuntime.java</B> - This class involves in running, downloading RAPTOR reports.
- * --------------------------------------------------------------------------------------------------<BR/>
- *
- *
- * <U>Change Log</U><BR/><BR/>
- *
- * 27-Aug-2009 : Version 8.5 (Sundar); <UL><LI>Order by logic is restored for DAYTONA.</LI></UL>
- * 13-Aug-2009 : Version 8.5 (Sundar); <UL><LI>Removing order by logic is rollbacked.</LI></UL>
- * 22-Jun-2009 : Version 8.4 (Sundar); <UL><LI>Bug while parsing SQL for text download is fixed.</LI></UL>
- *
- */
-
-public class ReportRuntime extends ReportWrapper implements Cloneable, Serializable {
-
- static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportRuntime.class);
-
-
- //TODO DELETE IF PARSE SQL is not working
- private int curSQLParsePos = 0;
-
- private String xmlFileURL = null;
-
- private String xmlFileName = null;
-
- private String flatFileName = null;
-
- private String excelPageFileName = null;
-
- private int reportDataSize = -1;
-
- private boolean displayChart = true;
-
- private boolean displayForm = true;
-
- private boolean displayContent = true;
-
- private boolean reportRunLogged = false; // Used to avoid multiple
- // entries in the report log
- // when executing with different
- // params or going to next page
-
- private DataSet chartDataCache = null;
-
- private ReportData pageDataCache = null;
-
- private int cachedPageNo = -1;
-
- private String cachedSQL = null; // For display purposes only
-
- private String wholeSQL = null; // For display purposes only
-
- private String totalSql = null; // For display purposes only
-
- private ReportParamValues reportParamValues = null;
-
- private ReportParamValuesForPDFExcel reportParamValuesFPE = null;
-
- private ReportFormFields reportFormFields = null;
-
- private VisualManager visualManager = null;
-
- private CrossTabOrderManager crossTabOrderManager = null;
-
- private boolean displayColTotals = false;
-
- private boolean displayRowTotals = false;
-
- private DataRow colDataTotalsLinear = null;
-
- private Vector colDataTotalsCrosstab = null;
-
- private Vector rowDataTotalsCrosstab = null;
-
- private String grandTotalCrosstab = null;
-
- public static int DISPLAY_DATA_ONLY = 1;
- public static int DISPLAY_CHART_ONLY = 2;
- public static int DISPLAY_CHART_AND_DATA = 3;
-
- public static final int DATE_OPTION_MONTHLY = 1;
- public static final int DATE_OPTION_YEARLY = 2;
- public static final int DATE_OPTION_DAILY = 3;
-
-
- private int DISPLAY_MODE = 0;
-
- private int DATE_OPTION = -1;
-
- /*
- * private ReportRuntime(CustomReport cr, String reportID,
- * HttpServletRequest request) { super(cr, reportID);
- *
- * reportParamValues = new ReportParamValues(this); reportFormFields = new
- * ReportFormFields(this);
- *
- * if(request!=null) setParamValues(request); } // ReportRuntime
- */
- private ReportRuntime(CustomReportType crType, String reportID, HttpServletRequest request,
- String ownerID, String createID, String createDate, String updateID,
- String updateDate, String menuID, boolean menuApproved) throws RaptorException {
- super(crType, reportID, ownerID, createID, createDate, updateID, updateDate, menuID,
- menuApproved);
- initializeReportRuntime(request);
- } // ReportRuntime
-
- public ReportRuntime(ReportWrapper rw) throws RaptorException {
- this(rw, null);
- } // ReportRuntime
-
- public ReportRuntime(ReportWrapper rw, HttpServletRequest request)throws RaptorException {
- super(rw);
- initializeReportRuntime(request);
- } // ReportRuntime
-
- private void initializeReportRuntime(HttpServletRequest request) throws RaptorException {
- reportFormFields = new ReportFormFields(this, request);
- setParamValues(request, true, true);
-
- visualManager = new VisualManager();
- } // initializeReportRuntime
-
-// public void setReportFormFields(HttpServletRequest request) {
-// reportFormFields = new ReportFormFields(this, request);
-// setParamValues(request, true, true);
-// }
-
- public static ReportRuntime unmarshal(String reportXML, String reportID)
- throws RaptorException {
- return unmarshal(reportXML, reportID, null);
- } // unmarshal
-
- public static ReportRuntime unmarshal(String reportXML, String reportID,
- HttpServletRequest request) throws RaptorException {
- CustomReportType crType = ReportWrapper.unmarshalCR(reportXML);
- ObjectFactory objFactory = new ObjectFactory();
-
- logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report [" + reportID + "]: XML unmarshalled"));
-
- return new ReportRuntime(crType, reportID, request, null, null, null, null, null, null,
- false);
-
- } // unmarshal
-
- public String getXmlFileURL() {
- return xmlFileURL;
- }
-
- public String getXmlFileName() {
- return xmlFileName;
- }
-
- public String getFlatFileName() {
- return flatFileName;
- }
-
- public String getExcelPageFileName() {
- return excelPageFileName;
- }
-
- public int getReportDataSize() {
- return reportDataSize;
- }
-
- public boolean getDisplayChart() {
- return displayChart;
- }
-
- public boolean getDisplayForm() {
- return displayForm;
- }
-
- public boolean getDisplayContent() {
- return displayContent;
- }
-
- public int getCachedPageNo() {
- return cachedPageNo;
- }
-
- public String getCachedSQL() {
- return cachedSQL;
- }
-
- public boolean isDashboardType() throws RaptorException {
- return ReportLoader.isDashboardType(getReportID());
- }
-
-
- public void setXmlFileURL(String xmlFileURL) {
- this.xmlFileURL = xmlFileURL;
- }
-
- public void setXmlFileName(String xmlFileName) {
- this.xmlFileName = xmlFileName;
- }
-
- public void setFlatFileName(String flatFileName) {
- this.flatFileName = flatFileName;
- }
-
- public void setExcelPageFileName(String excelPageFileName) {
- this.excelPageFileName = excelPageFileName;
- }
-
- /*private*/ public void setReportDataSize(int reportDataSize) {
- this.reportDataSize = reportDataSize;
- }
-
- private void setDisplayForm(boolean displayForm) {
- this.displayForm = displayForm;
- }
-
- private void setDisplayContent(boolean displayContent) {
- this.displayContent = displayContent;
- }
-
- public void setDisplayFlags(boolean isFirstAccess, boolean forceDisplayContent) {
- if (isFirstAccess) {
- setDisplayForm(true);
-
- if (forceDisplayContent)
- setDisplayContent(true);
- else if (Globals.getDisplayFormBeforeRun())
- if (needFormInput())
- setDisplayContent(false);
- else
- setDisplayContent(true);
- else
- setDisplayContent(true);
- } else {
- setDisplayContent(true);
-
- if (Globals.getIncludeFormWithData())
- setDisplayForm(true);
- else if (Globals.getDisplayFormBeforeRun())
- setDisplayForm(false);
- else
- setDisplayForm(true);
- } // else
- } // setDisplayFlags
-
- public void logReportRun(String userID, String executionTime, String formFields) throws RaptorException {
- if (reportRunLogged)
- return;
-
- ReportLoader.createReportLogEntry(null, reportID, userID, AppConstants.RLA_RUN,executionTime,formFields );
- reportRunLogged = true;
- } // logReportRun
-
- public void logReportExecutionTime(String userId, String executionTime, String action, String formFields) throws RaptorException {
- ReportLoader.createReportLogEntryForExecutionTime(null, reportID, userId,executionTime , action, formFields);
- }
-
- public void logReportExecutionTimeFromLogList (String userId, String executionTime, String formFields) throws RaptorException {
- ReportLoader.createReportLogEntryForExecutionTime(null, reportID, userId,executionTime , AppConstants.RLA_FROM_LOG, formFields);
- }
-
- public void resetVisualSettings() {
- boolean haveToResetCachedData = (visualManager.getSortByColId().length() > 0);
- visualManager = new VisualManager();
-
- if (haveToResetCachedData)
- pageDataCache = null;
-
- if (pageDataCache != null)
- pageDataCache.resetVisualSettings();
- } // resetVisualSettings
-
- /** ************** ReportParamValues processing *************** */
-
- public boolean setParamValues(HttpServletRequest request, boolean resetParams, boolean refresh) throws RaptorException {
- boolean paramsUpdated = false;
- if (resetParams) {
- reportFormFields = new ReportFormFields(this, request);
- reportParamValues = new ReportParamValues(reportFormFields, getReportDefType());
- // This is called even in the wizard page. Hence this condition.
- if((ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null)
- reportParamValuesFPE = new ReportParamValuesForPDFExcel(reportFormFields, getReportDefType());
- paramsUpdated = true;
-
- reportRunLogged = false;
- } else if (request != null) {
- paramsUpdated = reportParamValues.setParamValues(request,refresh);
- }
- // This is called even in the wizard page. Hence this condition.
- if((ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null) {
- if(reportParamValuesFPE!=null) reportParamValuesFPE.setParamValues(request,refresh);
- else {
- reportParamValuesFPE = new ReportParamValuesForPDFExcel(reportFormFields, getReportDefType());
- reportParamValuesFPE.setParamValues(request,refresh);
- }
- } else {
- reportFormFields = new ReportFormFields(this, request);
- //added below two lines for dashboard default value
- reportParamValues = new ReportParamValues(reportFormFields, getReportDefType());
- reportParamValues.setParamValues(request,refresh);
- //End
- reportParamValuesFPE = new ReportParamValuesForPDFExcel(reportFormFields, getReportDefType());
- reportParamValuesFPE.setParamValues(request,refresh);
-
- }
-// }
- if (paramsUpdated) {
- setReportDataSize(-1);
- chartDataCache = null;
- pageDataCache = null;
- cachedPageNo = -1;
-
- crossTabOrderManager = null;
-
- colDataTotalsLinear = null;
- colDataTotalsCrosstab = null;
- rowDataTotalsCrosstab = null;
- grandTotalCrosstab = null;
- if(!refresh)
- resetVisualSettings();
- } // if
-
- displayChart = (request.getParameter(AppConstants.RI_DISPLAY_CHART) == null) ? !isDisplayOptionHideChart() : request.getParameter("display_chart")
- .equals("Y");
-
- return paramsUpdated;
- } // setParamValues
-
- public String getParamValue(String key) {
- //reportParamValues.printValues();
- return reportParamValues.getParamValue(key);
- } // getParamValue
-
- public String getParamDisplayValue(String key) {
- //reportParamValues.printValues();
- return reportParamValues.getParamDisplayValue(key);
- } // getParamValue
-
- public Enumeration getParamKeys() {
- return reportParamValues.keys();
- } // getParamKeys
-
- public Enumeration getParamKeysForPDFExcel() {
- return reportParamValuesFPE.keys();
- } // getParamKeys
-
- public String getParamValueForPDFExcel(String key) {
- return reportParamValuesFPE.getParamValue(key);
- } // getParamValue
-
- public ArrayList getParamNameValuePairs() {
- ArrayList paramList = new ArrayList(getReportFormFields().size());
- for (Iterator iter = getReportFormFields().iterator(); iter.hasNext();) {
- FormField ff = (FormField) iter.next();
- paramList.add(new IdNameValue(ff.getFieldDisplayName(), reportParamValues
- .getParamDisplayValue(ff.getFieldName())));
- } // for
- return paramList;
- } // getParamNameValuePairs
-
- public ArrayList getParamNameValuePairsforPDFExcel(HttpServletRequest request, int type /*excel =1; pdf=2*/) {
- javax.servlet.http.HttpSession session = request.getSession();
- ArrayList paramList = new ArrayList(getReportFormFields().size());
- if(session.getAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO)!=null) {
- paramList = (ArrayList) session.getAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO);
- if(paramList!=null && paramList.size()>0)
- return paramList;
- }
- //System.out.println(" getParamNamePairs type " + type + " " + Globals.customizeFormFieldInfo());
- if ( reportParamValuesFPE == null) {
- reportParamValuesFPE = new ReportParamValuesForPDFExcel(reportFormFields, getReportDefType());
- reportParamValuesFPE.setParamValues(request,true);
- }
-
- String valueString = "";
- for (Iterator iter = getReportFormFields().iterator(); iter.hasNext();) {
- FormField ff = (FormField) iter.next();
- if(ff.isVisible() && /*!ff.getFieldType().equals(FormField.FFT_HIDDEN) &&*/ type == 1){
- valueString = reportParamValuesFPE.getParamDisplayValue(ff.getFieldName());
- } else if(ff.isVisible() && type != 1) {
- valueString = reportParamValuesFPE.getParamDisplayValue(ff.getFieldName());
- }
- if(valueString.equalsIgnoreCase("NULL"))
- valueString="";
- paramList.add(new IdNameValue(ff.getFieldDisplayName(), valueString));
-// }
- } // for
-
- String pdfAttachmentKey = AppUtils.getRequestValue(request, "pdfAttachmentKey");
- boolean isSchedule = false;
- if(pdfAttachmentKey != null)
- isSchedule = true;
- if(Globals.customizeFormFieldInfo() && type == 2) {
- String[] sessionParameters = Globals.getSessionParams().split(",");
-
- if(session != null && !isSchedule ) {
- session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
- for (int i = 0; i < sessionParameters.length; i++) {
- if(session.getAttribute(sessionParameters[i])!=null)
- paramList.add(new IdNameValue(sessionParameters[i].toUpperCase(), (String)session.getAttribute(sessionParameters[i])));
- }
- }
-
- if(isSchedule) {
- //debugLogger.debug("Globals " + Globals.getSessionParamsForScheduling());
- String[] scheduleSessionParam = Globals.getSessionParamsForScheduling().split(",");
- for (int i = 0; i < scheduleSessionParam.length; i++) {
- //debugLogger.debug(" scheduleSessionParam[i] " + scheduleSessionParam[i] + " " + request.getParameter(scheduleSessionParam[i]) );
- if(request.getParameter(scheduleSessionParam[i])!=null)
- paramList.add(new IdNameValue(scheduleSessionParam[i].toUpperCase(), request.getParameter(scheduleSessionParam[i])));
- }
- }
-
- try {
- SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss");
- Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime());
- SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern());
- paramList.add(new IdNameValue("DATE", dtimestamp.format(sysdate)+" "+Globals.getTimeZone()));
- } catch(Exception ex) {}
-
- } else {
- //System.out.println(" In Else getParamNamePairs type " + type);
- String[] sessionDisplayParameters = Globals.getDisplaySessionParamInPDFEXCEL().split(",");
- if(session != null && !isSchedule ) {
- session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
- for (int i = 0; i < sessionDisplayParameters.length; i++) {
- String sessionDispParam = sessionDisplayParameters[i];
- if(nvl(sessionDispParam).length()>0) {
- String sessionDispParamArr[] = sessionDispParam.split(";");
- //System.out.println("Session " + sessionDispParamArr[1] + " " + (String)session.getAttribute(sessionDispParamArr[0]));
- paramList.add(new IdNameValue(sessionDispParamArr[1], nvl((String)session.getAttribute(sessionDispParamArr[0]),"")));
- }
- }
- }
- if(isSchedule) {
- String[] scheduleSessionParam = Globals.getDisplayScheduleSessionParamInPDFEXCEL().split(",");
- for (int i = 0; i < scheduleSessionParam.length; i++) {
- String scheduleSessionDispParam = scheduleSessionParam[i];
- if(nvl(scheduleSessionDispParam).length()>0) {
- String scheduleSessionDispParamArr[] = scheduleSessionDispParam.split(";");
- paramList.add(new IdNameValue(scheduleSessionDispParamArr[1], nvl(request.getParameter(scheduleSessionDispParamArr[0]),"")));
- }
- }
- }
- try {
- SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss");
- Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime());
- SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern());
- paramList.add(new IdNameValue("Report Date/Time", dtimestamp.format(sysdate)+" "+Globals.getTimeZone()));
- } catch(Exception ex) {}
-
- }
-
- for (int i = 0; i < paramList.size(); i++) {
- IdNameValue value = (IdNameValue) paramList.get(i);
- String name = value.getName().replaceAll(",","~");
- value.setName(name);
- }
- //request.getSession().setAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO, paramList);
- return paramList;
- } // getParamNameValuePairs
-
- /** ************** ReportFormFields processing *************** */
-
- public String getFormFieldComments(HttpServletRequest request) {
- String comment = "";
- StringBuffer st = new StringBuffer("");
- if(getFormFieldList()!=null){
- comment = nvl(getFormFieldList().getComment());
- ArrayList al = null;
- if(comment.length()>0) {
- al = getParamNameValuePairsforPDFExcel(request, 2);
- if(al!=null) {
- //st = new StringBuffer(comment);
- for (int i=0; i < al.size(); i++) {
- IdNameValue idNameValue = (IdNameValue)al.get(i);
- if(nvl(idNameValue.getId()).equals("DATE"))
- st.append("<b>Date/Time Report Run:</b>"+ idNameValue.getName() +"<br></br>");
- }
-
- for (int i=0; i < al.size(); i++) {
- IdNameValue idNameValue = (IdNameValue)al.get(i);
- comment = Utils.replaceInString(comment, "["+ idNameValue.getId()+"]", idNameValue.getName());
- }
- st.append(comment);
-
- }
- }
- }
- return st.toString();
- }
-
- public boolean needFormInput() {
- return reportFormFields.getFieldCount() > 0;
- } // needFormInput
-
- public FormField getFormField(String fieldName) {
- return reportFormFields.getFormField(fieldName);
- } // getFormField
-
- public ReportFormFields getReportFormFields() {
- return reportFormFields;
- } // getReportFormFields
-
- /** ************** Report Data processing *************** */
- public DataSet loadChartData(String userId, HttpServletRequest request) throws RaptorException {
- if (nvl(getChartType()).length() == 0)
- return null;
- if (!getDisplayChart())
- return null;
-
- DataSet ds = chartDataCache;
- String sql = null;
- if (ds == null) {
- sql = generateChartSQL(reportParamValues, userId, request);
- String dbInfo = getDBInfo();
- ds = ConnectionUtils.getDataSet(sql, dbInfo);
- if (Globals.getCacheChartData())
- chartDataCache = ds;
- } // if
-
- return ds;
- } // loadChartData
-
- public String getReportDataSQL(String userId, int downloadLimit, HttpServletRequest request) throws RaptorException {
- String reportSQL = "";
- if(doesReportContainsGroupFormField()) {
- reportSQL = generateSubsetSQL(0, downloadLimit,userId, request, true, reportParamValues);
- } else
- reportSQL = generateSubsetSQL(0, downloadLimit,userId, request, false, reportParamValues);
- return reportSQL;
- }
-
- public ReportData loadReportData(int pageNo, String userId, int downloadLimit, HttpServletRequest request, boolean download) throws RaptorException {
- ReportData rd = null;
- boolean isGoBackAction = AppUtils.getRequestFlag(request, AppConstants.RI_GO_BACK);
- if (pageNo >= 0)
- if (pageNo == cachedPageNo && pageDataCache != null)
- rd = pageDataCache;
-
- if(isGoBackAction && rd!=null) return rd;
- if (rd == null) { // Commented So that Data is refreshed from DB again
- if (getReportDataSize() < 0)
- if (getReportType().equals(AppConstants.RT_CROSSTAB))
- rd = loadCrossTabReportData(pageNo, userId, downloadLimit, request, download);
- else if (getReportType().equals(AppConstants.RT_LINEAR))
- rd = loadLinearReportData(pageNo, userId, downloadLimit, request, download);
- else
- throw new RuntimeException(
- "[ReportRuntime.loadReportData] Invalid report type");
-
- if (pageNo >= 0)
- if (Globals.getCacheCurPageData()) {
- pageDataCache = rd;
- cachedPageNo = pageNo;
- }
- } // if // Commented So that Data is refreshed from DB again
-
- return rd;
- } // loadReportData
-
- private ReportData loadCrossTabReportData(int pageNo, String userId, int downloadLimit, HttpServletRequest request, boolean download) throws RaptorException {
- String reportSQL = generateSQL(reportParamValues, userId, request);
- setWholeSQL(reportSQL);
- cachedSQL = reportSQL;
- wholeSQL = reportSQL;
- List reportCols = getAllColumns();
- // replace the request parameter specified in the drill down
- DataColumnType dataColumnRequest = getCrossTabValueColumn();
- reportSQL = parseReportSQLForDrillDownParams(reportSQL, dataColumnRequest, request);
-
-
- DataSet ds = null;
- // try {
- String dbInfo = getDBInfo();
- StringBuffer colNames = new StringBuffer();
- StringBuffer colExtraIdNames = new StringBuffer();
- StringBuffer colExtraDateNames = new StringBuffer();
-
-
- for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
- DataColumnType dc = (DataColumnType) iter.next();
- //TODO: commented if (dc.isVisible()) {
- if (colNames.length() > 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) {
- System.out.println("Drilldown URL " + dc.getDrillDownURL());
-
- }
- } // for
-
- if (reportSQL.toUpperCase().indexOf("GROUP BY ") < 0)
- colNames.append(colExtraIdNames.toString());
- colNames.append(colExtraDateNames.toString());
- //reportSQL = " SELECT ROWNUM rnum, "
- // + colNames.toString() + " FROM (" + reportSQL + ") ";
-
- String rSQL = Globals.getLoadCrosstabReportData();
- rSQL = rSQL.replace("[colNames.toString()]", colNames.toString());
- rSQL = rSQL.replace("[reportSQL]", reportSQL);
- reportSQL = rSQL;
- setWholeSQL(reportSQL);
- if (crossTabOrderManager == null)
- crossTabOrderManager = new CrossTabOrderManager(this, userId,request);
- ds = ConnectionUtils.getDataSet(reportSQL, dbInfo);
-
- ReportData rd = new ReportData(pageNo, false);
- ReportFormFields childReportFormFields = null;
- if(doesReportContainsGroupFormField()) {
- List reportCols1 = getAllColumns();
- reportCols = new Vector();
- outer:
- for (Iterator iter = reportCols1.iterator(); iter.hasNext();) {
- DataColumnType dct = (DataColumnType) iter.next();
- for (int k=0; k<ds.getColumnCount(); k++) {
- if(dct.getColId().toUpperCase().trim().equals(ds.getColumnName(k).trim())) {
- reportCols.add(dct);
- continue outer;
- }
- }
- }
-
- if (getFormFieldList() != null) {
- String paramValue = "";
- for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
- FormFieldType fft = (FormFieldType) iter.next();
- if(fft.isGroupFormField()!=null && fft.isGroupFormField().booleanValue()) {
- paramValue = Utils.oracleSafe(nvl(reportParamValues
- .getParamValue(fft.getFieldId())));
- outer:
- for (Iterator iter1 = reportCols1.iterator(); iter1.hasNext();) {
- DataColumnType dct = (DataColumnType) iter1.next();
- if(("["+fft.getFieldName()+ "]").equals(dct.getColName().trim())) {
- dct.setDisplayName(paramValue);
- continue outer;
- }
- }
-
-
- }
- }
- }
- }
-
- int dataColumnIdx = (rd.reportRowHeaderCols.size() + rd.reportColumnHeaderRows.size())-1;
- DataColumnType dataColumn = getCrossTabValueColumn();
-
- String columnValue = "";
-
-
- for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
- DataColumnType dct = (DataColumnType) iter.next();
-
- if (nvl(dct.getDrillDownURL()).length() > 0) {
- childReportFormFields = getChildReportFormFields(request,dct.getDrillDownURL());
- }
-
- if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_ROW)) {
- RowHeaderCol rhc = new RowHeaderCol();
- rhc.setColumnTitle(dct.getDisplayName());
- // rhc.setColumnWidth("10%");
- //rhc.setColumnWidth(dct.getDisplayWidth() + "%");
- if(nvl(dct.getDisplayWidthInPxls()).length()<=0) {
- dct.setDisplayWidthInPxls("100px");
- }
- if(dct.getDisplayWidthInPxls().endsWith("px"))
- rhc.setColumnWidth(dct.getDisplayWidthInPxls());
- else
- rhc.setColumnWidth(dct.getDisplayWidthInPxls()+"px");
-
- rhc.setAlignment(dct.getDisplayAlignment());
- rhc.setDisplayHeaderAlignment(dct.getDisplayHeaderAlignment());
- rhc.setNowrap(nvl(dataColumn.getNowrap(),"null").equals("false")?"null":nvl(dataColumn.getNowrap(),"null"));
- rd.reportRowHeaderCols.addRowHeaderCol(rhc);
- } else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_COLUMN)) {
- ColumnHeaderRow chr = new ColumnHeaderRow();
- chr.setAlignment(dct.getDisplayHeaderAlignment());
- chr.setRowHeight("15");
- if(nvl(dct.getDisplayWidthInPxls()).length()<=0) {
- dct.setDisplayWidthInPxls("80px");
- }
- if(dct.getDisplayWidthInPxls().endsWith("px"))
- chr.setDisplayWidth(dct.getDisplayWidthInPxls());
- else
- chr.setDisplayWidth(dct.getDisplayWidthInPxls()+"px");
-
- rd.reportColumnHeaderRows.addColumnHeaderRow(chr);
- } else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_VALUE)) {
- columnValue = dct.getColId();
- } else {
- if(!dct.getColId().toLowerCase().endsWith("_sort")) {
- RowHeaderCol rhc = new RowHeaderCol();
- rhc.setVisible(false);
- rd.reportRowHeaderCols.addRowHeaderCol(rhc);
- }
- }
- } // for
-
- //int dataColumnIdx = getCrossTabValueColumnIndex();
- FormatProcessor formatProcessor = new FormatProcessor(getSemaphoreById(dataColumn
- .getSemaphoreId()),
- getReportDefType().equals(AppConstants.RD_SQL_BASED) ? AppConstants.CT_NUMBER
- : dataColumn.getColType(), dataColumn.getColFormat(), false);
- List dataList = new ArrayList();
- /* //fillup all rows based on rowheaders
- Vector rowHeaders = crossTabOrderManager.getRowHeaderValues();
- CrossTabColumnValues crossTabRowValues;
- int size = 0;
- for (int i = 0; i < rowHeaders.size(); i++) {
- if((i+1)==rowHeaders.size()) {
- crossTabRowValues = (CrossTabColumnValues) rowHeaders.get(i);
- size = crossTabRowValues.getValuesCount();
- }
- }
-
- for (int i = 0; i < size; i++) {
- dataList.add(new DataRow());
- }*/
-
- for (int i = 0; i < ds.getRowCount(); i++) {
- Vector rValues = new Vector();
- Vector cValues = new Vector();
- Vector cValuesSort = new Vector();
-
- int colIdx = 0;
- for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
- try {
- DataColumnType dct = (DataColumnType) iter.next();
- if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_ROW))
- rValues.add(addDataValue(dct, ds.getString(i, dct.getColId())));
- if (nvl(dct.getCrossTabValue()).trim().length()<=0 && !dct.getColId().toLowerCase().endsWith("_sort"))
- rValues.add(addDataValue(dct, ds.getString(i, dct.getColId())));
- if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_COLUMN)) {
- cValues.add(addDataValue(dct, ds.getString(i, dct.getColId())));
- if(getColumnById(dct.getColId().toLowerCase()+"_sort")!=null)
- cValuesSort.add(addDataValue(dct, new Integer(ds.getString(i, dct.getColId()+"_sort")).toString()));
- }
- if (dct.isVisible())
- colIdx++;
- } catch (ArrayIndexOutOfBoundsException ex ) {continue;}
- catch (NumberFormatException ex1) {
- ex1.printStackTrace();
- continue;
- }
- } // for
-
- DataValue dv = new DataValue();
- dv.setDisplayValue(ds.getString(i, columnValue));
- if (nvl(dataColumn.getCrossTabValue()).trim().length()<=0)
- dv.setVisible(false);
- dv.setAlignment(dataColumn.getDisplayAlignment());
- dv.setDisplayTotal(dataColumn.getDisplayTotal());
- dv.setColName(dataColumn.getColName());
- dv.setDisplayName(dataColumn.getDisplayName());
- dv.setColId(dataColumn.getColId());
- dv.setNowrap(nvl(dataColumn.getNowrap(),"null").equals("false")?"null":nvl(dataColumn.getNowrap(),"null"));
- /*StringBuffer indentation = new StringBuffer("");
- if(dataColumn.getIndentation()!=null && dataColumn.getIndentation().intValue()>0) {
- for (int indent=0; indent < dataColumn.getIndentation(); indent++) {
- indentation.append("\t");
- }
- dv.setNowrap("true");
- }
- dv.setIndentation(indentation.toString());*/
-
- if (nvl(dataColumn.getDrillDownURL()).length() > 0) {
- if(dv.getDisplayValue().length() > 0) {
- dv.setDrillDownURL(parseDrillDownURL(i, /* dataColumnIdx, */ds, dataColumn,request, childReportFormFields));
- dv.setDrillDowninPoPUp(dataColumn.isDrillinPoPUp()!=null?dataColumn.isDrillinPoPUp():false);
- }
- if (dv.getDisplayValue().length() == 0) {
- //dv.setDisplayValue("[NULL]");
- dv.setDisplayValue("");
- }
- } // if
-
- rd.setDataValue(rValues, cValues, cValuesSort.size()==0?null:cValuesSort, dv, formatProcessor, crossTabOrderManager, dataList);
- } // for
- rd.setReportDataList(dataList);
- /*if (getReportDataSize() < 0)
- setReportDataSize(rd.getDataRowCount());*/
-
- /*if (pageNo >= 0)
- rd.truncateData(pageNo * getPageSize(), (pageNo + 1) * getPageSize() - 1);
- else {
- if( downloadLimit != -1)
- rd.truncateData(0, downloadLimit - 1);
- else
- rd.truncateData(0, -1);
- }*/
-
- if (colDataTotalsCrosstab == null)
- colDataTotalsCrosstab = generateDataTotalsCrossTab(AppConstants.CV_COLUMN, userId,request);
- if (displayColTotals && colDataTotalsCrosstab != null)
- rd.setColumnDataTotalsCrossTab(colDataTotalsCrosstab, dataColumn
- .getDisplayAlignment(), getCrossTabDisplayTotal(AppConstants.CV_COLUMN),
- crossTabOrderManager, dataList);
-
- if (rowDataTotalsCrosstab == null)
- rowDataTotalsCrosstab = generateDataTotalsCrossTab(AppConstants.CV_ROW, userId, request);
- if (displayRowTotals && rowDataTotalsCrosstab != null)
- rd.setRowDataTotalsCrossTab(rowDataTotalsCrosstab, dataColumn
- .getDisplayAlignment(), getCrossTabDisplayTotal(AppConstants.CV_ROW),
- crossTabOrderManager, dataList);
-
- if (displayColTotals
- && displayRowTotals
- && getCrossTabDisplayTotal(AppConstants.CV_COLUMN).equals(
- getCrossTabDisplayTotal(AppConstants.CV_ROW))) {
- // Display grand total
- if (grandTotalCrosstab == null)
- grandTotalCrosstab = ((CrossTabTotalValue) generateDataTotalsCrossTab("",
- userId,request).get(0)).getTotalValue();
- if (grandTotalCrosstab != null)
- rd.setGrandTotalCrossTab(Utils.truncateTotalDecimals(grandTotalCrosstab),
- dataColumn.getDisplayAlignment(),
- getCrossTabDisplayTotal(AppConstants.CV_COLUMN), dataList);
- } // if
-
- rd.consolidateColumnHeaders(visualManager);
- //if (Globals.getMergeCrosstabRowHeadings())
- // rd.consolidateRowHeaders();
- //rd.addRowNumbers(pageNo, dataList);
-
- if (displayColTotals && colDataTotalsCrosstab != null) {
- String totalLabel = "Total";
- String colDisplayTotal = getCrossTabDisplayTotal(AppConstants.CV_COLUMN);
- if (colDisplayTotal.length() > 0
- && (!colDisplayTotal.equals(AppConstants.TOTAL_SUM_ID)))
- totalLabel = nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(colDisplayTotal));
- if (getReportDataSize() > getPageSize())
- totalLabel += "_nl_(for all pages)";
-
- //rd.setCrossTabColumnTotalLabel(totalLabel);
- } // if
-
- //rd.applyVisibility();
- //Collections.sort((List)dataList, new DataRowComparable());
- DataRow drInFor1 = null;
- Vector<DataValue> v1= null, v2 = null;
- ArrayList<String> temp = new ArrayList<String>();
- if (Globals.getMergeCrosstabRowHeadings()) {
- for (int i = 0; i < dataList.size(); i++) {
- drInFor1 = (DataRow)dataList.get(i);
- drInFor1.setRowNum(i+1);
- v1 = drInFor1.getRowValues();
- if(i<dataList.size()-1) {
- v2 = ((DataRow)dataList.get(i+1)).getRowValues();
- } /*else {
- v2 = ((DataRow)dataList.get(i-1)).getRowValues();
- }*/
- for (int j = 0; j < v1.size(); j++) {
- if(j==0) {
- if(v1.get(j).getDisplayValue().length()>0) { // another ArrayList
- temp = new ArrayList();
- temp.add(v1.get(j).getDisplayValue());
- }
- if(v2!=null && temp.get(j).equals(v2.get(j).getDisplayValue())) {
- v2.get(j).setDisplayValue("");
- }
- }
- }
- }
- }
- rd.setReportDataList(dataList);
- if (getReportDataSize() < 0) {
- //setReportDataSize(rd.getDataRowCount());
- setReportDataSize(rd.getReportDataList().size());
- }
-
- return rd;
- } // loadCrossTabReportData
-
-
- public DataValue addDataValue(DataColumnType dataColumn, String columnValue) {
- DataValue dv = new DataValue();
- dv.setDisplayValue(columnValue);
- if (nvl(dataColumn.getCrossTabValue()).trim().length()<=0)
- dv.setVisible(false);
- dv.setAlignment(dataColumn.getDisplayAlignment());
- dv.setDisplayTotal(dataColumn.getDisplayTotal());
- dv.setColName(dataColumn.getColName());
- dv.setDisplayName(dataColumn.getDisplayName());
- dv.setColId(dataColumn.getColId());
- dv.setNowrap(nvl(dataColumn.getNowrap(),"null").equals("false")?"null":nvl(dataColumn.getNowrap(),"null"));
- return dv;
-
- }
-
- /*private*/ public boolean doesReportContainsGroupFormField() {
- int flag = 0;
- if(getFormFieldList()!=null) {
- for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
- FormFieldType fft = (FormFieldType) iter.next();
- if(fft.isGroupFormField()!=null && fft.isGroupFormField().booleanValue()) {
- flag = 1;
- break;
- }
- }
- }
- return (flag ==1);
- }
-
- private ReportData loadLinearReportData(int pageNo, String userId, int downloadLimit, HttpServletRequest request, boolean download) throws RaptorException {
- String action = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action"));;
-
- String reportSQL = "";
-
- if(action.endsWith("session")) {
- reportSQL = getWholeSQL();
- wholeSQL = reportSQL;
- } else {
- reportSQL = generateSQL(reportParamValues, visualManager.getSortByColId(),
- visualManager.getSortByAscDesc(), userId, request);
- wholeSQL = reportSQL;
- setWholeSQL(wholeSQL);
- }
- DataSet ds = null;
- String dbInfo = getDBInfo();
- ds = ConnectionUtils.getDataSet(wholeSQL, dbInfo);
- setReportDataSize(ds.getRowCount());
- //wholeSQL = reportSQL;
- HttpSession session = request.getSession();
- //debugLogger.debug(" ******** Download Limit ********* " + downloadLimit + " %%%%%%%%%%PAGE " + pageNo );
- List reportCols = null;
- StringBuffer colNames = new StringBuffer();
-
- if(download && action.endsWith("session")) {
- reportCols = getAllColumns();
- 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());
- }
-
- }
- else {
- String pagedSQL = null; // reportSQL;
- if (pageNo >= 0)
- pagedSQL = generatePagedSQL(pageNo, userId, request, false, null);
- else
- pagedSQL = generateSubsetSQL(0, downloadLimit, userId, request, false, null);
- // replace the request parameter specified in the drill down
- reportCols = getAllColumns();
- 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());
- if (dc.isVisible()) {
- reportSQL = parseReportSQLForDrillDownParams(reportSQL, dc, request);
- pagedSQL = parseReportSQLForDrillDownParams(pagedSQL, dc, request);
- }
- }
-
- cachedSQL = pagedSQL;
-
-
- // try {
- if(doesReportContainsGroupFormField()) {
- if (pageNo >= 0)
- pagedSQL = generatePagedSQL(pageNo, userId, request, true, reportParamValues);
- else
- pagedSQL = generateSubsetSQL(0, downloadLimit, userId, request, true, reportParamValues);
- }
- //check for Group formfield
- //if groupformfield get columns from sql
-
- ds = ConnectionUtils.getDataSet(pagedSQL, dbInfo);
-
- if(doesReportContainsGroupFormField()) {
- List reportCols1 = getAllColumns();
- reportCols = new Vector();
- outer:
- for (Iterator iter = reportCols1.iterator(); iter.hasNext();) {
- DataColumnType dct = (DataColumnType) iter.next();
- for (int k=0; k<ds.getColumnCount(); k++) {
- if(dct.getColId().toUpperCase().trim().equals(ds.getColumnName(k).trim())) {
- reportCols.add(dct);
- continue outer;
- }
- }
- }
-
- if (getFormFieldList() != null) {
- String paramValue = "";
- for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
- FormFieldType fft = (FormFieldType) iter.next();
- if(fft.isGroupFormField()!=null && fft.isGroupFormField().booleanValue()) {
- paramValue = Utils.oracleSafe(nvl(reportParamValues
- .getParamValue(fft.getFieldId())));
- outer:
- for (Iterator iter1 = reportCols1.iterator(); iter1.hasNext();) {
- DataColumnType dct = (DataColumnType) iter1.next();
- if(("["+fft.getFieldName()+ "]").equals(dct.getColName().trim())) {
- dct.setDisplayName(paramValue);
- continue outer;
- }
- }
-
-
- }
- }
- }
- }
-
-
- // if ( (remDbInfo!=null) && (!remDbInfo.equals(AppConstants.DB_LOCAL)))
- // {
- // Globals.getRDbUtils().setDBPrefix(remDbInfo);
- // ds = RemDbUtils.executeQuery(pagedSQL);
- // }
- // else
- // ds = DbUtils.executeQuery(pagedSQL);
- /*
- * } catch(SQLException e) { throw new
- * ReportSQLException("[ReportRuntime.loadLinearReportData]
- * "+e.getMessage(), pagedSQL); }
- */
-
- if (getReportDataSize() < 0)
- if (pageNo < 0)
- setReportDataSize(ds.getRowCount());
- else if (ds.getRowCount() <= getPageSize())
- setReportDataSize(ds.getRowCount());
- else {
-
- /*Pattern re1 = Pattern.compile("[Oo][Rr][Dd][Ee][Rr](.*?[^\r\n]*)[Bb][Yy]", Pattern.DOTALL);
- Pattern re2 = Pattern.compile("[Oo][Rr][Dd][Ee][Rr](.*?[^\r\n]*)[Bb][Yy]((.*?[^\r\n]*)|[\\s]|[^0-9a-zA-Z])\\)", Pattern.DOTALL);
- Matcher matcher = re1.matcher(reportSQL);
- Matcher matcher2 = null;
- int startPoint = reportSQL.length()-30;
- String startReportSQL = "";
- String endReportSQL = "";
- while(reportSQL.indexOf("xid", startPoint)!=-1)startPoint++;
- if (matcher.find(startPoint)) {
- startReportSQL = reportSQL.substring(0, reportSQL.indexOf(matcher.group()));
- endReportSQL = reportSQL.substring(reportSQL.indexOf(matcher.group()));
- matcher2 = re2.matcher(endReportSQL);
- if(matcher2.find())
- endReportSQL = endReportSQL.substring(matcher.group().length()-1);
- else
- endReportSQL = "";
- reportSQL = startReportSQL + endReportSQL;
- }*/
- String countSQL = "SELECT count(*) FROM (" + reportSQL + ")"+ (Globals.isPostgreSQL() || Globals.isMySQL()?" AS ":"") +" x ";
- 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);
- if (dbType.equals("DAYTONA") && reportSQL.trim().toUpperCase().startsWith("SELECT")) {
- Pattern re1 = Pattern.compile("order(.*?[^\r\n]*)by", Pattern.DOTALL);
- Matcher matcher = re1.matcher(reportSQL);
- int startPoint = reportSQL.length()-30;
- while(reportSQL.indexOf("xid", startPoint)!=-1)startPoint++;
- if (matcher.find(startPoint)) {
- reportSQL = reportSQL.substring(0, reportSQL.indexOf(matcher.group()));
- }
- countSQL = "SELECT count(*) FROM (" + reportSQL + ")"+ (Globals.isPostgreSQL() || Globals.isMySQL()?" AS ":"") +" x";
- countSQL = countSQL + " ("+ colNames+ ")";
- } else if (dbType.equals("DAYTONA")) {
- setReportDataSize(50);
- }
- } catch (Exception ex) {
- throw new RaptorException(ex);
- }
- }
-
- DataSet ds2 = null;
- // try {
- if(reportSQL.trim().toUpperCase().startsWith("SELECT")) {
- ds2 = ConnectionUtils.getDataSet(countSQL, dbInfo);
- if (ds2.getRowCount() > 0)
- setReportDataSize(ds2.getInt(0, 0));
- else
- throw new RuntimeException(
- "[ReportRuntime.loadLinearReportData] Unable to load report data size");
- } else
- setReportDataSize(50);
- // if ( (remDbInfo!=null) &&
- // (!remDbInfo.equals(AppConstants.DB_LOCAL))){
- // Globals.getRDbUtils().setDBPrefix(remDbInfo);
- // ds2 = RemDbUtils.executeQuery(countSQL);
- // }
- // else
- // ds2 = DbUtils.executeQuery(countSQL);
- /*
- * } catch(SQLException e) { throw new
- * ReportSQLException("[ReportRuntime.loadLinearReportData size]
- * "+e.getMessage(), countSQL); }
- */
-
-
- } // else
- }
- ReportData rd = new ReportData(pageNo, true);
-
- // 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 = 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(
- getSemaphoreById(dc.getSemaphoreId()), dc.getColType(), dc
- .getColFormat(), getReportDefType().equals(
- AppConstants.RD_SQL_BASED)));
-
- if (nvl(dc.getDrillDownURL()).length() > 0) {
- childReportFormFields = getChildReportFormFields(request,AppUtils.getDrillActionURL()+""+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);
- }
- }
- }
- //}
-
- String widthInPxls = dc.getDisplayWidthInPxls();
-
- if(nvl(widthInPxls).endsWith("px"))
- dc.setDisplayWidthInPxls(widthInPxls);
- else {
- widthInPxls = widthInPxls+"px";
- dc.setDisplayWidthInPxls(widthInPxls+"px");
- }
-
- rd.createColumn(dc.getColId(), dc.getDisplayName(), dc.getDisplayWidthInPxls(), dc.getDisplayHeaderAlignment(),
- visualManager.isColumnVisible(dc.getColId()), visualManager
- .getSortByColId().equals(dc.getColId()) ? visualManager
- .getSortByAscDesc() : null, isRuntimeColSortDisabled(), 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(),
- true, 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
-
- if(getReportDefType().equals(AppConstants.RD_SQL_BASED_DATAMIN) && pageNo ==0) {
- /*Vector v = null;
- try {
- v = addForecastData(reportSQL);
- } catch (Exception ex) {
- ex.printStackTrace();
- throw new RaptorException (ex);
- }
- session.setAttribute("FORECASTED_DATA", v);
- DataSet dsWhole = ConnectionUtils.getDataSet(wholeSQL, dbInfo);
- dsWhole.addAll(v);
- session.setAttribute(AppConstants.RI_CHART_FORECAST_DATA, dsWhole);
- }
-
- if(getReportDefType().equals(AppConstants.RD_SQL_BASED_DATAMIN) && session.getAttribute("FORECASTED_DATA")!=null) {
- Vector vForecastedData = (Vector)session.getAttribute("FORECASTED_DATA");
- if(vForecastedData.size() > 0)
- ds.addAll(vForecastedData);*/
- }
-
-
- // 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
- for (int r = 0; r < Math.min(ds.getRowCount(), ((pageNo < 0) ? (downloadLimit == -1?Globals.getFlatFileUpperLimit():Globals.getDownloadLimit() ) : getPageSize())); 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);
- DataValue dv = new DataValue();
- dr.addDataValue(dv);
- dv.setDisplayValue(ds.getString(r, c));
- dv.setColName(dct.getColName());
- dv.setColId(dct.getColId());
- dv.setNowrap(nvl(dct.getNowrap(),"null").equals("false")?"null":nvl(dct.getNowrap(),"null"));
- 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) {
- dv.setDrillDownURL(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
-
- } 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
- } // for
-
- //Only if rownumber options is needed
- //rd.addRowNumbers(pageNo, getPageSize());
-
- if (colDataTotalsLinear == null) {
- if(!download && !action.endsWith("session"))
- colDataTotalsLinear = generateColumnDataTotalsLinear(new ArrayList(reportCols), userId,
- getDbInfo(),request);
- if(download && action.endsWith("session"))
- colDataTotalsLinear = generateColumnDataTotalsLinear(new ArrayList(reportCols), userId,
- getDbInfo(), getTotalSql());
- }
- if (displayColTotals && colDataTotalsLinear != null) {
- String totalLabel = "Total";
- if (getReportDataSize() > getPageSize())
- totalLabel += "<br><font size=1>(for all pages)</font>";
-
- rd.setColumnDataTotalsLinear(colDataTotalsLinear, totalLabel);
- } // if
- // 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 DataRow generateColumnDataTotalsLinear(ArrayList reportCols, String userId,
- String dbInfo, String reportSQL) throws RaptorException {
- DataRow dr = null;
-
- boolean displayColTotals = false;
- for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
-
- DataColumnType dct = (DataColumnType) iter.next();
- if( dct != null ) {
- if (nvl(dct.getDisplayTotal()).length() > 0) {
- displayColTotals = true;
- break;
- } // if
- } // if checking dct
- } // for
-
- DataSet ds = null;
- if (displayColTotals) {
- dr = new DataRow();
- // ds =
- // DbUtils.executeQuery(generateTotalSQLLinear(reportParamValues,
- // userId));
- ds = ConnectionUtils.getDataSet(reportSQL,
- dbInfo);
-
- for (int c = 0; c < reportCols.size(); c++) {
- DataColumnType dct = (DataColumnType) reportCols.get(c);
- if ( dct != null ) {
- DataValue dv = new DataValue();
-
- String totalValue = "";
- if (ds != null)
- totalValue = ds.getString(0, c);
- if (nvl(dct.getDisplayTotal()).length() > 0
- && (!dct.getDisplayTotal().equals(AppConstants.TOTAL_SUM_ID)))
- totalValue = nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(dct
- .getDisplayTotal()))
- + ": " + totalValue;
- dv.setDisplayValue(Utils.truncateTotalDecimals(totalValue));
-
- dv.setAlignment(dct.getDisplayAlignment());
- dv.setColName(dct.getColName());
- dv.setDisplayName(dct.getDisplayName());
- dv.setColId(dct.getColId());
- dv.setNowrap(nvl(dct.getNowrap(),"null").equals("false")?"null":nvl(dct.getNowrap(),"null"));
- 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());
- dv.setDisplayTotal(dct.getDisplayTotal());
- dv.setBold(true);
- dv.setVisible(dct.isVisible());
- if(dv.isVisible())
- dr.addDataValue(dv);
- } // dct check
- } // for
- }
-
- return dr;
- } // generateColumnDataTotalsLinear
-
-
- public ReportData loadHiveLinearReportData(String reportSQL, String userId, int downloadLimit, HttpServletRequest request) throws RaptorException {
- wholeSQL = reportSQL;
- int countRows = getHiveReportCount(wholeSQL);
- setReportDataSize(countRows);
- if(countRows < 1001)
- wholeSQL += " limit "+ countRows;
- else
- wholeSQL += " limit "+ downloadLimit;
- HttpSession session = request.getSession();
-
- DataSet ds = null;
- // try {
- String dbInfo = getDBInfo();
-
- List reportCols = getAllColumns();
- 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());
- }
-
- ds = ConnectionUtils.getDataSet(wholeSQL, dbInfo);
-
- ReportData rd = new ReportData(0, true);
-
- // 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 = 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(
- getSemaphoreById(dc.getSemaphoreId()), dc.getColType(), dc
- .getColFormat(), getReportDefType().equals(
- AppConstants.RD_SQL_BASED)));
-
- if (nvl(dc.getDrillDownURL()).length() > 0) {
- childReportFormFields = 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);
- }
- }
- }
- //}
-
- String widthInPxls = dc.getDisplayWidthInPxls();
-
- if(nvl(widthInPxls).endsWith("px"))
- dc.setDisplayWidthInPxls(widthInPxls);
- else {
- widthInPxls = widthInPxls+"px";
- dc.setDisplayWidthInPxls(widthInPxls+"px");
- }
-
- rd.createColumn(dc.getColId(), dc.getDisplayName(), dc.getDisplayWidthInPxls(), dc.getDisplayHeaderAlignment(),
- visualManager.isColumnVisible(dc.getColId()), visualManager
- .getSortByColId().equals(dc.getColId()) ? visualManager
- .getSortByAscDesc() : null, isRuntimeColSortDisabled(), 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(), "", dc.getDisplayWidthInPxls(), dc.getDisplayHeaderAlignment(),
- true, 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
-
- ArrayList reportDataList = new ArrayList();
- for (int r = 0; r < ds.getRowCount(); 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);
- DataValue dv = new DataValue();
- dr.addDataValue(dv);
- dv.setDisplayValue(ds.getString(r, c));
- dv.setColName(dct.getColName());
- dv.setColId(dct.getColId());
- dv.setNowrap(nvl(dct.getNowrap(),"null").equals("false")?"null":nvl(dct.getNowrap(),"null"));
- 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) {
- dv.setDrillDownURL(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
-
- } 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());
-
- if (colDataTotalsLinear == null)
- colDataTotalsLinear = generateColumnDataTotalsLinear(new ArrayList(reportCols), userId,
- getDbInfo(),request);
- if (displayColTotals && colDataTotalsLinear != null) {
- String totalLabel = "Total";
- if (getReportDataSize() > getPageSize())
- totalLabel += "<br><font size=1>(for all pages)</font>";
-
- rd.setColumnDataTotalsLinear(colDataTotalsLinear, totalLabel);
- } // if
- // Please note the below function doesn't set the visibility for dv since this is set in this function. - Sundar
- rd.applyVisibility();
-
- return rd;
- } // loadHiveLinearReportData
-
- //For Hive reports
- public int getHiveReportCount(String sql) throws RaptorException {
- //select t from (select count(*) t from (select * from program)x)x1;
- int count = 0;
- String countSql = "select t from (select count(*) t from ("+ sql + ")" + (Globals.isPostgreSQL() || Globals.isMySQL() ?" AS ":"") + " x) AS x1";
-
- DataSet ds = null;
- // try {
- String dbInfo = getDBInfo();
- System.out.println("SQL getReportCount()- " + countSql);
- try {
- ds = ConnectionUtils.getDataSet(countSql, dbInfo);
- int totalRows = 0;
- 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);
- }
- }
- if( ds.getRowCount()>0) {
- count = Integer.parseInt(ds.getString(0,0));
- }
- } catch (NumberFormatException ex) {}
- return count;
-
- } // getReportCount
-
-
- /*private*/ public ReportFormFields getChildReportFormFields( HttpServletRequest request, String URL ) throws RaptorException {
- String childReportID = getReportID(URL);
-
- ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, childReportID,
- false, 1);
-
- ReportFormFields ddReportFormFields = ddRr.getReportFormFields();
- return ddReportFormFields;
- }
-
- private String getReportID(String URL) {
- URL = nvl(URL);
- int pos = URL.toLowerCase().indexOf("c_master=")+9;
- String reportID = "";
- if(URL.toLowerCase().indexOf("&", pos)!=-1)
- reportID = URL.substring(pos, URL.toLowerCase().indexOf("&", pos));
- else
- reportID = URL.substring(pos);
- return reportID;
-
- }
- /*private*/ public String parseDrillDownURL(int rowIdx, /* int colIdx, */DataSet ds, DataColumnType dct, HttpServletRequest request, ReportFormFields ddReportFormFields)
- throws RaptorException {
- Vector viewActions = DataCache.getDataViewActions();
- javax.servlet.http.HttpSession session = request.getSession();
-
- StringBuffer dUrl = new StringBuffer();
-
- //String childReportID = getReportID(dct.getDrillDownURL());
-
- //ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, childReportID,
- // false, 1);
-
- //ReportFormFields ddReportFormFields = ddRr.getReportFormFields();
-
- boolean isViewAction = false;
- int flag = 0;
- String requestParam ="";
- for (int k = 0; k < viewActions.size(); k++)
- if (dct.getDrillDownURL().equals(
- AppUtils.getBaseActionURL() + ((String) viewActions.get(k))))
- isViewAction = true;
- if (isViewAction) {
- // Drill-down to record details
- String param = nvl(dct.getDrillDownParams()); // i.e.
- // "c_master=[bo1.RECID$]"
- param = param.substring(AppUtils.getBaseActionParam().length() + 1,
- param.length() - 1); // i.e. "bo1.RECID$"
- param = param.replace('.', '_'); // i.e. "bo1.RECID$"
-
- dUrl.append(AppUtils.getBaseActionParam());
- dUrl.append(java.net.URLEncoder.encode(ds.getString(rowIdx, param.toLowerCase())));
- } else {
- // Drill-down to another report
- // Replacing col ids with values
- String param = nvl(dct.getDrillDownParams());
- while (param.indexOf('[') >= 0) {
- int startIdx = param.indexOf('[');
- int endIdx = param.indexOf(']');
- StringBuffer sb = new StringBuffer();
- if(startIdx>endIdx) {
- if (endIdx < param.length() - 1)
- sb.append(param.substring(endIdx + 1));
- param = sb.toString();
- continue;
- }
- if (startIdx > 0)
- sb.append(param.substring(0, startIdx));
-
- if (param.charAt(startIdx + 1) == '!') {
- // Parameter is a form field value
- String fieldId = param.substring(startIdx + 2, endIdx);
- String fieldValue = (String) reportParamValues.get(fieldId);
-
- sb.append(java.net.URLEncoder.encode(nvl(fieldValue)));
- //TODO Add a else if condition to check whether the param is from request Param
- //TODO make a unique symbol like #
- }else if (param.charAt(startIdx + 1) == '#') {
- flag = 1;
- String fieldId = param.substring(startIdx + 2, endIdx);
- String fieldValue = request.getParameter(fieldId);
- sb.append(java.net.URLEncoder.encode(nvl(fieldValue)));
-
- }else {
- // Parameter is a column value
- String fieldValue = "";
- String colValue = null;
- String colId = null;
- if (param.indexOf('!') < 0 || param.indexOf('!') > endIdx)
- colId = param.substring(startIdx + 1, endIdx);
- else {
- // Need to use NVL(column, form field)
- colId = param.substring(startIdx + 1, param.indexOf('!'));
-
- String fieldId = param.substring(param.indexOf('!') + 1, endIdx);
- FormField ff = getFormField(fieldId);
- if (ff.getFieldType().equals(FormField.FFT_TEXTAREA)) {
- fieldValue = reportParamValues.getParamValueforTextAreaDrilldown(fieldId);
- } else
- fieldValue = (String) reportParamValues.get(fieldId);
- } // else
-
- DataColumnType column = getColumnById(colId);
- String columnName = "";
- int groupColumn = 0;
- int groupMatch = 0;
- if(column.getColName().startsWith("[")) {
- groupColumn = 1;
- columnName = column.getDisplayName();
- for(ddReportFormFields.resetNext(); ddReportFormFields.hasNext(); ) {
- FormField ff = ddReportFormFields.getNext();
- if(ff.getFieldDisplayName().toLowerCase().equals(columnName.toLowerCase())) {
- groupMatch = 1;
- sb.delete(sb.lastIndexOf("&")+1, sb.length());
- sb.append(ff.getFieldName()+"=");
- }
- }
- }
- if (groupColumn == 0 || (groupColumn == 1 && groupMatch == 1)) {
- String dependsOn = column.getDependsOnFormField();
- if(nvl(dependsOn).length()>0)
- System.out.println("DependsOn " + dependsOn);
- if (column != null) {
- // if (column.getColType().equals(AppConstants.CT_DATE))
- //if (!nvl(column.getColFormat(), AppConstants.DEFAULT_DATE_FORMAT)
- // .equals(AppConstants.DEFAULT_DATE_FORMAT))
- // Use extra column instead
- //commented out below line usually for Visual
- //colId += AppConstants.DD_COL_EXTENSION;
- colValue = ds.getString(rowIdx, colId.toLowerCase());
- // if SQL-Based and drill-down param is a date, decode
- // it to the expected Oracle format **/
- if (getReportDefType().equals(AppConstants.RD_SQL_BASED))
- if (!getColumnNoParseDateFlag(column))
- if (ReportParamDateValueParser.isDateParam(colValue))
- colValue = ReportParamDateValueParser
- .formatDateParamValue(colValue);
- } // if
-
- String suppressValues = "|" + nvl(dct.getDrillDownType()) + "|";
- if (suppressValues.length() > 2
- && suppressValues.indexOf("|" + colValue + "|") >= 0)
- // Parameter value is suppressed and not passed to the
- // drill-down report
- colValue = null;
-
- sb.append(java.net.URLEncoder.encode(nvl(colValue, fieldValue)));
- } else {
- sb.delete(sb.lastIndexOf("&")+1, sb.length());
- }
- } // else
-
- if (endIdx < param.length() - 1)
- sb.append(param.substring(endIdx + 1));
- param = sb.toString();
- } // while
- if(Globals.getPassRequestParamInDrilldown()) {
- if(param.indexOf('#') < 0) {
- String[] reqParameters = Globals.getRequestParams().split(",");
- String[] sessionParameters = Globals.getSessionParams().split(",");
- for (int i = 0; i < reqParameters.length; i++) {
- if(request.getParameter(reqParameters[i])!=null) {
- if(!reqParameters[i].toUpperCase().startsWith("FF")){
- if(param.length()>0) {
- param += "&" + reqParameters[i]+"="
- + request.getParameter(reqParameters[i]);
- } else {
- param += "&" + reqParameters[i]+"="
- + request.getParameter(reqParameters[i]);
-
- }
- }
- }
- }
- for (int i = 0; i < sessionParameters.length; i++) {
- if(session.getAttribute(sessionParameters[i].toUpperCase())!=null) {
- if(!sessionParameters[i].toUpperCase().startsWith("FF")){
- if(param.length()>0) {
- param += "&" + sessionParameters[i].toUpperCase()+"="
- + (String)session.getAttribute(sessionParameters[i].toUpperCase());
- } else {
- param += "&" + sessionParameters[i].toUpperCase()+"="
- + (String)session.getAttribute(sessionParameters[i].toUpperCase());
-
- }
- }
- } else {
- param += "&" + sessionParameters[i].toUpperCase()+"="
- + (String)session.getAttribute(sessionParameters[i]);
-
- }
- }
-
- }
- }
-
- dUrl.append(param.toString());
- dUrl.append("&");
- dUrl.append(AppConstants.RI_DISPLAY_CONTENT);
- dUrl.append("=Y");
- dUrl.append("&");
- if(dct.isDrillinPoPUp()==null || (!dct.isDrillinPoPUp().booleanValue())) {
- dUrl.append(AppConstants.RI_SHOW_BACK_BTN);
- dUrl.append("=Y");
- dUrl.append("&");
- }
- dUrl.append(AppConstants.DRILLDOWN_INDEX);
- int index = Integer.parseInt(nvl(AppUtils.getRequestValue(request, AppConstants.DRILLDOWN_INDEX), "0"));
- /*
- int form_index = Integer.parseInt(nvl(AppUtils.getRequestValue(request, AppConstants.FORM_DRILLDOWN_INDEX), "0"));
- index = index>0 ? --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));*/
-
- dUrl.append("=" + AppUtils.getRequestNvlValue(request, AppConstants.DRILLDOWN_INDEX));
-
- //TODO Add a if condition to check whether the param is request Param
- } // if
-
- if (dUrl.length() > 0)
- dUrl.insert(0, ((dct.getDrillDownURL()).indexOf('&') > 0) ? '&' : '&');
- dUrl.insert(0, AppUtils.getDrillActionURL()+dct.getDrillDownURL());
-
- //debugLogger.debug(" [[[[[[[[[[[[[[[[ " + dUrl);
-
- return dUrl.toString();
- } // parseDrillDownURL
-
- /** *********************************************************************************** */
-
- public DataRow generateColumnDataTotalsLinear(ArrayList reportCols, String userId,
- String dbInfo, HttpServletRequest request) throws RaptorException {
- DataRow dr = null;
-
- displayColTotals = false;
- for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
-
- DataColumnType dct = (DataColumnType) iter.next();
- if( dct != null ) {
- if (nvl(dct.getDisplayTotal()).length() > 0) {
- displayColTotals = true;
- break;
- } // if
- } // if checking dct
- } // for
-
- DataSet ds = null;
- if (displayColTotals) {
- dr = new DataRow();
- // ds =
- // DbUtils.executeQuery(generateTotalSQLLinear(reportParamValues,
- // userId));
- ds = ConnectionUtils.getDataSet(generateTotalSQLLinear(reportParamValues, userId,request),
- dbInfo);
-
- for (int c = 0; c < reportCols.size(); c++) {
- DataColumnType dct = (DataColumnType) reportCols.get(c);
- if ( dct != null ) {
- DataValue dv = new DataValue();
- if(dv.isVisible())
- dr.addDataValue(dv);
-
- String totalValue = "";
- if (ds != null)
- totalValue = ds.getString(0, c);
- if (nvl(dct.getDisplayTotal()).length() > 0
- && (!dct.getDisplayTotal().equals(AppConstants.TOTAL_SUM_ID)))
- totalValue = nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(dct
- .getDisplayTotal()))
- + ": " + totalValue;
- dv.setDisplayValue(Utils.truncateTotalDecimals(totalValue));
-
- dv.setAlignment(dct.getDisplayAlignment());
- dv.setColName(dct.getColName());
- dv.setDisplayName(dct.getDisplayName());
- dv.setColId(dct.getColId());
- dv.setNowrap(nvl(dct.getNowrap(),"null").equals("false")?"null":nvl(dct.getNowrap(),"null"));
- 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());
- dv.setDisplayTotal(dct.getDisplayTotal());
- dv.setBold(true);
- } // dct check
- } // for
- }
-
- return dr;
- } // generateColumnDataTotalsLinear
-
- private Vector generateDataTotalsCrossTab(String rowColPos, String userId, HttpServletRequest request)
- throws RaptorException {
- String sql = getWholeSQL();
- Vector dataTotals = new Vector();
-
- boolean displayTotals = ((rowColPos.length() == 0) || (getCrossTabDisplayTotal(
- rowColPos).length() > 0));
- if (rowColPos.equals(AppConstants.CV_COLUMN))
- displayColTotals = displayTotals;
- else if (rowColPos.equals(AppConstants.CV_ROW))
- displayRowTotals = displayTotals;
-
- if (displayTotals) {
- // DataSet ds =
- // DbUtils.executeQuery(generateTotalSQLCrossTab(reportParamValues,
- // rowColPos, userId));
- String executeSql = generateTotalSQLCrossTab(
- sql, rowColPos, userId, request, reportParamValues);
- DataSet ds = ConnectionUtils.getDataSet(executeSql, getDbInfo());
-
- for (int i = 0; i < ds.getRowCount(); i++) {
- Vector headerValues = new Vector();
- String totalValue = null;
-
- int cPos = 0;
- for (Iterator iter = getAllColumns().iterator(); iter.hasNext();) {
- DataColumnType dct = (DataColumnType) iter.next();
-
- if (rowColPos.length() > 0
- && nvl(dct.getCrossTabValue()).equals(rowColPos)) {
- DataValue dataValue = new DataValue();
- dataValue.setBold(true);
- dataValue.setAlignment("center");
- dataValue.setDisplayValue(ds.getString(i, cPos++));
- headerValues.add(dataValue);
-
- //headerValues.add(ds.getString(i, cPos++));
- }
- else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_VALUE))
- totalValue = ds.getString(i, cPos++);
- } // for
-
- dataTotals.add(new CrossTabTotalValue(headerValues, Utils
- .truncateTotalDecimals(totalValue)));
- } // for
- } // if
-
- return dataTotals;
- } // generateDataTotalsCrossTab
-
- /** *********************************************************************************** */
-
- public void hideColVisual(String colId) {
- visualManager.hideColumn(colId);
- if (pageDataCache != null)
- pageDataCache.columnVisualShowHide(colId, false);
- } // hideColVisual
-
- public void showColVisual(String colId) {
- visualManager.showColumn(colId);
- if (pageDataCache != null)
- pageDataCache.columnVisualShowHide(colId, true);
- } // showColVisual
-
- public void sortColVisual(String colId) {
- visualManager.setSortByColumn(colId);
- resetCache(true);
-
- pageDataCache = null;
- cachedPageNo = -1;
- } // sortColVisual
-
- /** *********************************************************************************** */
-
- public String generateDistinctValuesSQL(DataColumnType dct, String userId, HttpServletRequest request) throws RaptorException {
- return super.generateDistinctValuesSQL(reportParamValues, dct, userId, request);
- } // generateDistinctValuesSQL
-
- public String getDbInfo() {
- return this.cr.getDbInfo();
- }
-
- private String fixSQL(StringBuffer sql) {
- int pos = 0;
- int pos_f_format = 0;
- int pos_t_format = 0;
- int pos_alias = 0;
- String format = "";
- String alias = null;
- if(sql.indexOf("SELECT", 7)!= -1) {
- pos = sql.indexOf("SELECT", 7);
- if(sql.indexOf("TO_CHAR", pos)!= -1){
- pos = sql.indexOf("TO_CHAR", pos);
- if(sql.indexOf("999",pos)!= -1) {
- pos = sql.indexOf("999",pos);
- pos_f_format = sql.lastIndexOf(", '", pos);
- if(pos_f_format == -1 || (pos - pos_f_format > 10)) {
- pos_f_format = sql.lastIndexOf(",'", pos);
- pos_f_format -= 1;
- }
- pos = pos_f_format;
- if(sql.indexOf("')", pos)!= -1) {
- pos_t_format = sql.indexOf("')", pos);
- //debugLogger.debug("pos_t - " + pos_t_format + " " + pos);
- if(pos_t_format == -1 || (pos_t_format - pos > 20)) {
- pos_t_format = sql.indexOf("' )", pos);
- pos_t_format += 3;
- }
- else if (pos_t_format != -1)
- pos_t_format += 2;
- format = sql.substring(pos_f_format+3, pos_t_format);
- //alias = sql.substring(pos_t_format+3, pos_t_format+6);
- pos_alias = sql.indexOf(" ", pos_t_format);
- alias = sql.substring(pos_alias+1, pos_alias+4);
- }
- }
- }
-
- if(sql.indexOf(alias)!=-1) {
- pos = sql.indexOf(alias);
- //debugLogger.debug(pos + " " + alias.length()+1 + "\n" + sql);
- sql.delete(pos,pos+4);
- sql.insert(pos, "TO_NUMBER("+alias+", '"+format+"')),'"+ format + "')");
- pos = sql.lastIndexOf("SUM", pos);
- if(pos==-1)
- pos = sql.lastIndexOf("AVG", pos);
- else if (pos==-1)
- pos = sql.lastIndexOf("COUNT", pos);
- else if (pos == -1)
- pos = sql.lastIndexOf("STDDEV", pos);
- else if (pos == -1)
- pos = sql.lastIndexOf("VARIANCE", pos);
- sql.insert(pos, "TO_CHAR (");
- }
-
- }
-
- //debugLogger.debug("Alias|" + alias + "| Format " + format);
- //debugLogger.debug(sql.toString());
- return sql.toString();
- } // FixSQL
-
- public String parseReportSQL(String sql) throws RaptorException {
- StringBuffer parsedSQL = new StringBuffer();
-
- Vector updatedReportCols = new Vector();
-
- curSQLParsePos = 0;
- int lastParsePos = curSQLParsePos;
- String lastToken = null;
- logger.debug(EELFLoggerDelegate.debugLogger, ("Flat File parseReportSQL ******* SQL " + sql));
- sql = sql.replaceAll("([\\s]*\\() (?!FROM)", "(");
- sql = sql.replaceAll("[\\s]*\\)", ")");
- //sql = sql.replaceAll("[dD][eE][cC][oO][dD][eE] ", "decode");
- //sql = sql.replaceAll("[\\s]*\\(", "(");
- //sql = replaceNewLine(sql, "decode ", "decode");
- //sql = replaceNewLine(sql, "DECODE ", "decode");
- //sql = replaceNewLine(sql, "Decode ", "decode");
-
- 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) {
- //System.out.println("LastToken " + lastToken + " NextToken " + nextToken);
-
-
- 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 {
- //System.out.println("Next Token " + nextToken);
- 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 {
- //System.out.println("Next Token " + nextToken + " is Here" + " Last Token " + lastToken);
- 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);
- //System.out.println(" ********** " + token + " " + lastToken);
- if (!token.toUpperCase().equals("FROM"))
- throw new org.openecomp.portalsdk.analytics.error.ValidationException(
- "|FROM keyword or a comma expected after [" + nextToken
- + "].");
- //System.out.println("Next Token " + 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
- nextToken = getNextCYMBALSQLParseToken(sql, true);
- Pattern re = null;
- Matcher matcher = null;
- String extracted = null;
- while (nextToken.length() > 0) {
- if (lastToken == null) lastToken = nextToken;
-
- if( lastToken.toUpperCase().equals("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()-2);
- StringTokenizer sToken = new StringTokenizer(extracted);
- while(sToken.hasMoreTokens()) {
- updatedReportCols.add(getParseSQLDataColumn("", sToken.nextToken(),
- 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.");
-
-
- return parsedSQL.toString();
-
- } // 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);
- else break;
- } // for
-
- return nextToken.toString();
- } // getNextSQLParseToken
-
- 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 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); // ???
-
- 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
- } // 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
-
- 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*/ public String parseReportSQLForDrillDownParams(String reportSQL, DataColumnType dataColumnRequest, HttpServletRequest request){
- String param = nvl(dataColumnRequest.getDrillDownParams());
- String sql = reportSQL;
- int pos = 0;
- while (param.indexOf('[', pos) >= 0) {
- int startIdx = param.indexOf('[',pos);
- int endIdx = param.indexOf(']',startIdx+1);
- pos = startIdx+1;
- StringBuffer sb = new StringBuffer();
- if (startIdx > 0)
- sb.append(param.substring(0, startIdx));
- else break;
-
- if (param.charAt(startIdx + 1) == '#') {
- // Parameter is a form field value
- String fieldId = param.substring(startIdx + 2, endIdx);
- String fieldValue = request.getParameter(fieldId);
- sql = Utils.replaceInString(sql, "[" + fieldId.toUpperCase()+"]", fieldValue );
- }
- }
- return sql;
- }
-
-public List getMapMarkers(ReportData rd, org.openecomp.portalsdk.analytics.xmlobj.ReportMap xmlmap){
-
- ArrayList markers = new ArrayList();
- int rNum = 0;
- HashMap colHash = new HashMap();
-
- for(rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext(); rNum++) {
- DataRow dr = rd.reportDataRows.getNext();
- for(dr.resetNext(); dr.hasNext(); ) {
- DataValue dv = dr.getNext();
- colHash.put(dv.getColId(), dv.getDisplayValueLinkHtml());
- }
-
- for (int i = 0; i < xmlmap.getMarkers().size(); i ++){
- Marker marker = new Marker("", "", "");
- org.openecomp.portalsdk.analytics.xmlobj.Marker m = (org.openecomp.portalsdk.analytics.xmlobj.Marker) xmlmap.getMarkers().get(i);
- String address = (String) colHash.get(m.getAddressColumn());
- String data = (String) colHash.get(m.getDataColumn());
- marker.setAddress(address);
- if (xmlmap.getAddAddressInDataYN() != null && xmlmap.getAddAddressInDataYN().equals("Y")){
- marker.setData(address + "<br/>" + data);
- }
- else{
- marker.setData(data);
- }
- marker.setColor(m.getMarkerColor());
- markers.add(marker);
- System.out.println("%%%%%%%%%%%% marker is : " + address + data);
- }
-
- }
-
- return markers;
- }
-
-
-
- public ReportParamValues getReportParamValues() {
- return reportParamValues;
- }
-
- public String getFormFieldFilled(String title) {
- if( getFormFieldList()!=null && reportParamValues!=null && nvl(title).length()>0) {
- 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)));
- title = Utils.replaceInString(title, fieldDisplay, nvl(
- paramValue, ""));
- }
- }
- }
- return title;
- }
-
- public synchronized Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- // this shouldn't happen, since we are Cloneable
- throw new InternalError("Cloning throws error.");
- }
- }
-
- public VisualManager getVisualManager() {
- return visualManager;
- }
-
- public String getReportSQLWithRowNum(String _orderBy, boolean asc) {
- String sql = getWholeSQL();
- int closeBracketPos = 0;
- // Added reportSQLOnlyFirstPart which has Column information with Rownum
- return nvl(getReportSQLOnlyFirstPart()) + " " + sql + ") x ";
-
- }
-
- public int getDisplayMode() {
- return DISPLAY_MODE;
- }
-
- public void setDisplayMode(int mode) {
- DISPLAY_MODE = mode;
- }
-
- public int getDateOption() {
- return DATE_OPTION;
- }
-
- public void setDateOption(int dateOption) {
- DATE_OPTION = dateOption;
- }
-
- public boolean isDisplayColTotals() {
- return displayColTotals;
- }
-
- public void setDisplayColTotals(boolean displayColTotals) {
- this.displayColTotals = displayColTotals;
- }
-
- public boolean isDisplayRowTotals() {
- return displayRowTotals;
- }
-
- public void setDisplayRowTotals(boolean displayRowTotals) {
- this.displayRowTotals = displayRowTotals;
- }
-
-
- private boolean 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
-
- return visibleColExist;
- } // canPersistLinearReport
-
- public void persistLinearReport(HttpServletRequest request)
- throws RaptorException {
- if (!canPersistLinearReport())
- return;
-
- Connection connection = null;
- try {
- String userID = AppUtils.getUserID(request);
- String reportXML = marshal();
- logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report " + reportID
- + " XML marshalled succesfully"));
-
- // Update report
- verifySQLBasedReportAccess(request);
- reportSecurity.reportUpdate(request);
- connection = DbUtils.startTransaction();
- ReportLoader.updateCustomReportRec(connection, this, reportXML);
- ReportLoader.createReportLogEntry(connection, reportID, userID,
- AppConstants.RLA_UPDATE, "", "");
- logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] DB update report "
- + reportID + " succesfull"));
- DbUtils.commitTransaction(connection);
- } catch (RaptorException e) {
- e.printStackTrace();
- DbUtils.rollbackTransaction(connection);
- throw e;
- } finally {
- DbUtils.clearConnection(connection);
- }
- } // persistLinearReport
-
- public void persistDashboardReport(HttpServletRequest request)
- throws RaptorException {
-
- Connection connection = null;
- try {
- String userID = AppUtils.getUserID(request);
- String reportXML = marshal();
- logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] Report " + reportID
- + " XML marshalled succesfully"));
-
- // Update report
- verifySQLBasedReportAccess(request);
- reportSecurity.reportUpdate(request);
- connection = DbUtils.startTransaction();
- ReportLoader.updateCustomReportRec(connection, this, reportXML);
- ReportLoader.createReportLogEntry(connection, reportID, userID,
- AppConstants.RLA_UPDATE, "", "");
- logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] DB update report "
- + reportID + " succesfull"));
- DbUtils.commitTransaction(connection);
- } catch (RaptorException e) {
- e.printStackTrace();
- DbUtils.rollbackTransaction(connection);
- throw e;
- } finally {
- DbUtils.clearConnection(connection);
- }
- } // persistDashboardReport
- public String getTotalSql() {
- return totalSql;
- }
-
- public void setTotalSql(String totalSql) {
- this.totalSql = totalSql;
- }
-
- public void setTriggerFormFieldCheck( ReportFormFields FormFieldList, FormField selectedFormField) {
-
- for (Iterator iter = getReportFormFields().iterator(); iter.hasNext();) {
- FormField ff = (FormField) iter.next();
- if(!ff.getFieldName().equals(selectedFormField.getFieldName())) {
- if(nvl(ff.getBaseSQL()).length()>0 && ff.getBaseSQL().indexOf("["+selectedFormField.getFieldDisplayName() +"]")!= -1) {
- selectedFormField.setTriggerOtherFormFields(true);
- }
-
- }
- }
-
- }
-
- public void setTriggerThisFormFieldCheck( ReportFormFields FormFieldList, FormField selectedFormField) {
-
- String sql = nvl(selectedFormField.getBaseSQL()).length()>0 ? selectedFormField.getBaseSQL():"";
- for (Iterator iter = getReportFormFields().iterator(); iter.hasNext();) {
- FormField ff = (FormField) iter.next();
- if(!ff.getFieldName().equals(selectedFormField.getFieldName())) {
- if(sql.indexOf("["+ff.getFieldDisplayName() +"]")!= -1) {
- selectedFormField.setTriggerThisFormfield(true);
- break;
- }
-
- }
- }
-
- }
-
- private boolean isAllowEdit(HttpServletRequest request) {
- boolean allowEdit = false;
- String userId = AppUtils.getUserID(request);
- try {
- if( AppUtils.isAdminUser(request) || AppUtils.isSuperUser(request) ) {
- allowEdit = true;
- } else {
- if(getOwnerID().equals(userId)) allowEdit = true;
- else allowEdit = false;
- }
- } catch (RaptorException ex) {
- allowEdit = false;
- }
- return allowEdit;
- }
- public ReportJSONRuntime createReportJSONRuntime(HttpServletRequest request, ReportData rd) {
- String userId = AppUtils.getUserID(request);
- ObjectMapper mapper = new ObjectMapper();
- ReportJSONRuntime reportJSONRuntime = new ReportJSONRuntime();
- reportJSONRuntime.setReportTitle(getReportTitle());
- //reportJSONRuntime.setReportSubTitle(getReportSubTitle());
- reportJSONRuntime.setReportID(getReportID());
- reportJSONRuntime.setReportDescr(getReportDescr());
- reportJSONRuntime.setReportName(getReportName());
- reportJSONRuntime.setReportSubTitle(getReportSubTitle());
- reportJSONRuntime.setAllowSchedule(isAllowSchedule());
- reportJSONRuntime.setAllowEdit(isAllowEdit(request));
- reportJSONRuntime.setColIdxTobeFreezed(getFrozenColumnId());
- reportJSONRuntime.setNumFormCols(getNumFormColsAsInt());
- //back button url
- reportJSONRuntime.setBackBtnURL("");
- String chartType = getChartType();
- boolean displayChart = (nvl(chartType).length()>0)&&getDisplayChart();
- boolean displayChartWizard = getDisplayChart();
- reportJSONRuntime.setChartAvailable(displayChart);
- reportJSONRuntime.setChartWizardAvailable(displayChartWizard);
- reportJSONRuntime.setDisplayData(!isDisplayOptionHideData());
- reportJSONRuntime.setDisplayForm(!isDisplayOptionHideForm());
- reportJSONRuntime.setHideFormFieldsAfterRun(isHideFormFieldAfterRun());
- reportJSONRuntime.setDisplayExcel(!isDisplayOptionHideExcelIcons());
- reportJSONRuntime.setDisplayPDF(!isDisplayOptionHidePDFIcons());
- ArrayList<IdNameValue> formFieldValues = new ArrayList<IdNameValue>();
- ArrayList<FormFieldJSON> formFieldJSONList = new ArrayList<FormFieldJSON>();
- if(getReportFormFields()!=null) {
- formFieldJSONList = new ArrayList<FormFieldJSON>(getReportFormFields().size());
- for (Iterator iter = getReportFormFields().iterator(); iter.hasNext();) {
- formFieldValues = new ArrayList<IdNameValue>();
- FormField ff = (FormField) iter.next();
- ff.setDbInfo(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.setVisible(ff.isVisible());
- //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();
- setTriggerFormFieldCheck( getReportFormFields(), ff);
- ffJSON.setTriggerOtherFormFields(ff.isTriggerOtherFormFields());
- SQL = parseAndFillReq_Session_UserValues(request, SQL, userId);
- SQL = parseAndFillWithCurrentValues(request, SQL, ff);
- String defaultSQL = lu.getDefaultSQL();
- defaultSQL = parseAndFillReq_Session_UserValues(request, defaultSQL, userId);
- defaultSQL = parseAndFillWithCurrentValues(request, defaultSQL, 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);
- } else if (AppUtils.nvl(ff.getDefaultValue()).length()>0) {
- if(ff.getDefaultValue().equals(value.getId())) {
- 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 {
- setTriggerFormFieldCheck( getReportFormFields(), ff);
- ffJSON.setTriggerOtherFormFields(ff.isTriggerOtherFormFields());
- 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);
- } else if (AppUtils.nvl(ff.getDefaultValue()).length()>0) {
- IdNameValue value = new IdNameValue(ff.getDefaultValue(), ff.getDefaultValue(), true, false);
- formFieldValues.add(value);
- }
- }
- if(!ff.hasPredefinedList) {
- if(oldSQL != null && !oldSQL.equals("")) {
- ((IdNameSql)lookup).setSQL(oldSQL);
- }
- }
-
-
-
- ffJSON.setFormFieldValues(formFieldValues);
- formFieldJSONList.add(ffJSON);
- } // for
- }
- reportJSONRuntime.setFormFieldList(formFieldJSONList);
- //reportJSONRuntime.setReportDataColumns(get);
- int count = 0;
- Map<String,Object> dvJSON = null;
- if(rd!=null) {
- count = 0;
- reportJSONRuntime.setTotalRows(getReportDataSize());
- ArrayList<ColumnHeader> colList = new ArrayList<ColumnHeader>();
- ArrayList<Map<String,Object>> reportDataRows = new ArrayList<Map<String,Object>>();
- for(rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext(); ) {
- count++;
- ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
- for(chr.resetNext(); chr.hasNext(); ) {
- colList.add(chr.getNext());
- }
- }
- if(getReportDataSize() > 0) {
- count = 0;
- for(rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext(); count++) {
- dvJSON = new HashMap<String,Object>();
- DataRow dr = rd.reportDataRows.getNext();
- for(dr.resetNext(); dr.hasNext(); ) {
- DataValue dv = dr.getNext();
- try {
- dvJSON.put(dv.getColId(), dv);
- } catch (Exception ex) {
- ex.printStackTrace();
-
- }
- }
- reportDataRows.add(dvJSON);
- }
- }
- reportJSONRuntime.setReportDataColumns(colList);
- reportJSONRuntime.setReportDataRows(reportDataRows);
- //reportJSONRuntime.setSqlWhole(getWholeSQL());
- reportJSONRuntime.setPageSize(getPageSize());
-
- }
-
- if(getReportDataSize() <= 0) {
- reportJSONRuntime.setMessage(getEmptyMessage());
- }
- reportJSONRuntime.setSqlWhole(getWholeSQL());
- return reportJSONRuntime;
-
- }
-
- public ReportJSONRuntime createFormFieldJSONRuntime(HttpServletRequest request) {
- String userId = AppUtils.getUserID(request);
- ObjectMapper mapper = new ObjectMapper();
- ReportJSONRuntime reportJSONRuntime = new ReportJSONRuntime();
- reportJSONRuntime.setReportTitle(getReportTitle());
- reportJSONRuntime.setReportID(getReportID());
- reportJSONRuntime.setReportName(getReportName());
- reportJSONRuntime.setReportSubTitle(getReportSubTitle());
- reportJSONRuntime.setNumFormCols(getNumFormColsAsInt());
- ArrayList<IdNameValue> formFieldValues = new ArrayList<IdNameValue>();
- ArrayList<FormFieldJSON> formFieldJSONList = new ArrayList<FormFieldJSON>();
- if(reportFormFields!=null) {
- formFieldJSONList = new ArrayList<FormFieldJSON>(reportFormFields.size());
- for (Iterator iter = reportFormFields.iterator(); iter.hasNext();) {
- formFieldValues = new ArrayList<IdNameValue>();
- FormField ff = (FormField) iter.next();
- 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.setFormFieldValues(formFieldValues);
- ffJSON.setVisible(ff.isVisible());
- formFieldJSONList.add(ffJSON);
- }
- for (Iterator iter = reportFormFields.iterator(); iter.hasNext();) {
- formFieldValues = new ArrayList<IdNameValue>();
- FormField ff = (FormField) iter.next();
- ff.setDbInfo(getDbInfo());
- for (Iterator iter1 = formFieldJSONList.iterator(); iter1.hasNext();) {
- FormFieldJSON ffJSON = (FormFieldJSON) iter1.next();
- if(ffJSON.getFieldId().equals(ff.getFieldName())) {
- 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();
- setTriggerFormFieldCheck( getReportFormFields(), ff);
- ffJSON.setTriggerOtherFormFields(ff.isTriggerOtherFormFields());
- setTriggerThisFormFieldCheck(getReportFormFields(), ff);
- SQL = parseAndFillReq_Session_UserValues(request, SQL, userId);
- SQL = parseAndFillOtherFormfieldValues(request, SQL, userId, formFieldJSONList);
- //SQL = parseAndFillWithCurrentValues(formGrid,SQL, ff);
- String defaultSQL = lu.getDefaultSQL();
- defaultSQL = parseAndFillReq_Session_UserValues(request, defaultSQL, userId);
- //defaultSQL = parseAndFillWithCurrentValues(formGrid,defaultSQL, 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.getParameter(ff.getFieldName());
- ArrayList<String> requestValueList = new ArrayList<String>();
- requestValueList.add(requestValue);
-
- /*if(ff.isTriggerThisFormfield()) {
- refreshFormFieldsWithLatestValue(request, userId, ff, formFieldJSONList);
- }*/
-
-
- for (lookup.resetNext(); lookup.hasNext();) {
- IdNameValue value = lookup.getNext();
- readOnly = value.isReadOnly();
- if(nvl(requestValue).length()>0) {
- if(value.getId().equals(requestValue))
- value.setDefaultValue(true);
- }
- formFieldValues.add(value);
- //break;
- }
-
- } else {
- setTriggerFormFieldCheck( getReportFormFields(), ff);
- ffJSON.setTriggerOtherFormFields(ff.isTriggerOtherFormFields());
- 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);
- } else if (AppUtils.nvl(ff.getDefaultValue()).length()>0) {
- IdNameValue value = new IdNameValue(ff.getDefaultValue(), ff.getDefaultValue(), true, false);
- formFieldValues.add(value);
- }
- }
- if(!ff.hasPredefinedList) {
- if(oldSQL != null && !oldSQL.equals("")) {
- ((IdNameSql)lookup).setSQL(oldSQL);
- }
- }
-
-
- //if(!ff.isTriggerThisFormfield()) {
- ffJSON.setFormFieldValues(formFieldValues);
- //}
-
- break;
-
- } //if
- } //for
- }//for
- }//if
-
- reportJSONRuntime.setFormFieldList(formFieldJSONList);
- //reportJSONRuntime.setReportDataColumns(get);
-
- return reportJSONRuntime;
-
- }
-
-
- private String parseAndFillOtherFormfieldValues(HttpServletRequest request, String SQL, String userId, ArrayList<FormFieldJSON> formFieldJSONList) {
- ArrayList<IdNameValue> formFieldValues = new ArrayList<IdNameValue>();
- String selectedValue = "";
- String displayName = "";
- for (Iterator iter1 = formFieldJSONList.iterator(); iter1.hasNext();) {
- FormFieldJSON ffJSON = (FormFieldJSON) iter1.next();
- displayName = ffJSON.getFieldDisplayName();
- ArrayList<IdNameValue> formfieldvalues = ffJSON.getFormFieldValues();
- for (int i = 0; i< formfieldvalues.size(); i++) {
- IdNameValue formfieldItem = formfieldvalues.get(i);
- if(formfieldItem.isDefaultValue()) {
- selectedValue = formfieldItem.getId();
- }
- }
- SQL = Utils.replaceInString(SQL, "["+displayName+"]", selectedValue);
- }
- return SQL;
-
- }
-
- private void refreshFormFieldsWithLatestValue(HttpServletRequest request, String userId, FormField ff_src, ArrayList<FormFieldJSON> formFieldJSONList) {
- ArrayList<IdNameValue> formFieldValues = new ArrayList<IdNameValue>();
- List<String> requestValueList = null;
- IdNameList lookup = null;
- lookup = ff_src.getLookupList();
- IdNameSql lu = (IdNameSql) lookup;
- String SQL = "" ;
- String oldSQL = "";
- String oldDefaultSQL = "";
- String defaultSQL = "";
- IdNameList lookupList = null;
- if(lu != null) {
- SQL = lu.getSql();
- oldSQL = lu.getSql();
- oldDefaultSQL = lu.getDefaultSQL();
- defaultSQL = lu.getDefaultSQL();
- }
- boolean readOnly = false;
- for (Iterator iter1 = formFieldJSONList.iterator(); iter1.hasNext();) {
- FormFieldJSON ffJSON = (FormFieldJSON) iter1.next();
- if((ffJSON.getFieldId().equals(ff_src.getFieldName())) && ffJSON.isVisible()) {
- for (Iterator iter = reportFormFields.iterator(); iter.hasNext();) {
- formFieldValues = new ArrayList<IdNameValue>();
- FormField ff = (FormField) iter.next();
- if(!ff.getFieldName().equals(ff_src.getFieldName())) {
- //IdNameList lookup = null;
- //lookup = ff.getLookupList();
- String selectedValue = "";
-
-
-
- String [] requestParam = request.getParameterValues(ff.getFieldName());
- if(requestParam != null) {
- requestValueList = Arrays.asList(request.getParameterValues(ff.getFieldName()));
-
- } else {
- requestValueList = new ArrayList<String>();
- }
-
-
- if(nvl(ff_src.getBaseSQL()).length()>0 && ff_src.getBaseSQL().indexOf("["+ff.getFieldDisplayName() +"]")!= -1) {
- if(lookup!=null) {
- try {
- if(!ff_src.hasPredefinedList) {
- String formatSelected = null;
- if(ff_src.getFieldType().equals(FormField.FFT_LIST_MULTI) || ff_src.getFieldType().equals(FormField.FFT_CHECK_BOX)) {
- formatSelected = formatSelectedItems(requestValueList, ff_src.getFieldType());
- } else
- formatSelected = requestValueList.size()>0?requestValueList.get(0):"";
- SQL = Utils.replaceInString(SQL, "["+ff_src.getFieldDisplayName()+"]", formatSelected);
- defaultSQL = Utils.replaceInString(defaultSQL, "["+ff_src.getFieldDisplayName()+"]", formatSelected);
- defaultSQL = parseAndFillWithCurrentValues(request, defaultSQL, ff_src);
- defaultSQL = parseAndFillReq_Session_UserValues(request, defaultSQL, userId);
- SQL = parseAndFillReq_Session_UserValues(request, SQL, userId);
- SQL = parseAndFillWithCurrentValues(request, SQL, ff_src);
-
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- }
-
- }
-
- }
- }
- }
-
- if(nvl(ff_src.getBaseSQL()).length()>0) {
- lookup = new IdNameSql(-1,SQL,defaultSQL);
- lookupList = lookup;
- try {
- lookup.loadUserData(0, "", ff_src.getDbInfo(), ff_src.getUserId());
- } catch (Exception e ){
- e.printStackTrace(); //throw new RaptorRuntimeException(e);
- }
- if(!ff_src.hasPredefinedList) {
- lookup.trimToSize();
- for (lookup.resetNext(); lookup.hasNext();) {
- IdNameValue value = lookup.getNext();
- readOnly = value.isReadOnly();
- formFieldValues.add(value);
- }
- }
- ffJSON.setFormFieldValues(formFieldValues);
- }
- if(!ff_src.hasPredefinedList) {
- if(oldSQL != null && !oldSQL.equals("")) {
- ((IdNameSql)lookup).setSQL(oldSQL);
- }
- if(oldDefaultSQL != null && !oldDefaultSQL.equals("")) {
- ((IdNameSql)lookup).setDefaultSQL(oldDefaultSQL);
- }
- }
-
- }
- }
-
- }
-
-
- private void triggerOtherFormFieldsWithThisValue(HttpServletRequest request, String userId, FormField ff_src, ArrayList<String> requestValueList, ArrayList<FormFieldJSON> formFieldJSONList) {
- ArrayList<IdNameValue> formFieldValues = new ArrayList<IdNameValue>();
- //ArrayList<FormFieldJSON> formFieldJSONList = new ArrayList<FormFieldJSON>();
- for (Iterator iter = reportFormFields.iterator(); iter.hasNext();) {
- formFieldValues = new ArrayList<IdNameValue>();
- FormField ff = (FormField) iter.next();
- if(!ff_src.getFieldName().equals(ff.getFieldName())) {
- for (Iterator iter1 = formFieldJSONList.iterator(); iter1.hasNext();) {
- FormFieldJSON ffJSON = (FormFieldJSON) iter1.next();
- if(ffJSON.getFieldId().equals(ff.getFieldName()) && ffJSON.isVisible()) {
- if(nvl(ff.getBaseSQL()).length()>0 && ff.getBaseSQL().indexOf("["+ff_src.getFieldDisplayName() +"]")!= -1) {
- IdNameList lookup = null;
- lookup = ff.getLookupList();
- String selectedValue = "";
- String oldSQL = "";
- String oldDefaultSQL = "";
- IdNameList lookupList = null;
- boolean readOnly = false;
- if(lookup!=null) {
- try {
- if(!ff.hasPredefinedList) {
- IdNameSql lu = (IdNameSql) lookup;
- String SQL = lu.getSql();
- oldSQL = lu.getSql();
- oldDefaultSQL = lu.getDefaultSQL();
- String defaultSQL = lu.getDefaultSQL();
- String formatSelected = null;
- if(ff_src.getFieldType().equals(FormField.FFT_LIST_MULTI) || ff_src.getFieldType().equals(FormField.FFT_CHECK_BOX)) {
- formatSelected = formatSelectedItems(requestValueList, ff.getFieldType());
- }
- else
- formatSelected = requestValueList.size()>0?requestValueList.get(0):"";
- SQL = Utils.replaceInString(SQL, "["+ff_src.getFieldDisplayName()+"]", formatSelected);
- defaultSQL = Utils.replaceInString(defaultSQL, "["+ff_src.getFieldDisplayName()+"]", formatSelected);
- defaultSQL = parseAndFillWithCurrentValues(request, defaultSQL, ff_src);
- defaultSQL = parseAndFillReq_Session_UserValues(request, defaultSQL, userId);
- SQL = parseAndFillReq_Session_UserValues(request, SQL, userId);
- SQL = parseAndFillWithCurrentValues(request, SQL, ff_src);
- 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();
-
-
-
- for (lookup.resetNext(); lookup.hasNext();) {
- IdNameValue value = lookup.getNext();
- readOnly = value.isReadOnly();
-// if(nvl(requestValue).length()>0) {
-// if(value.getId().equals(requestValue))
-// value.setDefaultValue(true);
-// }
- formFieldValues.add(value);
- //break;
- }
-
- ffJSON.setFormFieldValues(formFieldValues);
-
- if(!ff.hasPredefinedList) {
- if(oldSQL != null && !oldSQL.equals("")) {
- ((IdNameSql)lookup).setSQL(oldSQL);
- }
- if(oldDefaultSQL != null && !oldDefaultSQL.equals("")) {
- ((IdNameSql)lookup).setDefaultSQL(oldDefaultSQL);
- }
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
-
- } //ff baseSQL
- }
- }
- }
- }
-
- }
-
- public String formatSelectedItems(List selectedItems, String type) {
- StringBuffer value = new StringBuffer("");
- int count = 0;
- boolean multiple = false;
- if(type.equals("LIST_MULTI_SELECT"))
- multiple = true;
- //multiple = (selectedItems.size()>1);
- for(Iterator iter = selectedItems.iterator(); iter.hasNext(); ) {
- count++;
- String entry = (String) iter.next();
- if(count == 1 && multiple)
- value.append("(");
- //if(type.equals(FormField.FFT_CHECK_BOX))
- /*if(type.equals(FormField.FFT_CHECK_BOX))
- value.append("'"+Utils.oracleSafe(entry)+"'");
- else*/ if (type.equals(FormField.FFT_LIST_MULTI))
- value.append("'"+Utils.oracleSafe(entry)+"'");
- else if(type.equals(FormField.FFT_LIST_BOX))
- value.append(Utils.oracleSafe(entry));
- else
- value.append("'"+Utils.oracleSafe(entry)+"'");
- if((count < selectedItems.size()) && multiple)
- value.append(",");
- if((count == selectedItems.size()) && multiple)
- value.append(")");
- }
-
- if(value.length()>0)
- return value.toString();
- else
- return null;
- }
-
-public String parseAndFillWithCurrentValues(HttpServletRequest request, String sql, FormField source_Formfield) {
-
- if (getFormFieldList() != null) {
- for (Iterator iter = getFormFieldList().getFormField().iterator(); iter.hasNext();) {
- FormFieldType fft = (FormFieldType) iter.next();
- String fieldId = fft.getFieldId();
- String fieldDisplay = getFormFieldDisplayName(fft);
- String formfield_value = "";
- List<String> selectedItems = new ArrayList<String>();
- //Added so that Combo Box in old RAPTOR definition is translated to List box
- if(fft.getFieldType().equals(FormField.FFT_COMBO_BOX)) {
- fft.setFieldType(FormField.FFT_LIST_BOX);
- }
- if(!fft.getFieldType().equals(FormField.FFT_BLANK)) {
- //if(source_Formfield==null || (source_Formfield!=null && !fft.getFieldId().equals(source_Formfield.getFieldName()))) {
- // Add oracle safe
- // Add param base sql
- if(fft.getFieldType().equals(FormField.FFT_LIST_MULTI) || fft.getFieldType().equals(FormField.FFT_CHECK_BOX)) {
- if(request.getParameterValues(fieldId)!=null && request.getParameterValues(fieldId).length > 0) {
-
- selectedItems = Arrays.asList(request.getParameterValues(fieldId));
- formfield_value = formatSelectedItems(selectedItems, fft.getFieldType());
- } else {
- formfield_value = "";
- }
- } else if(fft.getFieldType().equals(FormField.FFT_RADIO_BTN)) {
- if(request.getParameter(fieldId)!=null) {
- formfield_value = request.getParameter(fieldId);
- } else {
- formfield_value = "";
- }
- } else if (fft.getFieldType().equals(FormField.FFT_HIDDEN)) {
- if(request.getParameter(fieldId)!=null) {
- formfield_value = request.getParameter(fieldId);
- } else {
- formfield_value = "";
- }
- } else if((fft.getFieldType().equals(FormField.FFT_TEXT) || fft.getFieldType().equals(FormField.FFT_TEXTAREA)) &&
- (!fft.getValidationType().equals(FormField.VT_DATE) && !fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)&&
- !fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) && !fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) ) {
- if(request.getParameter(fieldId)!=null) {
- formfield_value = request.getParameter(fieldId);
- } else {
- formfield_value = "";
- }
- } else if (fft.getValidationType().equals(FormField.VT_DATE) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)||
- fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
- /*if(formGrid.hasFellow(fieldId, true)) {
- Datebox tb = (Datebox) formGrid.getFellowIfAny(fieldId, true);
- try {
- formfield_value = tb.getText();
- } catch (WrongValueException ex) {
- formfield_value = "";
- }
- if(AppUtils.nvl(formfield_value).length() > 0) {
- if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) {
- if(formGrid.hasFellow(fieldId+"_Hr", true)) {
- Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true);
- formfield_value = formfield_value + " " + hiddenLbHr.getValue();
- }
- } else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) {
- if(formGrid.hasFellow(fieldId+"_Min", true)) {
- Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true);
- //formfield_value = formfield_value + " " + hiddenLbHr.getValue();
- Label hiddenLbMin = (Label) formGrid.getFellowIfAny(fieldId+"_Min", true);
- formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue();
-
- }
- } else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
- if(formGrid.hasFellow(fieldId+"_Sec", true)) {
- Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true);
- //formfield_value = formfield_value + " " + hiddenLbHr.getValue();
- Label hiddenLbMin = (Label) formGrid.getFellowIfAny(fieldId+"_Min", true);
- //formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue();
- Label hiddenLbSec = (Label) formGrid.getFellowIfAny(fieldId+"_Sec", true);
- formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue()+ ":" +hiddenLbSec.getValue();
-
- }
- }
- }
-
- } else {
- formfield_value = "";
- }*/
- } else if ((fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)||
- fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC))) {
- /*if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)||
- fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
- if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) {
- if(formGrid.hasFellow(fieldId+"_Hr", true)) {
- Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true);
- formfield_value = formfield_value + " " + hiddenLbHr.getValue();
- }
- } else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) {
- if(formGrid.hasFellow(fieldId+"_Min", true)) {
- Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true);
- //formfield_value = formfield_value + " " + hiddenLbHr.getValue();
- Label hiddenLbMin = (Label) formGrid.getFellowIfAny(fieldId+"_Min", true);
- formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue();
-
- }
- } else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
- if(formGrid.hasFellow(fieldId+"_Sec", true)) {
- Label hiddenLbHr = (Label) formGrid.getFellowIfAny(fieldId+"_Hr", true);
- //formfield_value = formfield_value + " " + hiddenLbHr.getValue();
- Label hiddenLbMin = (Label) formGrid.getFellowIfAny(fieldId+"_Min", true);
- //formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue();
- Label hiddenLbSec = (Label) formGrid.getFellowIfAny(fieldId+"_Sec", true);
- formfield_value = formfield_value + " " + hiddenLbHr.getValue() + ":" +hiddenLbMin.getValue()+ ":" +hiddenLbSec.getValue();
-
- }
- }
-
- } */
- } else if (fft.getFieldType().equals(FormField.FFT_TEXT_W_POPUP)) {
- if(request.getParameter(fieldId)!=null) {
- formfield_value = request.getParameter(fieldId);
- } else {
- formfield_value = "";
- }
- } else if (fft.getFieldType().equals(FormField.FFT_LIST_BOX)) {
- if(request.getParameter(fieldId)!=null) {
- formfield_value = request.getParameter(fieldId);
- } else {
- formfield_value = "";
- }
- //}
- }
- if(nvl(formfield_value).length()>0) {
- sql = Utils.replaceInString(sql, fieldDisplay, formfield_value);
- } else {
- sql = Utils.replaceInString(sql, "'"+fieldDisplay+"'", "null");
- sql = Utils.replaceInString(sql, fieldDisplay, "null");
- //sql = Utils.replaceInString(sql, fieldDisplay, "''");
- }
- } // for
- }
- }
- return sql;
- }
- public String parseAndFillReq_Session_UserValues(HttpServletRequest request, String sql, String user_id) {
- HttpSession session = request.getSession();
-
- String[] reqParameters = Globals.getRequestParams().split(",");
- String[] sessionParameters = Globals.getSessionParams().split(",");
- String[] scheduleSessionParameters = Globals.getSessionParamsForScheduling().split(",");
-
-
- if(AppUtils.nvl(sql).length()>0) {
- for (int i = 0; i < reqParameters.length; i++) {
- if(!reqParameters[i].startsWith("ff") && (request.getParameter(reqParameters[i].toUpperCase())!=null && request.getParameter(reqParameters[i].toUpperCase()).length() > 0))
- sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
- else if (request.getParameter(reqParameters[i])!=null && request.getParameter(reqParameters[i]).length() > 0)
- sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
- }
-
- for (int i = 0; i < scheduleSessionParameters.length; i++) {
- //debugLogger.debug(" Session " + " scheduleSessionParameters[i] " + scheduleSessionParameters[i].toUpperCase() + " " + request.getParameter(scheduleSessionParameters[i]));
- if(request.getParameter(scheduleSessionParameters[i])!=null && request.getParameter(scheduleSessionParameters[i]).trim().length()>0 )
- sql = Utils.replaceInString(sql, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) );
- if(request.getAttribute(scheduleSessionParameters[i])!=null && ((String)request.getAttribute(scheduleSessionParameters[i])).trim().length()>0 )
- sql = Utils.replaceInString(sql, "[" + scheduleSessionParameters[i].toUpperCase()+"]", (String) request.getAttribute(scheduleSessionParameters[i]) );
-
- }
-
- for (int i = 0; i < sessionParameters.length; i++) {
- //if(!sessionParameters[i].startsWith("ff"))
- //fieldSQL = Utils.replaceInString(fieldSQL, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) );
- //else {
- if (session.getAttribute(sessionParameters[i])!=null && ((String)session.getAttribute(sessionParameters[i])).length() > 0) {
- //debugLogger.debug(" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i]));
- sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
- }
- // }
- }
- sql = Utils.replaceInString(sql, "[USERID]", user_id);
- sql = Utils.replaceInString(sql, "[USER_ID]", user_id);
- sql = Utils.replaceInString(sql, "[LOGGED_USERID]", user_id);
-
- }
- return sql;
- }
-
-} // ReportRuntime
+++ /dev/null
-/*-
- * ================================================================================
- * 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 TimeSeriesChartOptions {
- private String lineChartRenderer;
- private boolean multiSeries;
- private boolean nonTimeAxis;
- private boolean showXAxisLabel;
- private boolean addXAxisTicker;
-
- public String getLineChartRenderer() {
- return lineChartRenderer;
- }
- public void setLineChartRenderer(String lineChartRenderer) {
- this.lineChartRenderer = lineChartRenderer;
- }
- public boolean isMultiSeries() {
- return multiSeries;
- }
- public void setMultiSeries(boolean multiSeries) {
- this.multiSeries = multiSeries;
- }
- public boolean isNonTimeAxis() {
- return nonTimeAxis;
- }
- public void setNonTimeAxis(boolean nonTimeAxis) {
- this.nonTimeAxis = nonTimeAxis;
- }
- public boolean isShowXAxisLabel() {
- return showXAxisLabel;
- }
- public void setShowXAxisLabel(boolean showXAxisLabel) {
- this.showXAxisLabel = showXAxisLabel;
- }
- public boolean isAddXAxisTicker() {
- return addXAxisTicker;
- }
- public void setAddXAxisTicker(boolean addXAxisTicker) {
- this.addXAxisTicker = addXAxisTicker;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.*;
-
-import org.openecomp.portalsdk.analytics.*;
-import org.openecomp.portalsdk.analytics.system.*;
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class VisualManager extends RaptorObject {
- private HashMap hiddenCols = new HashMap();
-
- private String sortByColId = "";
-
- private String sortByAscDesc = AppConstants.SO_ASC;
-
- public VisualManager() {
- super();
- }
-
- public void hideColumn(String colId) {
- hiddenCols.put(colId, "Y");
- } // hideColumn
-
- public void showColumn(String colId) {
- hiddenCols.put(colId, "N");
- } // showColumn
-
- public boolean isColumnVisible(String colId) {
- return nvl((String) hiddenCols.get(colId), "N").equals("N");
- } // isColumnVisible
-
- public void setSortByColumn(String colId) {
- if (sortByColId.equals(colId))
- sortByAscDesc = sortByAscDesc.equals(AppConstants.SO_ASC) ? AppConstants.SO_DESC
- : AppConstants.SO_ASC;
- else {
- sortByColId = colId;
- sortByAscDesc = AppConstants.SO_ASC;
- }
- } // setSortByColumn
-
- public String getSortByColId() {
- return sortByColId;
- }
-
- public String getSortByAscDesc() {
- return sortByAscDesc;
- }
-
-} // VisualManager
+++ /dev/null
-/*-
- * ================================================================================
- * 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.search;
-
-import java.util.*;
-
-import org.openecomp.portalsdk.analytics.system.*;
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class ReportSearchResult extends SearchResult {
- private static final String HTML_FORM = "forma";
-
- public ReportSearchResult(int pageNo) {
- this(pageNo, Globals.getDefaultPageSize(), -1, -1);
- } // ReportSearchResult
-
- public ReportSearchResult(int pageNo, int writeAccessColIndex, int ownerIndicatorColIndex) {
- this(pageNo, Globals.getDefaultPageSize(), writeAccessColIndex, ownerIndicatorColIndex);
- } // ReportSearchResult
-
- public ReportSearchResult(int pageNo, int pageSize, int writeAccessColIndex,
- int ownerIndicatorColIndex) {
- super(pageNo, pageSize, writeAccessColIndex, ownerIndicatorColIndex);
-
- addColumn(new SearchResultColumn("no","No", "5%", "Center"));
- addColumn(new SearchResultColumn("rep_id","Report ID", "5%", "Center"));
- addColumn(new SearchResultColumn("rep_name","Report Name", "25%", "Left"));
- addColumn(new SearchResultColumn("descr","Description", "30%", "Left"));
- addColumn(new SearchResultColumn("owner","Report Owner", "10%", "Center"));
- addColumn(new SearchResultColumn("create_date","Create Date", "10%", "Center"));
- addColumn(new SearchResultColumn("copy"," Copy ", "5%", "Center",
- "document." + HTML_FORM + "." + AppConstants.RI_ACTION
- + ".value='report.copy';", "Copy report", HTML_FORM,
- "Are you sure you want to create a copy of this report?", AppUtils
- .getImgFolderURL()
- + "modify_icon.gif", "13", "12", true, false, false));
- /*addColumn(new SearchResultColumn(" Schedule ", "5%", "Center",
- "document." + HTML_FORM + "." + AppConstants.RI_ACTION
- + ".value='report.schedule_only';", "Schedule report", HTML_FORM,
- null, AppUtils
- .getImgFolderURL()
- + "calendar_icon.gif", "13", "12", true, false, false));
- */
-
- addColumn(new SearchResultColumn("edit"," Edit ", "5%", "Center",
- "document." + HTML_FORM + "." + AppConstants.RI_ACTION
- + ".value='report.edit';", "Edit report", HTML_FORM, null, AppUtils
- .getImgFolderURL()
- + "pen_paper.gif", "12", "12", false, true, false));
- addColumn(new SearchResultColumn("delete","Delete", "5%", "Center", "document." + HTML_FORM
- + "." + AppConstants.RI_ACTION + ".value='report.delete';", "Delete report",
- HTML_FORM, "Are you sure you want to delete this report?", AppUtils
- .getImgFolderURL()
- + "deleteicon.gif", "12", "12", false, false, true));
- addColumn(new SearchResultColumn("schedule","Schedule", "5%", "Center", "document." + HTML_FORM
- + "." + AppConstants.RI_ACTION + ".value='report.schedule.report.submit_wmenu';", "Schedule report",
- HTML_FORM, null, AppUtils
- .getImgFolderURL()
- + "calendar_icon.gif", "20", "20", false, false, false, true));
- addColumn(new SearchResultColumn("run"," Run ", "5%", "Center",
- "document." + HTML_FORM + "." + AppConstants.RI_ACTION
- + ".value='report.run';", "Run report", HTML_FORM, null, AppUtils
- .getImgFolderURL()
- + "test_run.gif", "12", "12"));
- } // ReportSearchResult
-
-} // ReportSearchResult
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.search;
-
-import java.util.*;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.system.*;
-import org.openecomp.portalsdk.analytics.util.*;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-class MetaReport {
- private boolean pagination = true;
- private int pageSize;
- private int totalSize;
- private int pageNo;
- public boolean isPagination() {
- return pagination;
- }
- public void setPagination(boolean pagination) {
- this.pagination = pagination;
- }
- public int getPageSize() {
- return pageSize;
- }
- public void setPageSize(int pageSize) {
- this.pageSize = pageSize;
- }
- public int getTotalSize() {
- return totalSize;
- }
- public void setTotalSize(int totalSize) {
- this.totalSize = totalSize;
- }
- public int getPageNo() {
- return pageNo;
- }
- public void setPageNo(int pageNo) {
- this.pageNo = pageNo;
- }
-
-
-}
-class SearchReport {
- private MetaReport metaReport;
- public MetaReport getMetaReport() {
- return metaReport;
- }
- public void setMetaReport(MetaReport metaReport) {
- this.metaReport = metaReport;
- }
- private ArrayList<ArrayList<SearchResultColumn>> columns = new ArrayList<ArrayList<SearchResultColumn>>();
- private ArrayList<ArrayList<SearchResultRow>> rows = new ArrayList<ArrayList<SearchResultRow>>();
- public ArrayList<ArrayList<SearchResultColumn>> getColumns() {
- return columns;
- }
- public void setColumns(ArrayList<ArrayList<SearchResultColumn>> columns) {
- this.columns = columns;
- }
- public ArrayList<ArrayList<SearchResultRow>> getRows() {
- return rows;
- }
- public void setRows(ArrayList<ArrayList<SearchResultRow>> rows) {
- this.rows = rows;
- }
-
-}
-
-public class ReportSearchResultJSON extends SearchResultJSON {
- private static final String HTML_FORM = "forma";
- private String JSONString= "";
- private SearchReport searchReport;
- //private ArrayList<ArrayList<SearchResultColumn>> columns = new ArrayList<ArrayList<SearchResultColumn>>();
- //private ArrayList<ArrayList<SearchResultRow>> rows = new ArrayList<ArrayList<SearchResultRow>>();
-
-
- public ReportSearchResultJSON(int pageNo) {
- this(pageNo, Globals.getDefaultPageSize(), -1, -1);
- } // ReportSearchResult
-
- public ReportSearchResultJSON(int pageNo, int writeAccessColIndex, int ownerIndicatorColIndex) {
- this(pageNo, Globals.getDefaultPageSize(), writeAccessColIndex, ownerIndicatorColIndex);
- } // ReportSearchResult
-
- public ReportSearchResultJSON(int pageNo, int pageSize, int writeAccessColIndex,
- int ownerIndicatorColIndex) {
-
- searchReport = new SearchReport();
- MetaReport metaReport = new MetaReport();
- //if(searchReport.getMetaReport()!=null)
- searchReport.setMetaReport(metaReport);
- metaReport.setPageNo(pageNo);
- metaReport.setPageSize(pageSize);
- metaReport.setPagination(true);
- addColumn(new SearchResultColumn("no", "No", "5%", "Center"));
- addColumn(new SearchResultColumn("rep_id", "Report ID", "5%", "Center"));
- addColumn(new SearchResultColumn("rep_name", "Report Name", "25%", "Left"));
- addColumn(new SearchResultColumn("descr", "Description", "30%", "Left"));
- addColumn(new SearchResultColumn("owner", "Report Owner", "10%", "Center"));
- addColumn(new SearchResultColumn("create_date", "Create Date", "10%", "Center"));
- addColumn(new SearchResultColumn("copy", "Copy", "5%", "Center",
- "document." + HTML_FORM + "." + AppConstants.RI_ACTION
- + ".value='report.copy';", "Copy report", HTML_FORM,
- "Are you sure you want to create a copy of this report?", AppUtils
- .getImgFolderURL()
- + "modify_icon.gif", "13", "12", true, false, false));
- /*addColumn(new SearchResultColumn(" Schedule ", "5%", "Center",
- "document." + HTML_FORM + "." + AppConstants.RI_ACTION
- + ".value='report.schedule_only';", "Schedule report", HTML_FORM,
- null, AppUtils
- .getImgFolderURL()
- + "calendar_icon.gif", "13", "12", true, false, false));
- */
-
- addColumn(new SearchResultColumn("edit", "Edit", "5%", "Center",
- "document." + HTML_FORM + "." + AppConstants.RI_ACTION
- + ".value='report.edit';", "Edit report", HTML_FORM, null, AppUtils
- .getImgFolderURL()
- + "pen_paper.gif", "12", "12", false, true, false));
- addColumn(new SearchResultColumn("delete", "Delete", "5%", "Center", "document." + HTML_FORM
- + "." + AppConstants.RI_ACTION + ".value='report.delete';", "Delete report",
- HTML_FORM, "Are you sure you want to delete this report?", AppUtils
- .getImgFolderURL()
- + "deleteicon.gif", "12", "12", false, false, true));
- addColumn(new SearchResultColumn("schedule", "Schedule", "5%", "Center", "document." + HTML_FORM
- + "." + AppConstants.RI_ACTION + ".value='report.schedule.report.submit_wmenu';", "Schedule report",
- HTML_FORM, null, AppUtils
- .getImgFolderURL()
- + "calendar_icon.gif", "20", "20", false, false, false, true));
- addColumn(new SearchResultColumn("run", "Run", "5%", "Center",
- "document." + HTML_FORM + "." + AppConstants.RI_ACTION
- + ".value='report.run';", "Run report", HTML_FORM, null, AppUtils
- .getImgFolderURL()
- + "test_run.gif", "12", "12"));
- searchReport.getColumns().add(searchResultColumns);
- } // ReportSearchResult
-
- public void parseData(DataSet ds, HttpServletRequest request, int pageNo, int pageSize, int writeAccessColIndex, int ownerIndicatorColIndex) throws RaptorException {
- // Presumes single ID field in the first column of the DataSet and row
- // number in the first SearchResultColumn
-
- pageNo = AppUtils.getRequestNvlValue(request, "r_page").length()>0?Integer.parseInt(AppUtils.getRequestNvlValue(request, "r_page")):0;
- String userID = AppUtils.getUserID(request);
- int dataSize = ds.getRowCount();
- //pageSize = 0;
-
- if(searchReport.getMetaReport()!=null) {
- searchReport.getMetaReport().setPageNo(pageNo);
- //searchReport.getMetaReport().setPageSize(pageSize);
- pageSize = searchReport.getMetaReport().getPageSize();
- searchReport.getMetaReport().setTotalSize(dataSize);
- }
- int startRow = (pageNo >= 0) ? (pageNo * pageSize) : 0;
- int endRow = (pageNo >= 0) ? Math.min(startRow + pageSize, ds.getRowCount()) : ds
- .getRowCount();
- for (int r = startRow; r < endRow; r++) {
- SearchResultRow row = new SearchResultRow();
- searchResultRows.add(row);
-
- String idValue = ds.getString(r, 0);
-
- boolean bCanEdit = true;
- if (writeAccessColIndex >= 0) {
- String isReadOnlyValue = nvl(ds.getString(r, writeAccessColIndex), "Y");
- bCanEdit = AppUtils.isSuperUser(request) || AppUtils.isAdminUser(request)
- || isReadOnlyValue.equals("N");
- }
-
- boolean bCanDelete = bCanEdit;
- if (Globals.getDeleteOnlyByOwner() && ownerIndicatorColIndex >= 0) {
- String isOwnedByUserRecord = nvl(ds.getString(r, ownerIndicatorColIndex), "N");
- bCanDelete = AppUtils.isSuperUser(request) || isOwnedByUserRecord.equals("Y");
- }
-
- boolean bCanSchedule = ds.getString(r, getNumColumns()-3).equals("Y");
-
- row.addColumnContent(new ColumnContent(getColumn(0).getColumnId(), new SearchResultField("" + (r + 1), idValue,
- getColumn(0), true)));
- boolean isAuthorized = true;
- for (int c = 1; c < getNumColumns(); c++) {
- SearchResultColumn column = getColumn(c);
- isAuthorized = true;
-
- if(column.isCopyLink())
- isAuthorized = Globals.getCanCopyOnReadOnly()? true:bCanEdit;
- else if (column.isDeleteLink())
- isAuthorized = bCanDelete;
- else if (column.isEditLink())
- isAuthorized = bCanEdit;
- else if (column.isScheduleLink())
- isAuthorized = bCanSchedule;
- row.addColumnContent(new ColumnContent(column.getColumnId(), new SearchResultField(
- (column.getLinkURL() == null) ? ds.getString(r, c) : column
- .getLinkTitle(), idValue, column, isAuthorized
- )));
- } // for
- } // for
- searchReport.getRows().add(searchResultRows);
- ObjectMapper mapper = new ObjectMapper();
- String jsonInString = "";
- try {
- jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(searchReport);
- } catch (Exception ex) {
- ex.printStackTrace();
-
- }
- System.out.println(jsonInString);
- this.JSONString = jsonInString;
- } // parseData
-
- private String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- private String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
- public String getJSONString() {
- return JSONString;
- }
-
- public void setJSONString(String jSONString) {
- JSONString = jSONString;
- }
-
-
-} // ReportSearchResult
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.search;
-
-import java.util.*;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.system.*;
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class SearchResult{
- private int pageNo = -1;
-
- private int pageSize = 50;
-
- private int dataSize = -1;
-
- private int writeAccessColIndex = -1;
-
- private int ownerIndicatorColIndex = -1;
-
- private String csvPageFileName = null;
-
-
-
- private String csvAllRowsFileName = null;
-
- private String excelAllRowsFileName = null;
-
- public ArrayList searchResultColumns = new ArrayList();
-
- public ArrayList searchResultRows = new ArrayList();
-
- public SearchResult(int pageNo) {
- this(pageNo, Globals.getDefaultPageSize());
- } // SearchResult
-
- public SearchResult(int pageNo, int pageSize) {
- this(pageNo, pageSize, -1, -1);
- } // SearchResult
-
- public SearchResult(int pageNo, int pageSize, int writeAccessColIndex,
- int ownerIndicatorColIndex) {
- super();
-
- this.pageNo = pageNo;
- this.pageSize = pageSize;
-
- this.writeAccessColIndex = writeAccessColIndex;
- this.ownerIndicatorColIndex = ownerIndicatorColIndex;
- } // SearchResult
-
- public int getPageNo() {
- return pageNo;
- }
-
- public int getPageSize() {
- return pageSize;
- }
-
- public int getDataSize() {
- return dataSize;
- }
-
- public String getCsvPageFileName() {
- return csvPageFileName;
- }
-
- public String getCsvAllRowsFileName() {
- return csvAllRowsFileName;
- }
-
- public String getExcelAllRowsFileName() {
- return excelAllRowsFileName;
- }
-
- private void setDataSize(int dataSize) {
- this.dataSize = dataSize;
- }
-
- public void setCsvPageFileName(String csvPageFileName) {
- this.csvPageFileName = csvPageFileName;
- }
-
-
-
- public void setCsvAllRowsFileName(String csvAllRowsFileName) {
- this.csvAllRowsFileName = csvAllRowsFileName;
- }
-
-
-
- public void addColumn(SearchResultColumn column) {
- searchResultColumns.add(column);
- } // addColumn
-
- public SearchResultColumn getColumn(int index) {
- return (SearchResultColumn) searchResultColumns.get(index);
- } // getColumn
-
- public int getNumColumns() {
- return searchResultColumns.size();
- } // getNumColumns
-
- public int getNumRows() {
- return searchResultRows.size();
- } // getNumRows
-
- public SearchResultRow getRow(int index) {
- return (SearchResultRow) searchResultRows.get(index);
- } // getRow
-
- public void parseData(DataSet ds, HttpServletRequest request) throws RaptorException {
- // Presumes single ID field in the first column of the DataSet and row
- // number in the first SearchResultColumn
- String userID = AppUtils.getUserID(request);
- setDataSize(ds.getRowCount());
-
- int startRow = (pageNo >= 0) ? (pageNo * pageSize) : 0;
- int endRow = (pageNo >= 0) ? Math.min(startRow + pageSize, ds.getRowCount()) : ds
- .getRowCount();
- for (int r = startRow; r < endRow; r++) {
- SearchResultRow row = new SearchResultRow();
- searchResultRows.add(row);
-
- String idValue = ds.getString(r, 0);
-
- boolean bCanEdit = true;
- if (writeAccessColIndex >= 0) {
- String isReadOnlyValue = nvl(ds.getString(r, writeAccessColIndex), "Y");
- bCanEdit = AppUtils.isSuperUser(request) || AppUtils.isAdminUser(request)
- || isReadOnlyValue.equals("N");
- }
-
- boolean bCanDelete = bCanEdit;
- if (Globals.getDeleteOnlyByOwner() && ownerIndicatorColIndex >= 0) {
- String isOwnedByUserRecord = nvl(ds.getString(r, ownerIndicatorColIndex), "N");
- bCanDelete = AppUtils.isSuperUser(request) || isOwnedByUserRecord.equals("Y");
- }
-
- boolean bCanSchedule = ds.getString(r, getNumColumns()-3).equals("Y");
-
- row.addSearchResultField(new SearchResultField("" + (r + 1), idValue,
- getColumn(0), true));
- boolean isAuthorized = true;
- for (int c = 1; c < getNumColumns(); c++) {
- SearchResultColumn column = getColumn(c);
- isAuthorized = true;
-
- if(column.isCopyLink())
- isAuthorized = Globals.getCanCopyOnReadOnly()? true:bCanEdit;
- else if (column.isDeleteLink())
- isAuthorized = bCanDelete;
- else if (column.isEditLink())
- isAuthorized = bCanEdit;
- else if (column.isScheduleLink())
- isAuthorized = bCanSchedule;
-
- row.addSearchResultField(new SearchResultField(
- (column.getLinkURL() == null) ? ds.getString(r, c) : column
- .getLinkTitle(), idValue, column, isAuthorized
- ));
- } // for
- } // for
- } // parseData
-
- public void truncateToPage(int pageNo) {
- if (this.pageNo >= 0 || pageNo < 0)
- return;
-
- this.pageNo = pageNo;
-
- int startRow = pageNo * pageSize;
- int endRow = Math.min(startRow + pageSize, dataSize);
-
- for (int r = getNumRows() - 1; r >= endRow; r--)
- searchResultRows.remove(r);
-
- for (int r = startRow - 1; r >= 0; r--)
- searchResultRows.remove(r);
- } // truncateToPage
-
- /** *********************************************************************** */
-
- private String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- private String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
-} // SearchResult
+++ /dev/null
-/*-
- * ================================================================================
- * 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.search;
-
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class SearchResultColumn extends org.openecomp.portalsdk.analytics.RaptorObject {
- private String columnId = "";
- private String columnTitle = "";
-
- private String columnWidth = "";
-
- private String alignment = "Left";
-
- private String linkURL = null; // if not null => display link instead of
- // text
-
- private String linkTitle = null; // if img => hint, otherwise link
- // display text
-
- private String linkForm = null; // if not null => displays input submit
- // instead of link
-
- private String linkConfirmMsg = null; // if not null => display conf. box
- // on link click
-
- private String linkImg = null; // if not null => link shows image, not text
-
- private String linkImgWidth = null; // optional
-
- private String linkImgHeight = null; // optional
-
- private boolean copyLink = false; // optional
-
- private boolean editLink = false; // optional
-
- private boolean deleteLink = false; // optional
-
- private boolean scheduleLink = false; // optional
-
- public SearchResultColumn(String columnId, String columnTitle) {
- super();
- setColumnId(columnId);
- setColumnTitle(columnTitle);
- } // SearchResultColumn
-
- public SearchResultColumn(String columnId, String columnTitle, String columnWidth, String alignment) {
- super();
- setColumnId(columnId);
- setColumnTitle(columnTitle);
- setColumnWidth(columnWidth);
- setAlignment(alignment);
- } // SearchResultColumn
-
- public SearchResultColumn(String columnId, String columnTitle, String columnWidth, String alignment,
- String linkURL, String linkTitle, String linkForm, String linkConfirmMsg,
- String linkImg) {
- super();
- setColumnId(columnId);
- setColumnTitle(columnTitle);
- setColumnWidth(columnWidth);
- setAlignment(alignment);
- setLinkURL(linkURL);
- setLinkTitle(linkTitle);
- setLinkForm(linkForm);
- setLinkConfirmMsg(linkConfirmMsg);
- setLinkImg(linkImg);
- } // SearchResultColumn
-
- public SearchResultColumn(String columnId, String columnTitle, String columnWidth, String alignment,
- String linkURL, String linkTitle, String linkForm, String linkConfirmMsg,
- String linkImg, String linkImgWidth, String linkImgHeight) {
- this(columnId, columnTitle, columnWidth, alignment, linkURL, linkTitle, linkForm,
- linkConfirmMsg, linkImg);
-
- setLinkWidth(linkImgWidth);
- setLinkHeight(linkImgHeight);
- } // SearchResultColumn
-
- public SearchResultColumn(String columnId, String columnTitle, String columnWidth, String alignment,
- String linkURL, String linkTitle, String linkForm, String linkConfirmMsg,
- String linkImg, String linkImgWidth, String linkImgHeight, boolean copyLink,
- boolean editLink, boolean deleteLink) {
- this(columnId, columnTitle, columnWidth, alignment, linkURL, linkTitle, linkForm,
- linkConfirmMsg, linkImg, linkImgWidth, linkImgHeight);
-
- setCopyLink(copyLink);
- setEditLink(editLink);
- setDeleteLink(deleteLink);
- } // SearchResultColumn
-
- public SearchResultColumn(String columnId, String columnTitle, String columnWidth, String alignment,
- String linkURL, String linkTitle, String linkForm, String linkConfirmMsg,
- String linkImg, String linkImgWidth, String linkImgHeight, boolean copyLink,
- boolean editLink, boolean deleteLink, boolean scheduleLink) {
- this(columnId, columnTitle, columnWidth, alignment, linkURL, linkTitle, linkForm,
- linkConfirmMsg, linkImg, linkImgWidth, linkImgHeight);
-
- setCopyLink(copyLink);
- setEditLink(editLink);
- setDeleteLink(deleteLink);
- setScheduleLink(scheduleLink);
- } // SearchResultColumn
-
- public String getColumnTitle() {
- return columnTitle;
- }
-
- public String getColumnWidth() {
- return columnWidth;
- }
-
- public String getAlignment() {
- return alignment;
- }
-
- public String getLinkURL() {
- return linkURL;
- }
-
- public String getLinkTitle() {
- return linkTitle;
- }
-
- public String getLinkForm() {
- return linkForm;
- }
-
- public String getLinkConfirmMsg() {
- return linkConfirmMsg;
- }
-
- public String getLinkImg() {
- return linkImg;
- }
-
- public String getLinkImgWidth() {
- return linkImgWidth;
- }
-
- public String getLinkImgHeight() {
- return linkImgHeight;
- }
-
- public boolean isCopyLink() {
- return copyLink;
- }
-
- public boolean isEditLink() {
- return editLink;
- }
-
- public boolean isDeleteLink() {
- return deleteLink;
- }
-
- public void setColumnTitle(String columnTitle) {
- this.columnTitle = nvl(columnTitle);
- }
-
- public void setColumnWidth(String columnWidth) {
- this.columnWidth = nvl(columnWidth);
- }
-
- public void setAlignment(String alignment) {
- this.alignment = alignment;
- }
-
- public void setLinkURL(String linkURL) {
- this.linkURL = linkURL;
- }
-
- public void setLinkTitle(String linkTitle) {
- this.linkTitle = linkTitle;
- }
-
- public void setLinkForm(String linkForm) {
- this.linkForm = linkForm;
- }
-
- public void setLinkConfirmMsg(String linkConfirmMsg) {
- this.linkConfirmMsg = linkConfirmMsg;
- }
-
- public void setLinkImg(String linkImg) {
- this.linkImg = linkImg;
- }
-
- public void setLinkWidth(String linkImgWidth) {
- this.linkImgWidth = linkImgWidth;
- }
-
- public void setLinkHeight(String linkImgHeight) {
- this.linkImgHeight = linkImgHeight;
- }
-
- public void setCopyLink(boolean copyLink) {
- this.copyLink = copyLink;
- }
-
- public void setEditLink(boolean editLink) {
- this.editLink = editLink;
- }
-
- public void setDeleteLink(boolean deleteLink) {
- this.deleteLink = deleteLink;
- }
-
- public String getColumnTitleHtml() {
- return (columnTitle.length() == 0) ? " " : columnTitle;
- }
-
- public String getColumnWidthHtml() {
- return (columnWidth.length() == 0) ? "" : (" width=" + columnWidth);
- }
-
- public String getLinkImgSizeHtml() {
- return ((nvl(linkImgWidth).length() > 0) ? " width=\"" + linkImgWidth + "\"" : "")
- + ((nvl(linkImgHeight).length() > 0) ? " height=\"" + linkImgHeight + "\""
- : "");
- }
-
- public boolean isScheduleLink() {
- return scheduleLink;
- }
-
- public void setScheduleLink(boolean scheduleLink) {
- this.scheduleLink = scheduleLink;
- }
-
- public String getColumnId() {
- return columnId;
- }
-
- public void setColumnId(String columnId) {
- this.columnId = columnId;
- }
-
-} // SearchResultColumn
+++ /dev/null
-/*-
- * ================================================================================
- * 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.search;
-
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class SearchResultField extends org.openecomp.portalsdk.analytics.RaptorObject {
- private String columnId;
- private String displayValue = "";
-
- private String alignment = "Left";
-
- private String drillDownLink = null;
-
- private String drillDownImage = null;
-
- private String confirmationText = null;
-
-
-
- public String getConfirmationText() {
- return confirmationText;
- }
-
- public void setConfirmationText(String confirmationText) {
- this.confirmationText = confirmationText;
- }
-
- public String getDrillDownImage() {
- return drillDownImage;
- }
-
- public void setDrillDownImage(String drillDownImage) {
- this.drillDownImage = drillDownImage;
- }
-
- public SearchResultField() {
- }
-
- public SearchResultField(String displayValue, String linkIdValue,
- SearchResultColumn column, boolean isAuthorized) {
- super();
-
- if (!isAuthorized)
- return;
-
- setColumnId(column.getColumnId());
- setDisplayValue(displayValue);
- setAlignment(column.getAlignment());
- if(column.getColumnId().equals("edit")) {
-// setDrillDownLink("report_wizard.htm?action=report.edit&c_master="+linkIdValue);
- setDrillDownLink("report#/report_wizard/"+linkIdValue);
- setDrillDownImage(column.getLinkImg());
- setConfirmationText(null);
- } else if(column.getColumnId().equals("copy")) {
-// setDrillDownLink("report_wizard.htm?action=report.copy&c_master="+linkIdValue);
- setDrillDownLink("report#/report_wizard/copy/"+linkIdValue);
- setDrillDownImage(column.getLinkImg());
- setConfirmationText(column.getLinkConfirmMsg());
- } else if(column.getColumnId().equals("delete")) {
- setDrillDownLink("raptor.htm?action=report.delete&c_master="+linkIdValue);
- setDrillDownImage(column.getLinkImg());
- setConfirmationText(column.getLinkConfirmMsg());
- } else if(column.getColumnId().equals("schedule")) {
- setDrillDownLink("report_wizard.htm?action=report.schedule.report.submit_wmenu&c_master="+linkIdValue+"&refresh=Y");
- setDrillDownImage(column.getLinkImg());
- setConfirmationText(null);
- } else if(column.getColumnId().equals("run")) {
- setDrillDownLink("raptor.htm?action=report.run.container&c_master="+linkIdValue+"&refresh=Y");
- setDrillDownImage(column.getLinkImg());
- setConfirmationText(null);
- } else {
- if (column.getLinkURL() != null) {
- StringBuffer sb = new StringBuffer();
-
- if (column.getLinkForm() == null) {
- sb.append("<a href=\"");
- sb.append(column.getLinkURL());
- sb.append(nvl(linkIdValue));
- if (column.getLinkConfirmMsg() != null) {
- sb.append(" onClick=\"return confirm('");
- sb.append(column.getLinkConfirmMsg());
- sb.append("');\"");
- }
- sb.append("\">");
- if (column.getLinkImg() != null) {
- sb.append("<img src=\"");
- sb.append(column.getLinkImg());
- sb.append("\"");
- sb.append(column.getLinkImgSizeHtml());
- sb.append(" border=\"0\"");
- sb.append(column.getLinkTitle() != null ? " alt=\""
- + column.getLinkTitle()/*
- * +(column.isDeleteLink()?"
- * "+linkIdValue:"")
- */
- + "\"" : "");
- sb.append(">");
- } else
- sb.append(column.getLinkTitle());
- sb.append("</a>");
- } else {
- sb.append("<input type=\"");
- if (column.getLinkImg() != null) {
- sb.append("image\" src=\"");
- sb.append(column.getLinkImg());
- sb.append("\"");
- sb.append(column.getLinkImgSizeHtml());
- sb.append(" border=\"0\"");
- sb.append(column.getLinkTitle() != null ? " alt=\""
- + column.getLinkTitle()/*
- * +(column.isDeleteLink()?"
- * "+linkIdValue:"")
- */
- + "\"" : "");
- } else {
- sb.append("submit\" value=\"");
- sb.append(column.getLinkTitle());
- sb.append("\"");
- }
- sb.append(" onClick=\"");
- if (column.getLinkConfirmMsg() != null) {
- sb.append("if(! confirm('");
- sb.append(column.getLinkConfirmMsg());
- sb.append("')) return false; ");
- }
- sb.append(column.getLinkURL());
- sb.append(" document.");
- sb.append(column.getLinkForm());
- sb.append(".");
- sb.append(AppConstants.RI_REPORT_ID);
- sb.append(".value='");
- sb.append(nvl(linkIdValue));
- sb.append("';");
- sb.append(" document.");
- sb.append(column.getLinkForm());
- sb.append(".");
- sb.append("refresh");
- sb.append(".value='");
- sb.append("Y");
- sb.append("';\">");
- } // else
-
- setDrillDownLink(sb.toString());
- } // if
- }
- } // SearchResultField
-
- public String getDisplayValue() {
- return displayValue;
- }
-
- public String getAlignment() {
- return alignment;
- }
-
- public String getDrillDownLink() {
- return drillDownLink;
- }
-
- public void setDisplayValue(String displayValue) {
- this.displayValue = nvl(displayValue);
- }
-
- public void setAlignment(String alignment) {
- this.alignment = alignment;
- }
-
- public void setDrillDownLink(String drillDownLink) {
- this.drillDownLink = drillDownLink;
- }
-
- public String getTooltipValue() {
- return (displayValue.length() == 0) ? " " : displayValue;
- }
-
- /*public String getAlignmentHtml() {
- return (alignment.length() == 0) ? "" : (" align=" + alignment);
- }*/
-
- /*public String getDisplayValueLinkHtml() {
- if (nvl(drillDownLink).length() == 0)
- return getDisplayValueHtml();
- else
- return getDrillDownLink();
- } // getDisplayValueLinkHtml*/
-
- public String getColumnId() {
- return columnId;
- }
-
- public void setColumnId(String columnId) {
- this.columnId = columnId;
- }
-
-
-} // SearchResultField
+++ /dev/null
-/*-
- * ================================================================================
- * 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.search;
-
-import java.util.*;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.system.*;
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class SearchResultJSON{
-
- public ArrayList<SearchResultColumn> searchResultColumns = new ArrayList<SearchResultColumn>();
-
- public ArrayList<SearchResultRow> searchResultRows = new ArrayList<SearchResultRow>();
-
-
-
-
-
-
- public ArrayList<SearchResultColumn> getSearchResultColumns() {
- return searchResultColumns;
- }
-
- public void setSearchResultColumns(ArrayList<SearchResultColumn> searchResultColumns) {
- this.searchResultColumns = searchResultColumns;
- }
-
- public ArrayList<SearchResultRow> getSearchResultRows() {
- return searchResultRows;
- }
-
- public void setSearchResultRows(ArrayList<SearchResultRow> searchResultRows) {
- this.searchResultRows = searchResultRows;
- }
-
- public void addColumn(SearchResultColumn column) {
- searchResultColumns.add(column);
- } // addColumn
-
- public SearchResultColumn getColumn(int index) {
- return (SearchResultColumn) searchResultColumns.get(index);
- } // getColumn
-
- public int getNumColumns() {
- return searchResultColumns.size();
- } // getNumColumns
-
- public int getNumRows() {
- return searchResultRows.size();
- } // getNumRows
-
- public SearchResultRow getRow(int index) {
- return (SearchResultRow) searchResultRows.get(index);
- } // getRow
-
-
- private String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- private String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
-} // SearchResultJSON
+++ /dev/null
-/*-
- * ================================================================================
- * 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.search;
-
-import java.util.*;
-
-class ColumnContent {
- String columnId;
- SearchResultField searchresultField;
-
- public ColumnContent(String columnId, SearchResultField searchresultField) {
- this.columnId = columnId;
- this.searchresultField = searchresultField;
- }
- public String getColumnId() {
- return columnId;
- }
- public void setColumnId(String columnId) {
- this.columnId = columnId;
- }
- public SearchResultField getSearchresultField() {
- return searchresultField;
- }
- public void setSearchresultField(SearchResultField searchresultField) {
- this.searchresultField = searchresultField;
- }
-
-
-
-}
-public class SearchResultRow extends ArrayList {
-
-
- //private SearchResultField searchresultField;
- 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 SearchResultField getNext() {
- return hasNext() ? getSearchResultField(nextElemIdx++) : null;
- } // getNext
-
- public SearchResultField getSearchResultField(int idx) {
- return (SearchResultField) get(idx);
- } // getRowHeader
-
- public void addSearchResultField(SearchResultField searchResultField) {
- add(searchResultField);
- } // addSearchResultField
-
- public void addSearchResultField(int idx, SearchResultField searchResultField) {
- add(idx, searchResultField);
- } // addSearchResultField
-
- public void addColumnContent(ColumnContent cc ) {
-
- add(cc);
- } // addSearchResultField
-
- public void addColumnContent(int idx, ColumnContent cc) {
- add(idx, cc);
- } // addSearchResultField
-
-
-} // SearchResultRow
+++ /dev/null
-/*-
- * ================================================================================
- * 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.scheduler;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.math.BigDecimal;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.sql.Types;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.List;
-import java.util.Locale;
-
-import org.openecomp.portalsdk.analytics.error.ReportSQLException;
-import org.openecomp.portalsdk.analytics.system.DbUtils;
-
-//import oracle.jdbc.*;
-//import oracle.sql.BLOB;
-
-
-public class SchedulerUtil {
-
- private Connection conn = null;
-
- protected Connection getConnection() {
- return conn;
- }
-
- protected void setConnection(Connection _conn) {
- conn = _conn;
- }
-
- protected Connection init() throws SQLException, ReportSQLException{
- if(conn != null)
- return conn;
- conn = DbUtils.getConnection();
- return conn;
- }
-
- protected void closeConnection() throws SQLException {
- if(conn != null) conn.close();
- }
-
- public void insertOrUpdate(String sql) throws SQLException, ReportSQLException {
-
- Statement stat = null;
- try{
- //conn = getConnection();
- stat = conn.createStatement();
- stat.executeUpdate(sql);
-
- } finally{
- stat.close();
- //conn.close();
- }
- }
-
- public void updateBinaryStream(String sql, BigDecimal id, InputStream is, int size) throws SQLException, ReportSQLException, IOException {
-
- // cludge hack for oracle databases
- if(conn.getMetaData().getDatabaseProductName().toLowerCase().contains("oracle")) {
-/* updateBlob(sql,id,is,size);
-*/ throw new ReportSQLException("only maria db support for this ");
-
- }
-
- PreparedStatement stat = null;
- try {
- stat = conn.prepareStatement(sql);
- stat.setBigDecimal(2, id);
- stat.setBinaryStream(1, is, size);
- stat.executeUpdate();
-
- } finally{
- stat.close();
- }
-
- }
-
- /*public void updateBlob(String sql, BigDecimal id, InputStream is, int size) throws SQLException, ReportSQLException, IOException {
- PreparedStatement stat = null;
- OutputStream out = null;
- BLOB blob = null;
- try {
- stat = conn.prepareStatement(sql);
- blob = BLOB.createTemporary(conn,false, BLOB.DURATION_SESSION);
- out = blob.getBinaryOutputStream();
-
- int read;
- while((read = is.read()) != -1) {
- out.write(read);
- }
- out.flush();
-
- stat.setBigDecimal(2, id);
- stat.setBlob(1, blob);
- stat.executeUpdate();
-
- }
- catch (SQLException sqL) {
- sqL.printStackTrace();
- }
- finally{
- out.close();
- stat.close();
- }
-
- }*/
-
-
- public void insertOrUpdateWithPrepared(String sql, List<Object> params, List<Integer> types) throws SQLException, ReportSQLException {
-
- PreparedStatement stat = null;
- try{
- //conn = getConnection();
- stat = conn.prepareStatement(sql);
- conn.getMetaData();
- int i2;
- int paramLength = params.size();
- for(int i = 0 ; i< paramLength ; i++) {
- i2 = i+1;
- Object param = params.get(i);
- int type = types.get(i);
-
- if(param.equals("NULL")) {
- stat.setNull(i2, type);
- }
- else if(type == Types.VARCHAR) {
- stat.setString(i2, (String)param);
- }
- else if(type == Types.INTEGER) {
- stat.setInt(i2, (Integer)param);
- }
- else if(type == Types.NUMERIC) {
- stat.setLong(i2, (Long)param);
- }
- else if(type == Types.DOUBLE) {
- stat.setDouble(i2, (Double)param);
- }
- else if(type == Types.DATE) {
- stat.setDate(i2, (java.sql.Date)param);
- }
- else if(type == Types.TIMESTAMP) {
- stat.setTimestamp(i2, (java.sql.Timestamp)param);
- }
- else if(type == Types.BIGINT) {
- stat.setBigDecimal(i2, (BigDecimal)param);
- }
- else
- throw new SQLException("Unidentified Object; Please contact admin and have this method updated with the current object type");
-
- }
-
- stat.executeUpdate();
-
- } finally{
- stat.close();
- //conn.close();
- }
- }
-
-
- public Object getSingleResult(String sql, String fieldname) throws SQLException, ReportSQLException{
-
- Statement stat = null;
- ResultSet rs = null;
- Object o=null;
- try{
- //conn = getConnection();
- stat = conn.createStatement();
- rs = stat.executeQuery(sql);
-
- while (rs.next()) {
- o = rs.getObject(fieldname);
- }
- }
- catch(SQLException sqlE){
- sqlE.printStackTrace();
- }
-
- finally{
- if(rs!=null)
- rs.close();
- if(stat!=null)
- stat.close();
- //conn.close();
- }
- return o;
- }
-
- public InputStream getDBStream(String sql, String fieldname) throws SQLException, ReportSQLException, IOException{
-
- // cludge hack for oracle databases
- if(conn.getMetaData().getDatabaseProductName().toLowerCase().contains("oracle")) {
- /*return getDBBlob(sql,fieldname);*/
- throw new ReportSQLException("only maria db support for this ");
-
- }
-
-
- Statement stat = null;
- ResultSet rs = null;
- InputStream o=null;
- try{
- //conn = getConnection();
- stat = conn.createStatement();
- rs = stat.executeQuery(sql);
-
- while (rs.next()) {
- o = rs.getBinaryStream(fieldname);
- }
- }
- catch(SQLException sqlE){
- sqlE.printStackTrace();
- }
-
- finally{
- if(rs!=null)
- rs.close();
- if(stat!=null)
- stat.close();
- //conn.close();
- }
- return o;
- }
-
- /*public InputStream getDBBlob(String sql, String fieldname) throws SQLException, ReportSQLException, IOException{
-
-
- Statement stat = null;
- ResultSet rs = null;
- BLOB blob=null;
- ByteArrayInputStream in = null;
- try{
- stat = conn.createStatement();
- rs = stat.executeQuery(sql);
-
- if (rs.next()) {
- blob = ((OracleResultSet) rs).getBLOB(fieldname);
- in = new ByteArrayInputStream(blob.getBytes(1,(int)blob.length()));
-
- }
- }
- catch(SQLException sqlE){
- sqlE.printStackTrace();
- }
-
- finally{
- if(rs!=null)
- rs.close();
- if(stat!=null)
- stat.close();
- //conn.close();
- }
- return in;
- }
- */
-
- public void getAndExecute(String sql, Executor executor) throws SQLException, ReportSQLException{
- //Connection conn = getConnection();
- Statement stat = conn.createStatement();
- ResultSet rs = stat.executeQuery(sql);
-
-
- while (rs.next()) {
- executor.execute(rs);
- }
-
- if(rs!=null)
- rs.close();
- if(stat!=null)
- stat.close();
- //conn.close();
- }
-
- interface Executor{
- public void execute(ResultSet rs) throws SQLException;
- }
-
-
-
-
-
-
- public static Date trunc_hour(Date v_date) {
-
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(v_date);
- calendar.set(Calendar.MILLISECOND, 0);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MINUTE, 0);
- return calendar.getTime();
- }
-
- public static Date add_hours(Date v_date, int i) {
-
- Calendar cal = Calendar.getInstance();
- cal.setTime(v_date);
- cal.add(Calendar.HOUR, i);
- return cal.getTime();
- }
-
- public static Date add_months(Date v_date, int i) {
-
- Calendar cal = Calendar.getInstance();
- cal.setTime(v_date);
- cal.add(Calendar.MONTH, i);
- return cal.getTime();
- }
-
- public static Date add_days(Date v_date, int i) {
-
- Calendar cal = Calendar.getInstance();
- cal.setTime(v_date);
- cal.add(Calendar.DATE, i);
- return cal.getTime();
- }
-
- public static Date to_date(String input, String format) {
-
- Date date = null;
- try {
- date = new SimpleDateFormat(format, Locale.ENGLISH).parse(input);
- } catch (Exception e) {
- }
- return date;
- }
-
- public static String to_date_str(Date input, String format) {
-
- String date = null;
- try {
- date = new SimpleDateFormat(format, Locale.ENGLISH).format(input);
- } catch (Exception e) {
- }
- return date;
- }
-
- public static String[] cr_dissecturl(String formfields, String delimiter){
- if(formfields == null || formfields.isEmpty())
- return new String[]{};
- return formfields.split("&");
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.scheduler;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigDecimal;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.List;
-
-import org.openecomp.portalsdk.analytics.error.ReportSQLException;
-import org.openecomp.portalsdk.analytics.scheduler.SchedulerUtil.Executor;
-import org.openecomp.portalsdk.analytics.system.Globals;
-
-
-
-
-public class SendEmail {
-
-SchedulerUtil schedulerUtil;
-
- public SendEmail() {
-
- }
-
-
- public void sendEmail( String p_mail_server, String p_sender, String p_subject, String p_mail_text, String p_url, int p_file_type, int p_schedule_id, int p_time_interval, boolean p_send_attachment, int connectionTimeout) throws SQLException, ReportSQLException{
-
- String allEmailAddr = "";
- final List<String> emailArr = new ArrayList<String>();
- //int count1 = 0;
- String schedular_email;
-
-
- schedular_email = (String) schedulerUtil.getSingleResult("select email from fn_user au, cr_report_schedule crs where CRS.SCHED_USER_ID = AU.USER_ID and CRS.SCHEDULE_ID = "+ p_schedule_id, "email");
-
-
- String sql=Globals.getSchedulerUserEmails().replace("[p_schedule_id]", p_schedule_id+"");
- schedulerUtil.getAndExecute(sql, new Executor() {
-
- @Override
- public void execute(ResultSet rs) throws SQLException {
-
- emailArr.add(rs.getString("email"));
- // count1 = count1 + 1
- }
-
- });
-
- if (!p_send_attachment) {
- http_to_blob(p_url, p_file_type, p_schedule_id, connectionTimeout);
- }
-
- int i = 0;
- for (String email : emailArr) {
- /* If the email address is invalid ignore that email address */
- if (email.contains("@")) {
-
- if (i == 0)
- allEmailAddr = email;
- else
- allEmailAddr += ',' + email;
-
- i++;
- }
- }
-
- /*List<MailAttachment> mailAttachments = null;
-
- if (p_file_type > 1 && p_send_attachment) {
- mailAttachments = add_attachment(p_url, p_file_type, p_schedule_id, connectionTimeout);
- }
- AppUtils.notifyWithAttachments(p_mail_text, emailArr.toArray(new String[emailArr.size()]), p_sender, p_subject, new String[] { schedular_email }, null, mailAttachments, true);
- */
- }
-
- class HistRec {
-
- String file_blob;
- BigDecimal rep_id;
- BigDecimal hist_id;
- String file_name;
- int sched_user_id;
- String recurrence;
- int file_size = 0;
- String raptor_url;
- int schedule_id;
- int file_type_id;
- int user_id;
- String deleted_yn;
- }
-
-
- private HistRec http_to_blob(String p_url, int v_file_type, int p_schedule_id, int connectionTimeout) throws SQLException , ReportSQLException{
-
-
- final HistRec v_hist_rec = initializeVHistoryRecord(p_url, v_file_type, p_schedule_id);
- HttpURLConnection con = null;
- try {
- URL url = new URL(p_url);
- con = (HttpURLConnection) url.openConnection();
- con.setConnectTimeout(connectionTimeout*1000);
- con.setRequestMethod("GET");
- schedulerUtil.insertOrUpdate("INSERT INTO cr_filehist_log (SCHEDULE_ID, url, notes, run_time) VALUES ("+ p_schedule_id +",'" + p_url+ "','http_to_blob: Initiated HTTP request', " + Globals.getCurrentDateString() + " )");
- int responseCode = con.getResponseCode();
- String outputFolder = Globals.getProjectFolder() + java.io.File.separator + Globals.getOutputFolder();
- String fileName = v_hist_rec.file_name;
- createFile(con, outputFolder, fileName);
-
- File readFile = new File(outputFolder + java.io.File.separator + fileName);
- // need to revist this conversion; may not be safe for large file sizes
- v_hist_rec.file_size = (int)readFile.length();
-
- schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url +"', 'http_to_blob: http response recieved. Code " + responseCode + "', " + Globals.getCurrentDateString() + " )");
-
- //v_hist_rec.file_blob = response.toString();
- //v_hist_rec.file_size = v_hist_rec.file_blob.length();
-
- List<Object> params = new ArrayList<Object>();
- List<Integer> types = new ArrayList<Integer>();
- prepareHisRecUpdate(v_hist_rec, params, types);
-
- schedulerUtil
- .insertOrUpdateWithPrepared("INSERT INTO cr_report_file_history(HIST_ID, SCHED_USER_ID, SCHEDULE_ID, USER_ID, REP_ID, RUN_DATE, RECURRENCE, FILE_TYPE_ID, FILE_NAME, FILE_SIZE, RAPTOR_URL, ERROR_YN, ERROR_CODE, DELETED_YN, DELETED_BY)"
- + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
- params, types
- );
-
- FileInputStream fileStream = new FileInputStream(readFile);
- schedulerUtil.updateBinaryStream("update cr_report_file_history set file_blob = ? where hist_id = ?", v_hist_rec.hist_id, fileStream, v_hist_rec.file_size);
- fileStream.close();
-
- String userAddRecSql =
- Globals.getSchedulerUserEmails().replace("[p_schedule_id]", p_schedule_id+"");
-
- schedulerUtil.getAndExecute(userAddRecSql, new Executor() {
-
- @Override
- public void execute(ResultSet rs) throws SQLException {
-
- try {
- schedulerUtil.insertOrUpdate("INSERT INTO CR_HIST_USER_MAP (HIST_ID, USER_ID) values ( " + v_hist_rec.hist_id + "," + rs.getInt("user_id") + ")");
- } catch (ReportSQLException e) {
- throw new SQLException(e.getMessage());
- }
- }
-
- });
-
- schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url + "','Success: http_to_blob', " + Globals.getCurrentDateString() + " )");
-
-
- } catch (Exception e) {
- schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url + "', 'Failure: http_to_blob : Exception" + e.getMessage() +"', " + Globals.getCurrentDateString() + " )");
- e.printStackTrace();
- } finally {
- if(con != null)
- con.disconnect();
- }
- return v_hist_rec;
-
- }
-
-
- protected void prepareHisRecUpdate(final HistRec v_hist_rec, List<Object> params,
- List<Integer> types) {
- params.add( v_hist_rec.hist_id);
- types.add(Types.BIGINT);
- params.add( v_hist_rec.sched_user_id);
- types.add(Types.INTEGER);
- params.add( v_hist_rec.schedule_id);
- types.add(Types.INTEGER);
- params.add( v_hist_rec.user_id);
- types.add(Types.INTEGER);
- params.add( v_hist_rec.rep_id);
- types.add(Types.BIGINT);
- params.add( new java.sql.Date(Calendar.getInstance().getTime().getTime()));
- types.add(Types.DATE);
- params.add( v_hist_rec.recurrence);
- types.add(Types.VARCHAR);
- params.add( v_hist_rec.file_type_id);
- types.add(Types.INTEGER);
- params.add( v_hist_rec.file_name);
- types.add(Types.VARCHAR);
- params.add( v_hist_rec.file_size);
- types.add(Types.INTEGER);
- params.add( v_hist_rec.raptor_url);
- types.add(Types.VARCHAR);
- params.add( "N");
- types.add(Types.VARCHAR);
- params.add( "NULL");
- types.add(Types.INTEGER);
- params.add( v_hist_rec.deleted_yn);
- types.add(Types.VARCHAR);
- params.add(v_hist_rec.sched_user_id );
- types.add(Types.INTEGER);
- }
-
-
- protected HistRec initializeVHistoryRecord(String p_url, int v_file_type,
- int p_schedule_id) throws SQLException,
- ReportSQLException {
-
- final HistRec v_hist_rec = new HistRec();
-
- v_hist_rec.rep_id = (BigDecimal) schedulerUtil.getSingleResult("SELECT rep_id FROM cr_report_schedule WHERE schedule_id =" + p_schedule_id, "rep_id");
-
- Object sequenceId = schedulerUtil.getSingleResult(Globals.getSequenceNextVal().replace("[sequenceName]", "seq_cr_report_file_history"),"ID");
-
- if(sequenceId instanceof Long)
- v_hist_rec.hist_id = new BigDecimal((Long)sequenceId);
- else if(sequenceId instanceof BigDecimal)
- v_hist_rec.hist_id = (BigDecimal)sequenceId;
-
- v_hist_rec.file_name = (String) schedulerUtil.getSingleResult("select translate(title||to_char( "+ Globals.getCurrentDateString() + ",'MM-dd-yyyyHH24:mm:ss'), "
- + "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'||'():;.-`~^\\|'||chr(34)||chr(39)||chr(9)||' ', "
- + "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')|| "+ v_hist_rec.hist_id +" as title FROM cr_report WHERE rep_id = "+v_hist_rec.rep_id, "title");
-
-
- class File {
-
- String file_name;
- String file_ext;
- }
- final File file = new File();
- schedulerUtil.getAndExecute("select template_file from cr_report_template_map where report_id = " + v_hist_rec.rep_id, new Executor() {
-
- @Override
- public void execute(ResultSet rs) throws SQLException {
-
- file.file_name = rs.getString("template_file");
- file.file_ext = file.file_name.substring(file.file_name.indexOf('.'));
-
- }
- });
-
- if (v_file_type == 2) {
- v_hist_rec.file_name = v_hist_rec.file_name + ".pdf";
-
- } else if (v_file_type == 4) {
- v_hist_rec.file_name = v_hist_rec.file_name + ".xls";
-
- } else if (v_file_type == 5) {
- if (file.file_name != null && file.file_ext.length() > 0) {
- v_hist_rec.file_name = v_hist_rec.file_name + file.file_ext;
- } else {
- v_hist_rec.file_name = v_hist_rec.file_name + ".xlsx";
- }
- } else if (v_file_type == 3) {
- v_hist_rec.file_name = v_hist_rec.file_name + ".csv";
-
- }
-
-
- schedulerUtil.getAndExecute("select sched_user_id, rep_id, recurrence from cr_report_schedule where schedule_id="+p_schedule_id, new Executor() {
-
- @Override
- public void execute(ResultSet rs) throws SQLException {
- v_hist_rec.sched_user_id = rs.getInt("sched_user_id");
- v_hist_rec.rep_id = rs.getBigDecimal("rep_id");
- v_hist_rec.recurrence = rs.getString("recurrence");
- }
- });
-
-
- v_hist_rec.file_size = 0;
- v_hist_rec.raptor_url = p_url;
- v_hist_rec.schedule_id = p_schedule_id;
- v_hist_rec.file_type_id = v_file_type;
- v_hist_rec.user_id = v_hist_rec.sched_user_id;
- v_hist_rec.deleted_yn = "N";
-
- return v_hist_rec;
- }
-
-
-
- /*private List<MailAttachment> add_attachment(String p_url, int v_file_type, int p_schedule_id, int connectionTimeout) throws SQLException,ReportSQLException{
-
-
- List<MailAttachment> mailAttachmentList = new ArrayList<MailAttachment>();
- final HistRec vHistRec = initializeVHistoryRecord(p_url, v_file_type, p_schedule_id);
-
- /*
- refer to http_to_blob for more details
-
- String v_content_type;
- String v_content_disposition;
- int transfer_timeout_limit = 1800;
- String v_title;
-
- if (v_file_type == 2) {
- v_content_type = "application/pdf";
- v_content_disposition ="inline; filename=\""+v_title+".pdf\"";
-
- }else if(v_file_type == 4){
- v_content_type = "application/excel";
- v_content_disposition ="inline; filename=\""+v_title+".xls\"";
-
- }else if(v_file_type == 5){
- v_content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
-
- if (file.file_ext != null && file.file_ext.length() > 0) {
- v_content_disposition ="inline; filename=\""+v_title+ file.file_ext+"\"";
- if (".xlsm".equals(file.file_ext)) {
- v_content_type = "application/vnd.ms-excel.sheet.macroEnabled.12";
- }
- } else {
- v_content_disposition ="inline; filename=\""+v_title+".xlsx\"";
- };
- }else if(v_file_type == 3){
- v_content_type = "application/csv";
- v_content_disposition ="inline; filename=\""+v_title+".csv\"";
-
- }
- * ... /
- HttpURLConnection con = null;
- try {
- URL url = new URL(p_url);
- con = (HttpURLConnection) url.openConnection();
- con.setConnectTimeout(connectionTimeout*1000);
- con.setRequestMethod("GET");
- schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'"+ p_url +"', 'Success: http request began.', " + Globals.getCurrentDateString() + " )");
- int responseCode = con.getResponseCode();
-
- String outputFolder = Globals.getProjectFolder() + java.io.File.separator + Globals.getOutputFolder();
- String fileName = vHistRec.file_name;
- createFile(con, outputFolder, fileName);
-
- MailAttachment mailAttachment = new MailAttachment();
- mailAttachment.setAttachmentType(MailAttachment.FILE_ATTACHMENT);
- mailAttachment.setFilePathName(outputFolder);
- mailAttachment.setFileName(fileName);
- mailAttachmentList.add(mailAttachment);
-
- schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url +"', 'Success: http response recieved. Code " + responseCode + "', " + Globals.getCurrentDateString() + " )");
-
- schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url + "','Success: added attachment', " + Globals.getCurrentDateString() + " )");
-
- } catch (Exception e) {
- schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + p_schedule_id + ",'" + p_url + "', 'Failure: adding attachment : Exception" + e.getMessage() +"', " + Globals.getCurrentDateString() + " )");
- e.printStackTrace();
- } finally {
- if(con != null)
- con.disconnect();
- }
-
-
- return mailAttachmentList;
- }*/
-
-
- void createFile(HttpURLConnection con, String outputFolder, String fileName)
- throws IOException, FileNotFoundException {
- //BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
- InputStream in = con.getInputStream();
-
- try {
-
- FileOutputStream out = new FileOutputStream(outputFolder + java.io.File.separator + fileName );
- try {
- int inputLine;
-
- while ((inputLine = in.read()) != -1) {
- out.write(inputLine);
- }
- out.flush();
- }
- finally {
- out.close();
- }
-
- }
- finally {
- in.close();
- }
- }
-
-
- public SchedulerUtil getSchedulerUtil() {
- return schedulerUtil;
- }
-
-
- public void setSchedulerUtil(SchedulerUtil schedulerUtil) {
- this.schedulerUtil = schedulerUtil;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.scheduler;
-
-import java.math.BigDecimal;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.UUID;
-
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.error.ReportSQLException;
-import org.openecomp.portalsdk.analytics.scheduler.SchedulerUtil.Executor;
-import org.openecomp.portalsdk.analytics.system.Globals;
-import org.openecomp.portalsdk.analytics.util.Log;
-
-public class SendNotifications {
-
- SchedulerUtil schedulerUtil;
- public SendEmail sendEmail;
-
- public SendNotifications() throws Exception {
- schedulerUtil = new SchedulerUtil();
- sendEmail = new SendEmail();
- sendEmail.setSchedulerUtil(schedulerUtil);
- init();
- }
-
-
- public void deInit() throws SQLException {
- schedulerUtil.closeConnection();
- }
-
- public void init() throws SQLException, ReportSQLException {
- schedulerUtil.init();
- }
-
- public void send_notification(String p_mail_server, String p_sender, String p_system_name, String p_system_url, int connectionTimeout) throws RaptorException, Exception {
-
- System.out.println(p_mail_server + " " + p_sender + " " + p_system_name + " " + p_system_url);
- int p_time_interval = Globals.getSchedulerInterval();
- int v_num_recs = 0;
- String v_gen_key;
- BigDecimal v_id = null;
- String v_url;
- String v_r_action = "report.download.pdf";
- String v_email_msg;
- String v_formfields;
- // String error_m;
- // int transfer_timeout_limit = 1800;
- // boolean v_attach_email_yn = true;
- int v_schedule_id;
- Date v_touch_date;
- // Exception for_rec;
-
- Connection conn = schedulerUtil.getConnection();
- Statement stat = conn.createStatement();
-
- String CNotificationsql =
- /*
- "SELECT x.rep_id, x.schedule_id, x.conditional_yn, x.condition_large_sql, x.notify_type, x.max_row, x.initial_formfields, x.processed_formfields, r.title, x.user_id "
- + "FROM ("
- + "SELECT rs.rep_id, rs.schedule_id, rs.sched_user_id user_id, rs.conditional_yn, rs.condition_large_sql, "
- + "rs.notify_type, rs.max_row, rs.initial_formfields, rs.processed_formfields "
- + "FROM cr_report_schedule rs "
- + "WHERE rs.enabled_yn='Y' "
- + "AND rs.start_"
- + "date <= sysdate "
- + "AND (rs.end_date >= sysdate or rs.end_date is null ) "
- + "AND rs.run_date IS NOT NULL "
- + ") x, cr_report r "
- + "WHERE x.rep_id = r.rep_id ";
- */
-
- Globals.getAvailableSchedules().replace("[currentDate]", Globals.getCurrentDateString());
-
-
- ResultSet rs = stat.executeQuery(CNotificationsql);
-
- while (rs.next()) {
-
- v_schedule_id = rs.getInt("schedule_id");
- int offset = get_report_sched_offset(rs.getInt("rep_id"), v_schedule_id);
-
- if(offset >= p_time_interval) continue;
-
-
- v_touch_date = (Date) schedulerUtil.getSingleResult("select touch_date from cr_report_email_sent_log where schedule_id = " + v_schedule_id + " and log_id = (select max(log_id) from cr_report_email_sent_log where schedule_id = " + v_schedule_id + ")", "touch_date");
- if (v_touch_date != null) {
- if (Math.abs(System.currentTimeMillis() - v_touch_date.getTime()) /1000 < (p_time_interval - 1)) {
- return;
- }
- }
-
- if ("Y".equals(rs.getString("conditional_yn"))) {
-
- v_num_recs = (Integer) schedulerUtil.getSingleResult("select count(*) count from (" + rs.getString("condition_large_sql") + " )", "count");
- }
-
- if (v_num_recs > 0 || "N".equals(rs.getString("conditional_yn"))) {
-
- v_gen_key = ("Z" + UUID.randomUUID()).toString().substring(0,24); // 25 character string
- Object sequenceId = schedulerUtil.getSingleResult(Globals.getSequenceNextVal().replace("[sequenceName]", "seq_email_sent_log_id"), "id");
-
- if(sequenceId instanceof Long)
- v_id = new BigDecimal((Long)sequenceId);
- else if(sequenceId instanceof BigDecimal)
- v_id = (BigDecimal)sequenceId;
-
- schedulerUtil.insertOrUpdate("insert into cr_report_email_sent_log (log_id, gen_key, schedule_id, rep_id, user_id, touch_date) values (" + v_id + ",'" + v_gen_key + "'," + rs.getInt("schedule_id") + "," + rs.getInt("rep_id") + "," + rs.getInt("user_id") + ", " + Globals.getCurrentDateString() + " )");
-
- int notify_type = rs.getInt("notify_type");
- if (notify_type == 4)
- v_r_action = "report.download";
- else if (notify_type == 2)
- v_r_action = "report.download.pdf";
- else if (notify_type == 3)
- v_r_action = "report.csv.download";
- else if (notify_type == 5)
- v_r_action = "report.download.excel2007";
- else if (notify_type == 6)
- v_r_action = "download.all";
-
- if (rs.getObject("processed_formfields") != null)
- v_formfields = modify_formfields(v_schedule_id, rs.getString("processed_formFields"));
- else
- v_formfields = strip_formfields(v_schedule_id, rs.getString("initial_formfields"));
-
- v_url = p_system_url + "&r_action=" + v_r_action + "&log_id=" + v_id + "&user_id=" + rs.getString("user_id") + "&pdfAttachmentKey=" + v_gen_key + "&download_limit=" + rs.getInt("max_row") + v_formfields;
-
- boolean v_attach_email_yn = shouldSendAttachmentInEmail(v_schedule_id);
-
- v_email_msg = "<html><body><p><b><u><i>" + p_system_name + " System Notification</i></u></b></p>" + "<p>Report <b>" + rs.getString("title") + "</b> is available for viewing.</p><p>You can view the report if it is attached. </br>"
- + "If it is not attached, or you have problem to open it, you can log into Business Direct and run the report.</p>" + "</body></html>";
-
- if (rs.getInt("notify_type") != 6) {
-
- sendEmail.sendEmail(p_mail_server, p_sender, p_system_name + " System Notification: Report " + rs.getString("title") + " generated", v_email_msg, v_url, rs.getInt("notify_type"), v_schedule_id, p_time_interval, v_attach_email_yn,connectionTimeout);
-
- } else {
-
- // may not necessary
- schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + v_schedule_id + ",'" + v_url + "'," + "'Success: http request began.', " + Globals.getCurrentDateString() + " )");
- schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + v_schedule_id + ",'" + v_url + "'," + "'Success: http response recieved. Code resp.status_code '' desc '' resp.reason_phrase', " + Globals.getCurrentDateString() + " )");
-
- }
-
- schedulerUtil.insertOrUpdate("update cr_report_schedule set run_date = " + Globals.getCurrentDateString() +" where schedule_id=" + v_schedule_id);
-
- schedulerUtil.insertOrUpdate("update cr_report_email_sent_log set sent_date= " + Globals.getCurrentDateString() +" , access_flag='N' where log_id=" + v_id);
- schedulerUtil.insertOrUpdate("insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values (" + v_schedule_id + ",'" + v_url + "','Success: Email Sent', " + Globals.getCurrentDateString() + " )");
-
- }
-
- }
-
- if(rs!=null)
- rs.close();
- if(stat!=null)
- stat.close();
- //conn.close();
-
- }
-
- private boolean shouldSendAttachmentInEmail(int v_schedule_id) throws SQLException, ReportSQLException {
-
- String l_boolean = (String) schedulerUtil.getSingleResult("SELECT ATTACHMENT_YN from cr_report_schedule where schedule_id = " + v_schedule_id, "ATTACHMENT_YN");
- if ("Y".equals(l_boolean))
- return true;
- return false;
- }
-
- private String strip_formfields(int v_schedule_id, String p_formfields) throws SQLException, ReportSQLException {
-
- String v_formfields_insert = "";
- String v_formfields_generate = "";
- String v_name = "";
- String v_value = "";
-
-
- String[] column_values = schedulerUtil.cr_dissecturl(p_formfields, "&");
-
- for(String column_value : column_values){
- if(column_value == null || column_value.isEmpty())
- continue;
-
- v_name = column_value.substring(0, column_value.indexOf('='));
- v_formfields_insert += column_value + "&";
- v_value = column_value.substring(column_value.indexOf('=') + 1);
- if (column_value.indexOf("_auto") > 0) {
- v_formfields_generate = v_formfields_generate + v_name.substring(0, v_name.indexOf("_auto")) + "=" + v_value + "&";
- } else {
- v_formfields_generate = v_formfields_generate + column_value + "&";
- }
- }
-
- schedulerUtil.insertOrUpdate("update CR_REPORT_SCHEDULE set processed_formfields ='" + v_formfields_insert + "' where schedule_id = " + v_schedule_id);
-
- return v_formfields_generate.substring(0, v_formfields_generate.length());
-
- }
-
- private String modify_formfields(int v_schedule_id, String p_formfields) throws SQLException, ReportSQLException {
-
- class Result {
-
- String v_formfields_insert = "";
- String v_formfields_generate = "";
- String v_name = "";
- String v_value = "";
- Date v_date;
- String v_hour = "";
- String v_hour_value = "";
- }
-
- final Result result = new Result();
-
- final String v_recurrence = (String) schedulerUtil.getSingleResult("select recurrence from cr_report_schedule where schedule_id = " + v_schedule_id, "recurrence");
-
- String[] column_values = schedulerUtil.cr_dissecturl(p_formfields, "&");
-
- for(String column_value : column_values){
- if (column_value == null)
- column_value = "";
-
- if ("MONTHLY".equals(v_recurrence)) {
- if (column_value.indexOf("_auto") > 0) {
- result.v_name = column_value.substring(0, column_value.indexOf('='));
- result.v_date = schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
- result.v_value = schedulerUtil.add_months(result.v_date, 1).toString();
-
- if (result.v_name.length() > 0) {
- result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
- result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value + "&";
- }
- } else {
- result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
- result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
- }
-
- } else if ("DAILY".equals(v_recurrence)) {
- if (column_value.indexOf("_auto") > 0) {
- result.v_name = column_value.substring(0, column_value.indexOf('='));
- result.v_date = schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
- result.v_value = schedulerUtil.add_months(result.v_date, 1).toString();
-
- if (result.v_name.length() > 0) {
- result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
- result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value + "&";
- }
- } else {
- result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
- result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
- }
-
- } else if ("DAILY_MO_FR".equals(v_recurrence)) {
- if (column_value.indexOf("_auto") > 0) {
- result.v_name = column_value.substring(0, column_value.indexOf('='));
- result.v_date = schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
- SimpleDateFormat sdf = new SimpleDateFormat("EEE");
- sdf.format(result.v_date);
- if ("FRI".equals(result.v_date.toString())) {
- result.v_date = schedulerUtil.add_days(result.v_date, 3);
- } else if ("SAT".equals(result.v_date.toString())) {
- result.v_date = schedulerUtil.add_days(result.v_date, 2);
- } else {
- result.v_date = schedulerUtil.add_days(result.v_date, 1);
- }
- result.v_value = result.v_date.toString();
- if (result.v_name.length() > 0) {
- result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
- result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value + "&";
- }
-
- } else {
- result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
- result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
- }
-
- } else if ("HOURLY".equals(v_recurrence)) {
-
- result.v_name = column_value.indexOf('=')>0?column_value.substring(0, column_value.indexOf('=')) : "";
- if (column_value.indexOf("_auto") > 0) {
-
-
- String[] column_values2 = schedulerUtil.cr_dissecturl(p_formfields, "&");
-
- for(String column_value2 : column_values2){
-
- String key = column_value2.substring(0, column_value2.indexOf("="));
- if(key.equals(result.v_name.substring(0, result.v_name.indexOf("_auto"))) || key.equals(result.v_name.substring(0, result.v_name.indexOf("_Hr")))){
- result.v_hour = column_value2;
- }
- }
-
-// schedulerUtil.getAndExecute("select c.column_value from table(CR_DISSECTURL(p_formfields)) c where substr(c.column_value, 1, instr(c.column_value, '=')-1) = substr(" + result.v_name + ",1,instr(" + result.v_name + ",'_auto')-1)||'_Hr'", new Executor() {
-//
-// @Override
-// public void execute(ResultSet rs) throws SQLException {
-//
-// result.v_hour = rs.getString("column_value");
-// }
-//
-// });
-
- if (result.v_hour.length() > 0) {
- result.v_hour_value = result.v_hour.substring(result.v_hour.indexOf('=') + 1);
- }
-
- result.v_date = schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1) + " " + result.v_hour_value, "mm/dd/yyyy HH24:MI:SS");
-
- result.v_value = schedulerUtil.to_date_str(schedulerUtil.add_hours(result.v_date, 1), "mm/dd/yyyy HH24");
-
- if (result.v_name.length() > 0) {
- if (result.v_hour.length() > 0) {
-
- result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value.substring(0, 10) + "&" + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "_Hr=" + result.v_value.substring(11, 13);
- result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value.substring(0, 10) + "&" + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "_Hr="
- + result.v_value.substring(11, 13) + "&";
-
- } else {
- result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
- result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value + "&";
- }
- }
- }
- if (column_value.indexOf("_Hr") <= 0) {
- result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
- result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
- }
- } else if ("WEEKLY".equals(v_recurrence)) {
-
- if (column_value.indexOf("_auto") > 0) {
- result.v_name = column_value.substring(0, column_value.indexOf('='));
- result.v_date = schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
- result.v_value = schedulerUtil.add_days(result.v_date, 7).toString();
-
- if (result.v_name.length() > 0) {
- result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
- result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value + "&";
- }
-
- } else {
- result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
- result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
- }
-
- } else {
- if (column_value.indexOf("_auto") > 0) {
- result.v_name = column_value.substring(0, column_value.indexOf('='));
- result.v_date = schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
- result.v_value = schedulerUtil.add_days(result.v_date, 7).toString();
- if (result.v_name.length() > 0) {
- result.v_formfields_insert = result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
- result.v_formfields_generate = result.v_formfields_generate + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value + "&";
- }
-
- } else {
- result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
- result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
- }
- }
- }
-
- schedulerUtil.insertOrUpdate("update CR_REPORT_SCHEDULE set processed_formfields ='" + result.v_formfields_insert + "' where schedule_id =" + v_schedule_id);
- return "&" + result.v_formfields_generate.substring(0, result.v_formfields_generate.length());
- }
-
- private int get_report_sched_offset(int p_rep_id, int p_schedule_id) throws SQLException, ReportSQLException {
-
- class CrReportSchedule {
-
- Date run_date;
- String recurrence;
- }
- Date v_last_date = null;
- Date v_sysdate = new Date();
-
- final CrReportSchedule v_report_schedule_rec = new CrReportSchedule();
-
- schedulerUtil.getAndExecute("SELECT * FROM cr_report_schedule WHERE rep_id = " + p_rep_id + " and schedule_id = " + p_schedule_id, new Executor() {
-
- @Override
- public void execute(ResultSet rs) throws SQLException {
-
- v_report_schedule_rec.recurrence = rs.getString("recurrence");
- java.sql.Timestamp runDate = rs.getTimestamp("run_date");
- v_report_schedule_rec.run_date = new Date(runDate.getTime()) ;
- }
-
- });
-
- if (v_report_schedule_rec.run_date == null || v_report_schedule_rec.run_date.compareTo(v_sysdate) > 0) {
- return Integer.MAX_VALUE;
- }
-
- Date v_next_date = v_report_schedule_rec.run_date;
-
- while (v_next_date.compareTo(v_sysdate) < 0) {
-
- if ("HOURLY".equals(v_report_schedule_rec.recurrence)) {
- v_next_date = SchedulerUtil.add_hours(v_next_date, 1);
- } else if ("DAILY".equals(v_report_schedule_rec.recurrence)) {
- v_next_date = SchedulerUtil.add_days(v_next_date, 1);
- } else if ("DAILY_MO_FR".equals(v_report_schedule_rec.recurrence)) {
- SimpleDateFormat sdf = new SimpleDateFormat("EEE");
- sdf.format(v_next_date);
- if ("FRI".equals(v_next_date.toString())) {
- v_next_date = SchedulerUtil.add_days(v_next_date, 3);
- } else if ("SAT".equals(v_next_date.toString())) {
- v_next_date = SchedulerUtil.add_days(v_next_date, 2);
- } else {
- v_next_date = SchedulerUtil.add_days(v_next_date, 1);
- }
- } else if ("WEEKLY".equals(v_report_schedule_rec.recurrence)) {
- v_next_date = SchedulerUtil.add_days(v_next_date, 7);
- } else if ("MONTHLY".equals(v_report_schedule_rec.recurrence)) {
- v_next_date = SchedulerUtil.add_months(v_next_date, 1);
- } else {
- break;
- }
- v_last_date = v_next_date;
- }
-
- if (SchedulerUtil.trunc_hour(v_last_date).compareTo(SchedulerUtil.trunc_hour(v_sysdate)) == 0) {
- return (int)(Math.abs (v_sysdate.getTime() - v_last_date.getTime()) / 1000);
- } else {
- // More than an hour
- return 3601;
- }
- }
-
- public SchedulerUtil getSchedulerUtil() {
- return schedulerUtil;
- }
-
- public void setSchedulerUtil(SchedulerUtil schedulerUtil) {
- this.schedulerUtil = schedulerUtil;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system;
-
-import java.io.File;
-import java.text.SimpleDateFormat;
-import java.util.*;
-
-import javax.servlet.http.*;
-
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class AppUtils /* implements IAppUtils */{
- private static String baseURL = null;
-
- private AppUtils() {
- }
-
- /** ******************************************************** */
-
- public static String generateFileName(HttpServletRequest request, String fileTypeExtension) {
- return AppConstants.FILE_PREFIX + getUserID(request) + fileTypeExtension;
- } // generateFileName
-
- public static String generateUniqueFileName(HttpServletRequest request, String reportName, String fileTypeExtension) {
- String formattedReportName = new HtmlStripper().stripSpecialCharacters(reportName);
- String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date());
- return formattedReportName+formattedDate+getUserID(request)+fileTypeExtension;
- } // generateFileName
-
- public static String getRequestValue(HttpServletRequest request, String valueID) {
- String value = (String) request.getAttribute(valueID);
- if (value == null)
- value = request.getParameter(valueID);
- return value;
- } // getRequestValue
-
- public static String getRequestNvlValue(HttpServletRequest request, String valueID) {
- String value = getRequestValue(request, valueID);
- return (value == null) ? "" : value;
- } // getRequestValue
-
- public static boolean getRequestFlag(HttpServletRequest request, String valueID) {
- String value = getRequestNvlValue(request, valueID);
- return value.toLowerCase().equals("true") || value.toUpperCase().startsWith("Y");
- } // getRequestFlag
-
- /** ******************************************************** */
-
- public static String getUserID(HttpServletRequest request) {
- return Globals.getAppUtils().getUserID(request);
- } // getUserID
-
- public static String getUserName(HttpServletRequest request) {
- return Globals.getAppUtils().getUserName(request);
- } // getUserName
-
- public static String getUserName(String userId) {
- return Globals.getAppUtils().getUserName(userId);
- } // getUserName
-
- public static String getUserEmail(String userId) {
- return Globals.getAppUtils().getUserEmail(userId);
- } // getUserEmail
-
- public static String getUserEmail(HttpServletRequest request) {
- return Globals.getAppUtils().getUserEmail(request);
- } // getUserEmail
-
- public static String getUserLoginId(HttpServletRequest request) {
- return Globals.getAppUtils().getUserLoginId(request);
- } // getUserLoginId
-
- public static String getUserLoginId(String userId) {
- return Globals.getAppUtils().getUserLoginId(userId);
- } // getUserLoginId
-
- public static String getUserBackdoorLoginId(HttpServletRequest request) {
- return Globals.getAppUtils().getUserBackdoorLoginId(request);
- } // getUserBackdoorLoginId
-
- public static Vector getAllUsers(String customizedQuery, String param, boolean isAdmin) {
- return Globals.getAppUtils().getAllUsers(customizedQuery, param, isAdmin);
- } // getAllUsers
-
- public static String getRoleName(String roleId) {
- return Globals.getAppUtils().getRoleName(roleId);
- } // getRoleName
-
- public static Vector getAllRoles(String customizedQuery, String param, boolean isAdmin) {
- return Globals.getAppUtils().getAllRoles(customizedQuery, param, isAdmin);
- } // getAllRoles
-
- public static boolean isUserInRole(HttpServletRequest request, String roleId) throws RaptorException {
- return Globals.getAppUtils().isUserInRole(request,roleId);
- } // isUserInRole
-
-// public static boolean isUserInRole(String userId, String roleId) throws RaptorException {
-// return Globals.getAppUtils().isUserInRole(userId, roleId);
-// } // isUserInRole
-
- public static Vector getUserRoles(HttpServletRequest request) throws RaptorException {
- return Globals.getAppUtils().getUserRoles(request);
- } // getUserRoles
-
- public static Vector getUserRoles(String userID) throws RaptorException {
- return Globals.getAppUtils().getUserRoles(userID);
- } // getUserRoles
-
-// public static Vector getUserRoles(HttpServletRequest request) throws RaptorException {
-// return Globals.getAppUtils().getUserRoles(request);
-// } // getUserRoles
-
- public static void resetUserCache() {
- Globals.getAppUtils().resetUserCache();
- } // resetUserCache
-
- public static String getSuperRoleID() {
- return Globals.getAppUtils().getSuperRoleID();
- } // getSuperRoleID
-
- public static Vector getAdminRoleIDs() {
- return Globals.getAppUtils().getAdminRoleIDs();
- } // getAdminRoleIDs
-
- // This is changed to check for Admin User as admin user also need super user privilege if explicitly specified in properties file.
- public static boolean isSuperUser(HttpServletRequest request)throws RaptorException {
- if(Globals.isAdminRoleEquivalenttoSuperRole()) return isAdminUser(request);
- else return isUserInRole(request, getSuperRoleID());
- } // isSuperUser
-
- /*public static boolean isSuperUser(String userId) throws RaptorException {
- if(Globals.isAdminRoleEquivalenttoSuperRole()) return isAdminUser(userId);
- else return isUserInRole(userId, getSuperRoleID());
- } // isSuperUser
- */
-
- public static boolean isAdminUser(HttpServletRequest request) throws RaptorException {
- if (isSuperUser(request))
- return true;
- for (int i = 0; i < getAdminRoleIDs().size(); i++)
- if (isUserInRole(request, (String) getAdminRoleIDs().get(i)))
- return true;
-
- return false;
- } // isAdminUser
-
- /*public static boolean isAdminUser(String userId) throws RaptorException {
- if (isSuperUser(userId))
- return true;
-
- for (int i = 0; i < getAdminRoleIDs().size(); i++)
- if (isUserInRole(userId, (String) getAdminRoleIDs().get(i)))
- return true;
-
- return false;
- } // isAdminUser
- */
-
- public static String getTempFolderPath() {
- String path = Globals.getAppUtils().getTempFolderPath();
- if (path.endsWith(File.separator) || path.endsWith("/")){
- return path;
- } else {
- path = path + File.separator;
- return path;
- }
- } // getTempFolderPath
-
- public static String getUploadFolderPath() {
- String path = Globals.getAppUtils().getUploadFolderPath();
- if (path.endsWith(File.separator)){
- return path;
- } else {
- path = path + File.separator;
- return path;
- }
- } // getUploadFolderPath
-
- public static String getTempFolderURL() {
- return Globals.getAppUtils().getTempFolderURL();
- } // getTempFolderURL
-
- public static String getUploadFolderURL() {
- return Globals.getAppUtils().getUploadFolderURL();
- } // getUploadFolderURL
-
- public static String getSMTPServer()throws Exception {
- return Globals.getAppUtils().getSMTPServer();
- } // getSMTPServer
-
- public static String getDefaultEmailSender() throws RaptorException {
- return Globals.getAppUtils().getDefaultEmailSender();
- } // getDefaultEmailSender
-
- public static String getErrorPage() {
- return getJspContextPath() + Globals.getAppUtils().getErrorPage();
- } // getErrorPage
-
- public static String getErrorPageWMenu() {
- return getJspContextPath() + Globals.getAppUtils().getErrorPageWMenu();
- } // getErrorPage
-
- public static String getJspContextPath() {
- return Globals.getAppUtils().getJspContextPath();
- } // getJspContextPath
-
- public static String getImgFolderURL() {
- return Globals.getAppUtils().getImgFolderURL();
- } // getImgFolderURL
-
- public static String getBaseFolderURL() {
- return Globals.getAppUtils().getBaseFolderURL();
- } // getBaseFolderURL
-
- public static String getChartScriptsPath() {
- return getFolderPathAdj()+getBaseFolderURL();
- } // getBaseFolderURL
-
- public static String getChartScriptsPath(String folderAdj1) {
- return folderAdj1+getBaseFolderURL();
- } // getBaseFolderURL
-
- public static String getFolderPathAdj() {
- return Globals.getAppUtils().getFolderPathAdj();
- } // getBaseFolderURL
-
-
- /*
- * public static String getReportExecuteActionURL() { return
- * Globals.getAppUtils().getReportExecuteActionURL(); } //
- * getReportExecuteActionURL
- *
- * public static String getDataViewActionURL() { return
- * Globals.getAppUtils().getDataViewActionURL(); } // getDataViewActionURL
- *
- * public static String getDataViewActionParam() { return
- * Globals.getAppUtils().getDataViewActionParam(); } //
- * getDataViewActionParam
- */
- public static String getDirectAccessURL() {
- return Globals.getAppUtils().getDirectAccessURL();
- } // getDirectAccessURL
-
- public static String getBaseURL() {
- if (baseURL == null) {
- baseURL = getBaseActionURL();
- if (baseURL.indexOf("?") > 0)
- baseURL = baseURL.substring(0, baseURL.indexOf("?"));
- } // if
-
- return baseURL;
- } // getBaseURL
-
- public static String getBaseActionURL() {
- return Globals.getAppUtils().getBaseActionURL();
- } // getBaseActionURL
-
- public static String getDrillActionURL() {
- return Globals.getAppUtils().getDrillActionURL();
- } // getBaseActionURL
-
- public static String getRaptorActionURL() {
- return Globals.getAppUtils().getBaseActionURL() + "raptor&" + AppConstants.RI_ACTION
- + "=";
- } // getRaptorActionURL
-
- public static String getRaptorActionURLNG() {
- return Globals.getAppUtils().getBaseActionURLNG();
- } // getRaptorActionURL
-
- public static String getReportExecuteActionURL() {
- return getRaptorActionURL() + "report.run.container&" + AppConstants.RI_REPORT_ID + "="; // getBaseActionParam();
- } // getReportExecuteActionURL
-
- public static String getReportExecuteActionURLNG() {
- return getRaptorActionURLNG() + "report_run/"; // getBaseActionParam();
- } // getReportExecuteActionURL
-
- public static String getBaseActionParam() {
- return Globals.getAppUtils().getBaseActionParam();
- } // getBaseActionParam
-
- public static Vector getQuickLinksMenuIDs() {
- return Globals.getAppUtils().getQuickLinksMenuIDs();
- } // getQuickLinksMenuIDs
-
- public static String getMenuLabel(String menuId) {
- return Globals.getAppUtils().getMenuLabel(menuId);
- } // getMenuLabel
-
- public static String getReportDbColsMaskSQL() {
- return Globals.getAppUtils().getReportDbColsMaskSQL();
- } // getReportDbColsMaskSQL
-
- public static String getReportDbLookupsSQL() {
- return Globals.getAppUtils().getReportDbLookupsSQL();
- } // getReportDbLookupsSQL
-
- public static void processErrorNotification(HttpServletRequest request, RaptorException e) {
- Globals.getAppUtils().processErrorNotification(request, e);
- } // processErrorNotification
-
- public static String getExcelTemplatePath() {
- String path = Globals.getAppUtils().getExcelTemplatePath();
- if (path.endsWith(File.separator)){
- return path;
- } else {
- path = path + File.separator;
- return path;
- }
- } // getTempFolderPath
-
- public static String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- public static boolean isNotEmpty(String s) {
- return nvl(s).length()>0;
- }
- public static String nvls(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
-} // AppUtils
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system;
-
-import java.sql.Connection;
-
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.error.ReportSQLException;
-import org.openecomp.portalsdk.analytics.util.AppConstants;
-import org.openecomp.portalsdk.analytics.util.DataSet;
-
-public class ConnectionUtils {
-
- public static DataSet getDataSet(String sql, String remoteDbPrefix)
- throws RaptorException {
- return getDataSet(sql, remoteDbPrefix, false);
- }
-
- public static Connection getConnection(String remoteDbPrefix) throws ReportSQLException {
- if (!isNull(remoteDbPrefix) && (!remoteDbPrefix.equals(AppConstants.DB_LOCAL)) && !Globals.getSystemType().equals(Globals.ST_GENERIC) ) {
- return RemDbUtils.getConnection(remoteDbPrefix);
- } else {
- return DbUtils.getConnection();
- }
- }
-
- public static DataSet getDataSet(String sql, String remoteDbPrefix,
- boolean pagesize) throws ReportSQLException {
- DataSet ds = null;
- if (!isNull(remoteDbPrefix) && (!remoteDbPrefix.equals(AppConstants.DB_LOCAL)) && !Globals.getSystemType().equals(Globals.ST_GENERIC) ) {
- if (pagesize == false)
- ds = RemDbUtils.executeQuery(sql,remoteDbPrefix);
- else
- ds = RemDbUtils.executeQuery(sql, Globals.getDefaultPageSize() + 1,remoteDbPrefix);
- } else {
- if (pagesize == false)
- ds = DbUtils.executeQuery(sql);
- else
- ds = DbUtils.executeQuery(sql, Globals.getDefaultPageSize() + 1);
- }
- return ds;
- }
-
- public static boolean isNull(String a) {
- if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null"))
- return true;
- else
- return false;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system;
-
-import java.sql.CallableStatement;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.sql.Types;
-
-import javax.sql.DataSource;
-
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.error.ReportSQLException;
-import org.openecomp.portalsdk.analytics.model.runtime.ReportRuntime;
-import org.openecomp.portalsdk.analytics.util.DataSet;
-import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-
-public class DbUtils /* implements IDbUtils */{
-
- static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DbUtils.class);
-
- private static DataSource dataSource;
-
- public DbUtils() {
- }
-
- public static Connection getConnection() throws ReportSQLException {
- try {
- return AppUtils.getDatasource().getConnection();
- } catch(SQLException ex) {
- ex.printStackTrace();
- }
- return null;
- } // getConnection
-
- public static void clearConnection(Connection con) throws ReportSQLException {
- try {
- if ((con != null) && !con.isClosed())
- Globals.getDbUtils().clearConnection(con);
- } catch (SQLException ex) {
- throw new ReportSQLException(ex.getMessage(), ex.getCause());
- } catch (Exception ex2 ) {
- throw new ReportSQLException (ex2.getMessage(), ex2.getCause());
- }
- } // clearConnection
-
- public static Connection startTransaction() throws ReportSQLException {
- Connection con = null;
- try {
- con = getConnection();
- con.setAutoCommit(false);
- } catch (SQLException ex) {
- throw new ReportSQLException (ex.getMessage(), ex.getCause());
- } catch (Exception ex2 ) {
- throw new ReportSQLException (ex2.getMessage(), ex2.getCause());
- }
- return con;
- } // startTransaction
-
- public static void commitTransaction(Connection con) throws ReportSQLException {
- try {
- con.commit();
- } catch (SQLException ex) {
- throw new ReportSQLException (ex.getMessage(), ex.getCause());
- } catch (Exception ex2 ) {
- throw new ReportSQLException (ex2.getMessage(), ex2.getCause());
- }
- } // commitTransaction
-
- public static void rollbackTransaction(Connection con) throws ReportSQLException {
- try {
- con.rollback();
- clearConnection(con);
- } catch (SQLException ex) {
- throw new ReportSQLException (ex.getMessage(), ex.getCause());
- } catch (Exception ex2 ) {
- throw new ReportSQLException (ex2.getMessage(), ex2.getCause());
- }
- } // rollbackTransaction
-
- public static String executeCall(Connection con, String sql, boolean expectResult)
- throws ReportSQLException {
- String result = null;
-
- try {
- if(con.isClosed()) con = getConnection();
- logger.debug(EELFLoggerDelegate.debugLogger, ("[SQL CALL FROM RAPTOR] [SQL Call] " + sql));
- CallableStatement stmt = con.prepareCall(sql);
- if (expectResult)
- stmt.registerOutParameter(1, Types.CHAR);
- stmt.executeUpdate();
- if (expectResult)
- result = stmt.getString(1);
- stmt.close();
- con.commit();
- } catch (SQLException e) {
- throw new ReportSQLException(e.getMessage(), sql);
- } finally {
- clearConnection(con);
- }
-
- return result;
- } // executeCall
-
- public static String executeCall(String sql, boolean expectResult)
- throws RaptorException {
- Connection con = null;
- con = getConnection();
- String result = executeCall(con, sql, expectResult);
- //con.commit();
- return result;
- } // executeCall
-
- public static int executeUpdate(Connection con, String sql) throws ReportSQLException {
- int rcode = -1;
- try {
- Statement stmt = con.createStatement();
- logger.debug(EELFLoggerDelegate.debugLogger, ("[SQL CALL FROM RAPTOR] [SQL Update] " + sql));
- rcode = stmt.executeUpdate(sql);
- stmt.close();
- //con.commit();
- } catch (SQLException e) {
- //e.printStackTrace();
- throw new ReportSQLException(e.getMessage(), sql);
- }
- return rcode;
- } // executeUpdate
-
- public static int executeUpdate(String sql) throws ReportSQLException {
- Connection con = null;
- try {
- con = getConnection();
- int rcode = executeUpdate(con, sql);
- if(Globals.getDBType().equals("oracle"))
- con.commit();
-
- return rcode;
- } catch (SQLException e) {
- throw new ReportSQLException(e.getMessage(), sql);
- } finally {
- clearConnection(con);
- }
- } // executeUpdate
-
- public static DataSet executeQuery(Connection con, String sql) throws ReportSQLException {
- return executeQuery(con, sql, Integer.MAX_VALUE);
- } // executeQuery
-
- public static DataSet executeQuery(Connection con, String sql, int maxRowLimit)
- throws ReportSQLException {
- try {
- if(con.isClosed()) con = getConnection();
- //con.
- Statement stmt = con.createStatement();
-
- logger.debug(EELFLoggerDelegate.debugLogger, ("[SQL CALL FROM RAPTOR] [SQL] " + sql));
- ResultSet rs = stmt.executeQuery(sql);
- DataSet ds = new DataSet(rs, maxRowLimit);
-
- if(rs!=null)
- rs.close();
- if(stmt!=null)
- stmt.close();
-
- return ds;
- } catch (SQLException e) {
- throw new ReportSQLException(e.getMessage(), sql);
- }
- } // executeQuery
-
- public static DataSet executeQuery(String sql) throws ReportSQLException {
- return executeQuery(sql, Integer.MAX_VALUE);
- } // executeQuery
-
- public static DataSet executeQuery(String sql, int maxRowLimit) throws ReportSQLException {
- Connection con = null;
- try {
- con = getConnection();
- return executeQuery(con, sql, maxRowLimit);
- }catch (ReportSQLException ex) {
- logger.error(EELFLoggerDelegate.debugLogger, ("Error " + sql));
- throw new ReportSQLException(ex.getMessage(), ex);
- }catch(Exception ex1) {
- throw new ReportSQLException(ex1.getMessage(), ex1.getCause());
- } finally {
- clearConnection(con);
- }
- } // executeQuery
-
- //For ZK Support
-
- public static int executeQuery(ReportRuntime rr, int dateOption) {
- Connection con = null;
- int rowCount = 0;
- try {
- con = ConnectionUtils.getConnection(rr.getDBInfo());
- String wholeSql = rr.getWholeSQL();
-
- DataColumnType dc = rr.getColumnWhichNeedEnhancedPagination();
- String date_ColId = dc.getColId();
- String dataFormat = dc.getColFormat();
- if(dataFormat!=null && dataFormat.length()>0)
- date_ColId = "to_date("+date_ColId+", '"+ dataFormat +"')";
- String sql = "";
- if(dateOption == 1)
- sql = "select count(distinct to_char("+date_ColId+", 'YYYY/MM')) from ("+wholeSql+")";
- else if (dateOption == 3)
- sql = "select count(distinct to_char("+date_ColId+", 'YYYY/MM/DD')) from ("+wholeSql+")";
- else if (dateOption == 2)
- sql = "select count(distinct to_char("+date_ColId+", 'YYYY')) from ("+wholeSql+")";
- DataSet ds = executeQuery(con, sql.toString());
- rowCount = ds.getInt(0,0);
- } catch (ReportSQLException ex) {
- ex.printStackTrace();
- }catch(Exception ex1) {
- ex1.printStackTrace();
- } finally {
- try {
- clearConnection(con);
- } catch (ReportSQLException ex2) {
- ex2.printStackTrace();
- }
- }
- return rowCount;
- }
-
- public String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- public static String nvls(String s) {
- return (s == null) ? "" : s;
- }
-
- public static String nvl(String s, String sDefault) {
- return nvls(s).equals("") ? sDefault : s;
- }
-
- public static DataSource getDataSource() {
- return dataSource;
- }
-
- @Autowired
- public void setDataSource(DataSource dataSource) {
- dataSource = dataSource;
- }
-
-} // DbUtils
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system;
-
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.concurrent.Callable;
-
-public class ExecuteQuery implements Callable<ResultSet>{
-
- private Statement stmt;
- private String sql = "";
- private int maxRowLimit;
- private ResultSet resultSet;
-
- public ResultSet getResultSet() {
- return resultSet;
- }
- public void setResultSet(ResultSet resultSet) {
- this.resultSet = resultSet;
- }
-
- public ExecuteQuery(Statement stmt, String sql, int maxRowLimit) {
- super();
- this.stmt = stmt;
- this.sql = sql;
- this.maxRowLimit = maxRowLimit;
- }
-
- public ResultSet call() throws SQLException {
- try {
- System.out.println("Query Started" + new java.util.Date());
- resultSet = stmt.executeQuery(sql);
- System.out.println("Query End" + new java.util.Date());
- } catch (SQLException ex) {
- System.out.println("Query Exception" + new java.util.Date());
- ex.printStackTrace();
- throw ex;
- }
- return resultSet;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I>
- * Raptor : This tool is used to generate different kinds of reports with lot of utilities
- * ===========================================================================================
- *
- * -------------------------------------------------------------------------------------------
- * Globals.java - This class is used to read properties file and call the common methods
- * existing among all the frameworks.
-
- * -------------------------------------------------------------------------------------------
- *
- *
- * Changes
- * -------
- * 31-Jul-2009 : Version 8.4 (Sundar); <UL><LI> getRequestparametersMap method iterates form field collections. </LI>
- * </UL>
- * 27-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Added property "admin_role_equiv_to_super_role" to specify Admin User equivalent to Super User.</LI>
- * </UL>
- * 14-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Added property to showing/hiding params displayed in dashboard reports.</LI>
- * </UL>
- *
- */
-package org.openecomp.portalsdk.analytics.system;
-
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.analytics.config.ConfigLoader;
-import org.openecomp.portalsdk.analytics.controller.ActionMapping;
-import org.openecomp.portalsdk.analytics.model.runtime.FormField;
-import org.openecomp.portalsdk.analytics.model.runtime.ReportFormFields;
-import org.openecomp.portalsdk.analytics.model.runtime.ReportRuntime;
-import org.openecomp.portalsdk.analytics.util.AppConstants;
-import org.openecomp.portalsdk.analytics.util.ExcelColorDef;
-import org.openecomp.portalsdk.analytics.util.Scheduler;
-import org.openecomp.portalsdk.analytics.util.Utils;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
-public class Globals extends org.openecomp.portalsdk.analytics.RaptorObject {
-
- static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Globals.class);
-
-
- private static boolean systemInitialized = false;
-
- private static ActionMapping raptorActionMapping = null;
-
- private static Scheduler scheduler = null;
-
- // System type constants
- public final static String ST_FUSION = "fusion";
-
- public final static String ST_GENERIC = "generic";
-
- public final static String ST_PRISMS = "prisms";
-
- private static String systemType = ST_PRISMS; // default
-
- private static IAppUtils appUtils = null;
-
- private static IDbUtils dbUtils = null;
-
- private static RDbUtils rdbUtils = null;
-
- private static int debugLevel = 5;
-
- private static int downloadLimit = 65000; // max number rows for download
- // csv file
-
- private static int defaultPageSize = 50;
-
- private static int formFieldsListSize = 50;
-
- private static int schedulerInterval = 0;
-
- private static String systemName = "MSA Databank";
-
- private static String baseTitle = "ANALYSIS";
-
- private static String sheet_name = "Raptor Reports";
-
- private static boolean allowSQLBasedReports = true; // whether to allow
- // SQL-based report
- // definition (security
- // risk); super users
- // are always allowed to
- // create SQL-based
- // reports
-
- private static boolean showDisclaimer = true; // whether to include
- // disclaimer page at the
- // bottom of each screen
-
- private static boolean displayFormBeforeRun = true; // whether to display
- // the form page as a
- // separate page before
- // running the report
-
- private static boolean includeFormWithData = true; // whether to include
- // the form page on the
- // report data page
-
- private static boolean cacheChartData = true; // whether to cache chart
- // data in the session =>
- // faster re-display if the
- // data volume does not get
- // too large
-
- private static boolean cacheCurPageData = true; // whether to cache report
- // data for the currently
- // displayed page in the
- // session => faster
- // re-display if the data
- // volume does not get too
- // large
-
- private static boolean deleteOnlyByOwner = true; // whether to permit
- // report deletion only
- // by report owner or by
- // everyone with "write"
- // access
-
- private static boolean enableReportLog = true; // whether to log each
- // report execution and
- // update time and user ID
-
- private static boolean cacheUserRoles = true; // whether to cache user
- // roles info in memory
- // (saves many DB reads, but
- // does not account for
- // roles assigned after the
- // cache was loaded)
-
- private static boolean monthFormatUseLastDay = true; // whether to
- // convert month
- // formats (e.g.
- // MM/YYYY) to the
- // last day of the
- // month (true) or
- // first day (false)
- // - like 12/2003 is
- // converted to
- // either 12/31/2003
- // or 12/01/2003
-
- private static boolean printTitleInDownload = false; // whether to print
- // the report title
- // in the download
- // files
-
- private static boolean showDescrAtRuntime = false; // whether to show
- // report description
- // when the report is
- // run and in the quick
- // links
-
- // private static boolean skipChartLabelsToFit = false; // whether to skip
- // labels on the Line chart axis when they overlap
- private static boolean showNonstandardCharts = false; // whether to show
- // chart types that
- // are purpose
- // and/or data
- // specific
-
- private static boolean allowRuntimeChartSel = true; // whether to allow the
- // user to change the
- // chart type at runtime
-
- private static boolean displayChartTitle = false; // whether to display
- // the report title as
- // chart title as well
-
- private static boolean mergeCrosstabRowHeadings = true; // whether to
- // merge/blank
- // multi-level row
- // headings in
- // cross-tab report
-
- private static boolean displayChartByDefault = true; // whether to
- // display chart
- // when displaying
- // the report at
- // first or just a
- // "Show Chart"
- // button
-
- private static boolean printParamsInDownload = false; // whether to print
- // the form field
- // values in the
- // download files
-
- // private static boolean chartLinesAlwaysSolid = true; // whether
- // multi-lines chart uses solid line for all series or dashed/dotted/etc for
- // each
- // private static boolean chartLinesAlwaysSmooth = true; // whether line
- // charts display smooth lines or with marked points on them for each value
- private static int maxDecimalsOnTotals = 2; // Maximum number of decimals
- // displayed in totals; decimal
- // digits beyond that number
- // will be truncated; if
- // negative => display all
- // decimal digits
-
- private static int defaultChartWidth = 700;
-
- private static int defaultChartHeight = 420;
-
- private static int skipChartLabelsLimit = 30;
-
- private static boolean canCopyOnReadOnly = true; // whether to users with
- // read-only rights for
- // a report can copy it
-
- // Currently not loaded from a property file
- private static boolean restrictTablesByRole = true; // whether to restrict
- // DB tables
- // accessibility by user
- // role; defaults to
- // false if table
- // CR_TABLE_ROLE is
- // empty, otherwise true
-
- private static String javaTimeFormat = "MM/dd/yyyy h:m:s a";
-
- private static String oracleTimeFormat = "%m/%d/%Y %h:%i:%s %p"; // must
- // correspond
- // to
- // the
- // java
- // format
- // modifier
-
- private static String raptorVersion = "10.5.1";
-
- private static int flatFileLowerLimit = 0;
-
- private static int flatFileUpperLimit = 0;
-
- private static String shellScriptDir = "";
-
- private static String queryFolder = "";
-
- private static String requestParams = "";
-
- private static String sessionParams = "";
-
- private static boolean displayAllUsers = true;
-
- private static boolean user_col_def = true;
-
- private static boolean printFooterInDownload = true;
-
- private static String footerFirstLine = "";
-
- private static String footerSecondLine = "";
-
- private static boolean reportsInPoPUpWindow = false;
-
- private static boolean poPUpInNewWindow = false;
-
- private static boolean passRequestParamInDrilldown = false;
-
- private static Properties raptorPdfProperties;
-
- private static Properties raptorProperties;
-
- private static Properties sqlProperty;
-
- private static boolean showPDFDownloadIcon = false;
-
-
-
- private Globals() {
- }
-
- public static synchronized void initializeSystem(ServletContext servletContext) {
- if (systemInitialized)
- return;
- AppConstants.initializeAppConstants();
- ExcelColorDef.initializeExcelColorDef();
-
- //DB Agnostic Addition
- try{
- Properties sqlProperty = ConfigLoader.getProperties(servletContext, ConfigLoader.SQL_PROPERTIES);
- Globals.sqlProperty = sqlProperty;
- }
-
- catch (IOException e) {
- e.printStackTrace();
- }
-
- try {
- Properties raptorProperties = ConfigLoader.getProperties(servletContext,
- ConfigLoader.RAPTOR_PROPERTIES);
- initializeRaptorProperties(raptorProperties);
-
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] Globals: Unable to load properties ["
- + ConfigLoader.RAPTOR_PROPERTIES + "]. Exception: " + e.getMessage()));
- // throw new RuntimeException(e.getMessage());
- }
-
- systemInitialized = true;
-
- try {
- appUtils = (IAppUtils) Class.forName(
- "org.openecomp.portalsdk.analytics.system." + systemType.toLowerCase() + ".AppUtils")
- .newInstance();
- appUtils.initializeAppUtils(servletContext);
-
- dbUtils = (IDbUtils) Class.forName(
- "org.openecomp.portalsdk.analytics.system." + systemType.toLowerCase() + ".DbUtils")
- .newInstance();
- dbUtils.initializeDbUtils(servletContext);
-
- if(!Globals.getSystemType().equals(Globals.ST_GENERIC)) {
- rdbUtils = (RDbUtils) Class.forName(
- "org.openecomp.portalsdk.analytics.system." + systemType.toLowerCase() + ".RemoteDbUtils")
- .newInstance();
- rdbUtils.initializeDbUtils(servletContext);
- }
- } catch (Exception e) {
- String eMsg = "[SYSTEM ERROR] Globals: Unable to instantiate system classes. Exception: "
- + e.getMessage();
- logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] " + eMsg));
- systemInitialized = false;
- throw new RuntimeException(eMsg);
- }
-
- try {
- raptorActionMapping = ConfigLoader.loadRaptorActionMapping(servletContext);
- } catch (Exception e) {
- String eMsg = "[SYSTEM ERROR] Globals: Unable to load Raptor action mapping. Exception: "
- + e.getMessage();
- logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] " + eMsg));
- systemInitialized = false;
- throw new RuntimeException(eMsg);
- } // catch
-
- /*try {
- //DataSet ds = DbUtils
- // .executeQuery("SELECT 1 FROM dual WHERE EXISTS (SELECT 1 FROM cr_table_role)");
-
- String p_sql = Globals.getInitializeRoles();
- DataSet ds = DbUtils.executeQuery(p_sql);
-
- restrictTablesByRole = (ds.getRowCount() > 0);
- } catch (Exception e) {
- String eMsg = "[SYSTEM ERROR] Globals: Unable to load Raptor version. Exception: "
- + e.getMessage();
- debugLogger.error("[EXCEPTION ENCOUNTERED IN RAPTOR] " + eMsg, e);
- } // catch
- */
- /*try {
- //DataSet ds = DbUtils.executeQuery("SELECT cr_raptor.get_version FROM dual");
-
- //String n_sql = Globals.getInitializeVersion();
- //DataSet ds = DbUtils.executeQuery(n_sql);
- //raptorVersion = Globals.get
- // if(ds.getRowCount()>0)
- // raptorVersion = " v"+ds.getString(0, 0);
- } catch (Exception e) {
- String eMsg = "[SYSTEM ERROR] Globals: Unable to load Raptor version. Exception: "
- + e.getMessage();
- debugLogger.error("[EXCEPTION ENCOUNTERED IN RAPTOR] " + eMsg, e);
- } // catch*/
-
-
- //initiate pdf global config
- try {
- raptorPdfProperties = ConfigLoader.getProperties(servletContext, ConfigLoader.RAPTOR_PDF_PROPERTIES);
- }
- catch (Exception e) {
- logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] Globals: Unable to load properties ["
- + ConfigLoader.RAPTOR_PDF_PROPERTIES + "]. Exception: " + e.getMessage()));
-
- }
-
- scheduler = new Scheduler(schedulerInterval);
-
- } // initializeSystem
-
- public static void initializeRaptorProperties(Properties raptorProperties) {
- Globals.raptorProperties = raptorProperties;
- systemType = raptorProperties.getProperty("system");
-
- try {
- debugLevel = Integer.parseInt(nvls(raptorProperties
- .getProperty("debug_level")).trim());
- } catch (NumberFormatException nfe) {
- }
-
- try {
- downloadLimit = Integer.parseInt(nvls(raptorProperties
- .getProperty("download_limit")).trim());
- } catch (NumberFormatException nfe) {
- }
-
- try {
- defaultPageSize = Integer.parseInt(nvls(raptorProperties
- .getProperty("default_page_size")).trim());
- } catch (NumberFormatException nfe) {
- }
-
- try {
- formFieldsListSize = Integer.parseInt(nvls(raptorProperties
- .getProperty("form_fields_list_size")).trim());
- } catch (NumberFormatException nfe) {
- }
-
- try {
- schedulerInterval = Integer.parseInt(nvls(raptorProperties
- .getProperty("scheduler_interval")).trim());
- } catch (NumberFormatException nfe) {
- System.out.println("NUMBERFORMATEXCEPTION Schedular " + raptorProperties
- .getProperty("scheduler_interval"));
- schedulerInterval = 0;
- }
-
- try {
- maxDecimalsOnTotals = Integer.parseInt(nvls(raptorProperties
- .getProperty("max_decimals_on_totals")).trim());
- } catch (NumberFormatException nfe) {
- }
-
- try {
- defaultChartWidth = Integer.parseInt(nvls(raptorProperties
- .getProperty("default_chart_width")).trim());
- } catch (NumberFormatException nfe) {
- }
-
- try {
- defaultChartHeight = Integer.parseInt(nvls(raptorProperties
- .getProperty("default_chart_height")).trim());
- } catch (NumberFormatException nfe) {
- }
-
- try {
- skipChartLabelsLimit = Integer.parseInt(nvls(raptorProperties
- .getProperty("skip_chart_labels_limit")).trim());
- } catch (NumberFormatException nfe) {
- }
-
- systemName = nvls(raptorProperties.getProperty("system_name"), "MSA Databank");
- baseTitle = nvls(raptorProperties.getProperty("base_title"), "ANALYSIS");
-
- allowSQLBasedReports = nvls(
- raptorProperties.getProperty("allow_sql_based_reports"), "yes")
- .toUpperCase().startsWith("Y");
- showDisclaimer = nvls(raptorProperties.getProperty("show_disclaimer"), "yes")
- .toUpperCase().startsWith("Y");
- displayFormBeforeRun = nvls(
- raptorProperties.getProperty("display_form_before_run"), "yes")
- .toUpperCase().startsWith("Y");
- includeFormWithData = nvls(raptorProperties.getProperty("include_form_with_data"),
- "yes").toUpperCase().startsWith("Y");
- cacheChartData = nvls(raptorProperties.getProperty("cache_chart_data"), "yes")
- .toUpperCase().startsWith("Y");
- cacheCurPageData = nvls(raptorProperties.getProperty("cache_cur_page_data"), "yes")
- .toUpperCase().startsWith("Y");
- deleteOnlyByOwner = nvls(raptorProperties.getProperty("delete_only_by_owner"),
- "yes").toUpperCase().startsWith("Y");
- enableReportLog = nvls(raptorProperties.getProperty("enable_report_log"), "yes")
- .toUpperCase().startsWith("Y");
- cacheUserRoles = nvls(raptorProperties.getProperty("cache_user_roles"), "yes")
- .toUpperCase().startsWith("Y");
- monthFormatUseLastDay = nvls(
- raptorProperties.getProperty("month_format_use_last_day"), "yes")
- .toUpperCase().startsWith("Y");
- printTitleInDownload = nvls(
- raptorProperties.getProperty("print_title_in_download"), "no")
- .toUpperCase().startsWith("Y");
- showDescrAtRuntime = nvls(raptorProperties.getProperty("show_descr_at_runtime"),
- "no").toUpperCase().startsWith("Y");
- // skipChartLabelsToFit =
- // nvls(raptorProperties.getProperty("skip_chart_labels_to_fit"),
- // "no" ).toUpperCase().startsWith("Y");
- showNonstandardCharts = nvls(
- raptorProperties.getProperty("show_nonstandard_charts"), "no")
- .toUpperCase().startsWith("Y");
- allowRuntimeChartSel = nvls(
- raptorProperties.getProperty("allow_runtime_chart_sel"), "yes")
- .toUpperCase().startsWith("Y");
- displayChartTitle = nvls(raptorProperties.getProperty("display_chart_title"), "no")
- .toUpperCase().startsWith("Y");
- mergeCrosstabRowHeadings = nvls(
- raptorProperties.getProperty("merge_crosstab_row_headings"), "yes")
- .toUpperCase().startsWith("Y");
- displayChartByDefault = nvls(
- raptorProperties.getProperty("display_chart_by_default"), "yes")
- .toUpperCase().startsWith("Y");
- //System.out.println("Params Globals " + raptorProperties.getProperty("print_params_in_download"));
-
- printParamsInDownload = nvls(
- raptorProperties.getProperty("print_params_in_download"), "no")
- .toUpperCase().startsWith("Y");
- //System.out.println("printParamsInDownload " + printParamsInDownload);
-
- canCopyOnReadOnly = nvls(raptorProperties.getProperty("can_copy_on_read_only"),
- "yes").toUpperCase().startsWith("Y");
- // chartLinesAlwaysSolid =
- // nvls(raptorProperties.getProperty("chart_lines_always_solid"),
- // "yes").toUpperCase().startsWith("Y");
- // chartLinesAlwaysSmooth =
- // nvls(raptorProperties.getProperty("chart_lines_always_smooth"),
- // "yes").toUpperCase().startsWith("Y");
- displayAllUsers = nvls(
- raptorProperties.getProperty("display_all_users"), "yes")
- .toUpperCase().startsWith("Y");
- requestParams = nvls(
- raptorProperties.getProperty("request_get_params"), "");
- sessionParams = nvls(
- raptorProperties.getProperty("session_params"), "");
- user_col_def = nvls(
- raptorProperties.getProperty("user_col_def"), "no")
- .toUpperCase().startsWith("Y");
- sheet_name = nvls(raptorProperties.getProperty("sheet_name"), "Raptor Reports");
- try {
- flatFileLowerLimit = Integer.parseInt(raptorProperties
- .getProperty("flat_file_lower_limit"));
- } catch (NumberFormatException nfe) {
- }
- try {
- flatFileUpperLimit = Integer.parseInt(raptorProperties
- .getProperty("flat_file_upper_limit"));
- } catch (NumberFormatException nfe) {
- }
- shellScriptDir = nvls(raptorProperties.getProperty("shell_script_dir"), "");
- //queryFolder = nvls(raptorProperties.getProperty("download_query_folder"), AppUtils.getTempFolderPath()+"../raptor/dwnld/query/");
- queryFolder = nvls(raptorProperties.getProperty("download_query_folder"),"../raptor/dwnld/query/");
-
-
- printFooterInDownload = nvls(
- raptorProperties.getProperty("print_footer_in_download"), "no")
- .toUpperCase().startsWith("Y");
- footerFirstLine = nvls(raptorProperties.getProperty("footer_first_line"), "AT&T Proprietary");
- footerSecondLine = nvls(raptorProperties.getProperty("footer_second_line"), "Use Pursuant to Company Instructions");
- reportsInPoPUpWindow = nvls(
- raptorProperties.getProperty("report_in_popup_window"), "no")
- .toUpperCase().startsWith("Y");
- poPUpInNewWindow = nvls(
- raptorProperties.getProperty("popup_in_new_window"), "no")
- .toUpperCase().startsWith("Y") && reportsInPoPUpWindow;
-
- passRequestParamInDrilldown = nvls(
- raptorProperties.getProperty("pass_request_param_in_drilldown"), "yes")
- .toUpperCase().startsWith("Y");
- showPDFDownloadIcon = nvls(
- raptorProperties.getProperty("show_pdf_download"), "no")
- .toUpperCase().startsWith("Y");
- }
-
- /** *********************************************************************** */
-
- public static ActionMapping getRaptorActionMapping() {
- if (!systemInitialized)
- throw new RuntimeException("[SYSTEM ERROR] Globals not initialized");
-
- return raptorActionMapping;
- } // getRaptorActionMapping
-
- public static String getSystemType() {
- if (!systemInitialized)
- throw new RuntimeException("[SYSTEM ERROR] Globals not initialized");
-
- return systemType;
- } // getSystemType
-
- public static IAppUtils getAppUtils() {
- if (!systemInitialized)
- throw new RuntimeException("[SYSTEM ERROR] Globals not initialized");
-
- return appUtils;
- } // getAppUtils
-
- public static IDbUtils getDbUtils() {
- if (!systemInitialized)
- throw new RuntimeException("[SYSTEM ERROR] Globals not initialized");
-
- return dbUtils;
- } // getDbUtils
-
- public static RDbUtils getRDbUtils() {
- if (!systemInitialized)
- throw new RuntimeException("[SYSTEM ERROR] Globals not initialized");
- return rdbUtils;
- } // getDbUtils
-
- /** *********************************************************************** */
-
- public static int getDebugLevel() {
- return debugLevel;
- }
-
- public static int getDownloadLimit() {
- return downloadLimit;
- }
-
- public static int getCSVDownloadLimit() {
- return Integer.parseInt(nvls(raptorProperties.getProperty("csv_download_limit"), new Integer(getDownloadLimit()).toString()).trim());
- }
-
- public static String getDownloadLimitAsText() {
- return java.text.NumberFormat.getNumberInstance(java.util.Locale.US).format(
- downloadLimit);
- }
-
- public static int getDefaultPageSize() {
- return defaultPageSize;
- }
-
- public static int getFormFieldsListSize() {
- return formFieldsListSize;
- }
-
- public static int getSchedulerInterval() {
- return schedulerInterval;
- }
-
- public static String getBaseTitle() {
- return baseTitle;
- }
-
- public static String getSystemName() {
- return systemName;
- }
-
- public static boolean getAllowSQLBasedReports() {
- return allowSQLBasedReports;
- }
-
- public static boolean getShowDisclaimer() {
- return showDisclaimer;
- }
-
- public static boolean getDisplayFormBeforeRun() {
- return displayFormBeforeRun;
- }
-
- public static boolean getIncludeFormWithData() {
- return includeFormWithData;
- }
-
- public static boolean getCacheChartData() {
- return cacheChartData;
- }
-
- public static boolean getCacheCurPageData() {
- return cacheCurPageData;
- }
-
- public static boolean getDeleteOnlyByOwner() {
- return deleteOnlyByOwner;
- }
-
- public static boolean getEnableReportLog() {
- return enableReportLog;
- }
-
- public static boolean getCacheUserRoles() {
- return cacheUserRoles;
- }
-
- public static boolean getMonthFormatUseLastDay() {
- return monthFormatUseLastDay;
- }
-
- public static boolean getPrintTitleInDownload() {
- return printTitleInDownload;
- }
-
- public static boolean getShowDescrAtRuntime() {
- return showDescrAtRuntime;
- }
-
- // public static boolean getSkipChartLabelsToFit() { return
- // skipChartLabelsToFit; }
- public static boolean getShowNonstandardCharts() {
- return showNonstandardCharts;
- }
-
- public static boolean getAllowRuntimeChartSel() {
- return allowRuntimeChartSel;
- }
-
- public static boolean getDisplayChartTitle() {
- return displayChartTitle;
- }
-
- public static boolean getMergeCrosstabRowHeadings() {
- return mergeCrosstabRowHeadings;
- }
-
- public static boolean getDisplayChartByDefault() {
- return displayChartByDefault;
- }
-
- public static boolean getPrintParamsInDownload() {
- return printParamsInDownload;
- }
-
- public static boolean getCanCopyOnReadOnly() {
- return canCopyOnReadOnly;
- }
-
- // public static boolean getChartLinesAlwaysSolid() { return
- // chartLinesAlwaysSolid; }
- // public static boolean getChartLinesAlwaysSmooth() { return
- // chartLinesAlwaysSmooth; }
- public static int getMaxDecimalsOnTotals() {
- return maxDecimalsOnTotals;
- }
-
- public static int getDefaultChartWidth() {
- return defaultChartWidth;
- }
-
- public static int getDefaultChartHeight() {
- return defaultChartHeight;
- }
-
- public static int getSkipChartLabelsLimit() {
- return skipChartLabelsLimit;
- }
-
- public static boolean getRestrictTablesByRole() {
- return restrictTablesByRole;
- }
-
- public static String getJavaTimeFormat() {
- return javaTimeFormat;
- }
-
-/* public static String getOracleTimeFormat() {
- return oracleTimeFormat;
- }
-*/
-
- public static String getRaptorVersion() {
- return raptorVersion;
- }
-
- public static boolean getDisplayAllUsers() {
- return displayAllUsers;
- }
-
- public static boolean getUserColDef() {
- return user_col_def;
- }
-
- public static String getSheetName() {
- return sheet_name;
- }
-
- public static int getFlatFileLowerLimit() {
- return flatFileLowerLimit;
- }
-
- public static int getFlatFileUpperLimit() {
- return flatFileUpperLimit;
- }
-
-
- public static String getShellScriptDir() {
- return shellScriptDir;
- }
-
- public static String getQueryFolder() {
- return AppUtils.getTempFolderPath()+queryFolder;
- }
-
- public static String getRequestParams() {
- return requestParams;
- }
-
- public static String getSessionParams() {
- return sessionParams;
- }
-
- public static boolean getPrintFooterInDownload() {
- return printFooterInDownload;
- }
-
- public static String getFooterFirstLine() {
- return footerFirstLine;
- }
-
- public static String getFooterSecondLine() {
- return footerSecondLine;
- }
-
- public static boolean getReportsInPoPUpWindow() {
- return reportsInPoPUpWindow;
- }
-
- public static boolean getPoPUpInNewWindow() {
- return poPUpInNewWindow;
- }
-
- public static boolean getPassRequestParamInDrilldown() {
- return passRequestParamInDrilldown;
- }
-
-
- //pdf specific properties
- public static float getDataFontSize() {
- float size = 10f;
-
- try {
- size = Float.parseFloat(nvls(raptorPdfProperties.getProperty("pdf_data_font_size")).trim());
- } catch (Exception ex) {
-
- }
- return size;
- }
-
- public static float getDataFontSizeOffset() {
- float size = 9f;
-
- try {
- size = Float.parseFloat(nvls(raptorPdfProperties.getProperty("pdf_data_font_size_offset")).trim());
- } catch (Exception ex) {
-
- }
- return size;
- }
-
- public static float getFooterFontSize() {
- float size = 9f;
-
- try {
- size = Float.parseFloat(nvls(raptorPdfProperties.getProperty("pdf_footer_font_size")).trim());
- } catch (Exception ex) {
-
- }
- return size;
- }
-
- public static int getPageNumberPosition() {
- int size = 1;
-
- try {
- size = Integer.parseInt(nvls(raptorPdfProperties.getProperty("pdf_page_number_position")).trim());
- } catch (Exception ex) {
-
- }
- return size;
- }
-
- public static String getDataFontFamily() {
-
- return nvls(raptorPdfProperties.getProperty("pdf_data_font_family"),"Arial").trim();
- }
-
- public static String getFooterFontFamily() {
-
- return nvls(raptorPdfProperties.getProperty("pdf_footer_font_family"),"Arial").trim();
- }
-
- public static boolean isCoverPageNeeded() {
-
- return nvls(raptorPdfProperties.getProperty("display_cover_page"),"true").trim().equalsIgnoreCase("true");
- }
-
- public static boolean isDataAlternateColor() {
-
- return nvls(raptorPdfProperties.getProperty("pdf_data_alternate_color"),"true").trim().equalsIgnoreCase("true");
- }
-
- public static String getPDFFooter() {
-
- return nvls(raptorPdfProperties.getProperty("pdf_footer"));
- }
-
- public static boolean isCreatedOwnerInfoNeeded() {
- return nvls(raptorPdfProperties.getProperty("display_create_owner_info"),"true").trim().equalsIgnoreCase("true");
- }
-
- // Selected Form field section in the run page
- public static boolean displayFormFieldInfo() {
- return nvls(raptorProperties.getProperty("display_formfield_info"),"no").trim().toUpperCase().startsWith("Y");
- }
-
- // Customize Form field section in the run page
- public static boolean customizeFormFieldInfo() {
- return nvls(raptorProperties.getProperty("customize_formfield_info"),"no").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean displayLoginIdForDownloadedBy() {
- return nvls(raptorPdfProperties.getProperty("display_loginid_for_downloaded_by"),"false").trim().equalsIgnoreCase("true");
- }
-
- public static boolean isDefaultOrientationPortrait() {
- return nvls(raptorPdfProperties.getProperty("is_default_orientation_portrait"),"true").trim().equalsIgnoreCase("true");
- }
-
- public static String getSessionInfoForTheCoverPage() {
- return nvls(raptorPdfProperties.getProperty("session_info"));
- }
-
- public static String getDatePattern() {
-
- return nvls(raptorPdfProperties.getProperty("pdf_date_pattern"),"MM/dd/yyyy hh:mm:ss a");
- }
-
- public static String getTimeZone() {
-
- return nvls(raptorPdfProperties.getProperty("pdf_date_timezone"),"EST");
- }
-
- public static String getWordBeforePageNumber() {
-
- return nvls(raptorPdfProperties.getProperty("pdf_word_before_page_number"));
- }
-
- public static String getWordAfterPageNumber() {
-
- return nvls(raptorPdfProperties.getProperty("pdf_word_after_page_number"));
- }
-
- public static float getPDFFooterFontSize() {
- float size = 7f;
-
- try {
- size = Float.parseFloat(nvls(raptorPdfProperties.getProperty("pdf_footer_font_size")).trim());
- } catch (Exception ex) {
-
- }
- return size;
- }
-
- public static String getDataBackgroundAlternateHexCode() {
-
- return nvls(raptorPdfProperties.getProperty("pdf_data_background_alternate_hex_code"),"#FFFFFF");
- }
-
- public static String getDataDefaultBackgroundHexCode() {
-
- return nvls(raptorPdfProperties.getProperty("pdf_data_default_background_hex_code"),"#FFFFFF");
- }
-
- public static String getDataTableHeaderFontColor() {
-
- return nvls(raptorPdfProperties.getProperty("pdf_data_table_header_font_hex_code"),"#FFFFFF");
- }
-
- public static String getDataTableHeaderBackgroundFontColor() {
-
- return nvls(raptorPdfProperties.getProperty("pdf_data_table_header_background_hex_code"),"#8A9BB3");
- }
-
- public static boolean isFolderTreeAllowed() {
- return nvls(raptorProperties.getProperty("show_folder_tree"),"yes").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean isFolderDefaultMinimized() {
- return nvls(raptorProperties.getProperty("folder_tree_minimized"),"no").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean isFolderTreeAllowedOnlyForAdminUsers() {
- return nvls(raptorProperties.getProperty("show_folder_tree_only_to_admin_users"),"yes").trim().toUpperCase().startsWith("Y");
- }
-
- public static float getCoverPageFirstColumnSize() {
- float size = 0.3f;
-
- try {
- size = Float.parseFloat(nvls(raptorPdfProperties.getProperty("pdf_coverpage_firstcolumn_size")).trim());
- } catch (Exception ex) {
-
- }
- return size;
- }
-
- public static boolean isImageAutoRotate() {
- return nvls(raptorPdfProperties.getProperty("pdf_image_auto_rotate"),"false").trim().equalsIgnoreCase("true");
- }
-
-
- public static boolean isShowPDFDownloadIcon() {
- return showPDFDownloadIcon;
- }
-
-
- public static void setShowPDFDownloadIcon(boolean showPDFDownloadIcon) {
- Globals.showPDFDownloadIcon = showPDFDownloadIcon;
- }
-
- public static int getScheduleLimit() {
- int limit = 1000;
- try {
- limit = Integer.parseInt(nvls(raptorProperties.getProperty("schedule_limit")).trim());
- } catch (Exception ex) {
-
- }
- return limit;
- }
-
-// public static String getWhereConditionForUserRole() {
-// return nvls(raptorProperties.getProperty("schedule_where_condition"),"").trim();
-// }
- public static String getCustomizedScheduleQueryForUsers() {
- return nvls(raptorProperties.getProperty("schedule_custom_query_for_users"),"").trim();
- }
-
- public static String getTimeFormat() {
- return nvls(raptorProperties.getProperty("time_format"),"%m/%d/%Y %h:%i:%s %p").trim();
- }
-
- public static String getCustomizedScheduleQueryForRoles() {
- return nvls(raptorProperties.getProperty("schedule_custom_query_for_roles"),"").trim();
- }
-
- public static String getScheduleDatePattern() {
- return nvls(raptorProperties.getProperty("schedule_date_pattern"),"MM/dd/yyyy hh:mm:ss a");
- }
-
- public static String getChartYearlyPattern() {
- return nvls(raptorProperties.getProperty("chart_yearly_format"),"yyyy");
- }
-
- public static String getChartMonthlyPattern() {
- return nvls(raptorProperties.getProperty("chart_monthly_format"),"MMM-yyyy");
- }
-
- public static String getChartDailyPattern() {
- return nvls(raptorProperties.getProperty("chart_daily_format"),"MM-dd-yyyy");
- }
-
- public static String getChartWeeklyPattern() {
- return nvls(raptorProperties.getProperty("chart_weekly_format"),"MM-dd-yyyy");
- }
-
- public static String getChartHourlyPattern() {
- return nvls(raptorProperties.getProperty("chart_hourly_format"),"HH");
- }
-
- public static String getChartMinutePattern() {
- return nvls(raptorProperties.getProperty("chart_minute_format"),"HH:mm");
- }
-
- public static String getChartSecPattern() {
- return nvls(raptorProperties.getProperty("chart_second_format"),"HH:mm:ss");
- }
-
- public static String getChartMilliSecPattern() {
- return nvls(raptorProperties.getProperty("chart_millisecond_format"),"HH:mm:ss.S");
- }
-
- public static String getSessionParamsForScheduling() {
- return nvls(raptorProperties.getProperty("session_params_for_scheduling"),"");
- }
-
- public static String getDisplaySessionParamInPDFEXCEL() {
- return nvls(raptorProperties.getProperty("display_session_param_pdfexcel"),"");
- }
-
- public static String getDisplayScheduleSessionParamInPDFEXCEL() {
- return nvls(raptorProperties.getProperty("session_params_for_displaying_in_scheduling"),"");
- }
-
- public static boolean isScheduleDateParamAutoIncr() {
- return nvls(raptorProperties.getProperty("session_date_formfield_auto_incr"),"yes").trim().toUpperCase().startsWith("Y");
- }
-
- public static int getMaxCellWidthInExcel() {
- int cellWidth = 40;
- try {
- cellWidth = Integer.parseInt(nvls(raptorProperties.getProperty("max_cell_width_in_excel")).trim());
- } catch (Exception ex) {
-
- }
- return cellWidth;
- }
-
- public static synchronized int getFormFieldsCount(HttpServletRequest request)
- {
- if(request.getSession().getAttribute(
- AppConstants.SI_REPORT_RUNTIME) == null )
- {
- return 0;
- }
-
- ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(
- AppConstants.SI_REPORT_RUNTIME);
-
- 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++;
- }
- return countOfFields;
-
- }
-
- public static synchronized java.util.HashMap getRequestParametersMap(HttpServletRequest request, HashMap paramsMap) {
- HashMap valuesMap = new HashMap();
- if(paramsMap.size() <= 0) {
- return valuesMap;
- }
-
- ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(
- AppConstants.SI_REPORT_RUNTIME);
- if(rr.getReportType().equals(AppConstants.RT_DASHBOARD)) {
- rr = (ReportRuntime) request.getSession().getAttribute("FirstDashReport");
- }
- 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();
-
- if(paramsMap.containsKey(formField) ) {
- String vals = (String) paramsMap.get(formField);
- StringBuffer value = new StringBuffer("");
- 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(isMultiValue) {
- value.append("(");
- }
- StringTokenizer st = new StringTokenizer(vals, "|");
- if(st.countTokens()>0) {
- while(st.hasMoreTokens()) {
- if(isMultiValue) value.append("'");
- String token = st.nextToken();
- try {
- if(token !=null && token.length() > 0)
- token = java.net.URLDecoder.decode(token, "UTF-8");
- } catch (UnsupportedEncodingException ex) {}
- catch (IllegalArgumentException ex1){}
- catch (Exception ex2){}
- value.append(token);
- if(isMultiValue) value.append("'");
- if(st.hasMoreTokens()) {
- value.append(",");
- }
- }
- } else {
- String valueStr = "";
- valueStr = request.getParameter(formField);
- valueStr = Utils.oracleSafe(valueStr);
- valueStr = "('" + Utils.replaceInString(valueStr, ",", "'|'") + "')";
- valueStr = Utils.replaceInString(valueStr, "|", ",");
- valuesMap.put(fieldNameMap.get(formField), valueStr);
- valueStr = "";
- }
- if(isMultiValue) value.append(")");
-
- valuesMap.put(fieldNameMap.get(formField), value.toString());
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
- String valueStr = "";
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) {
- valueStr = (String) paramsMap.get(formField +"_Hr");
- valuesMap.put(formField+"_Hr", valueStr);
- valueStr = "";
- } else if (ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) {
- valueStr =(String) paramsMap.get(formField +"_Hr");
- valuesMap.put(formField+"_Hr", valueStr);
- valueStr = "";
- valueStr = (String) paramsMap.get(formField +"_Min");
- valuesMap.put(formField+"_Min", valueStr);
- valueStr = "";
- } else if (ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
- valueStr = (String) paramsMap.get(formField +"_Hr");
- valuesMap.put(formField+"_Hr", valueStr);
- valueStr = "";
- valueStr =(String) paramsMap.get(formField +"_Min");
- valuesMap.put(formField+"_Min", valueStr);
- valueStr = "";
- valueStr = (String) paramsMap.get(formField +"_Sec");
- valuesMap.put(formField+"_Sec", valueStr);
- valueStr = "";
- }
- }
-
- value = new StringBuffer("");
-
- } else if (paramsMap.containsKey(formField +"_auto")) {
- String vals = (String) paramsMap.get(formField +"_auto");
- StringBuffer value = new StringBuffer("");
- 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(isMultiValue) {
- value.append("(");
- }
- StringTokenizer st = new StringTokenizer(vals, "|");
- if(st.countTokens()>0) {
- while(st.hasMoreTokens()) {
- if(isMultiValue) value.append("'");
- String token = st.nextToken();
- try {
- if(token !=null && token.length() > 0)
- token = java.net.URLDecoder.decode(Utils.oracleSafe(token), "UTF-8");
- } catch (UnsupportedEncodingException ex) {}
- catch (IllegalArgumentException ex1){}
- catch (Exception ex2){}
- value.append(token);
- if(isMultiValue) value.append("'");
- if(st.hasMoreTokens()) {
- value.append(",");
- }
- }
- } else {
- String valueStr = "";
- valueStr = request.getParameter(formField +"_auto");
- valueStr = "('" + Utils.replaceInString(valueStr, ",", "'|'") + "')";
- valueStr = Utils.replaceInString(valueStr, "|", ",");
- valuesMap.put(fieldNameMap.get(formField), valueStr);
- valueStr = "";
- }
- if(isMultiValue) value.append(")");
-
- valuesMap.put(fieldNameMap.get(formField), value.toString());
-
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) || ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
- String valueStr = "";
- if(ff.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) {
- valueStr = (String) paramsMap.get(formField +"_Hr");
- valuesMap.put(formField+"_Hr", valueStr);
- valueStr = "";
- } else if (ff.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) {
- valueStr = (String) paramsMap.get(formField +"_Hr");
- valuesMap.put(formField+"_Hr", valueStr);
- valueStr = "";
- valueStr = (String) paramsMap.get(formField +"_Min");
- valuesMap.put(formField+"_Min", valueStr);
- valueStr = "";
- } else if (ff.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
- valueStr = (String) paramsMap.get(formField +"_Hr");
- valuesMap.put(formField+"_Hr", valueStr);
- valueStr = "";
- valueStr = (String) paramsMap.get(formField +"_Min");
- valuesMap.put(formField+"_Min", valueStr);
- valueStr = "";
- valueStr = (String) paramsMap.get(formField +"_Sec");
- valuesMap.put(formField+"_Sec", valueStr);
- valueStr = "";
- }
- }
- value = new StringBuffer("");
-
-
- } else
- valuesMap.put(fieldNameMap.get(formField), "" );
- }
- return valuesMap;
- }
-
- public static synchronized java.util.HashMap getRequestParamtersMap(HttpServletRequest request) {
- return getRequestParamtersMap(request, false);
- }
-
- public static synchronized java.util.HashMap getRequestParamtersMap(HttpServletRequest request, boolean isFromChild)
- {
- HashMap valuesMap = new HashMap();
- ReportRuntime rr = null;
- if(request.getSession().getAttribute(
- AppConstants.SI_REPORT_RUNTIME) == null )
- {
- rr = (ReportRuntime) request.getSession().getAttribute("FirstDashReport");
- if(rr==null)
- return valuesMap;
- }
-
- rr = (ReportRuntime) request.getSession().getAttribute(
- AppConstants.SI_REPORT_RUNTIME);
- if(rr!=null && rr.getReportType().equals(AppConstants.RT_DASHBOARD)) {
- rr = (ReportRuntime) request.getSession().getAttribute("FirstDashReport");
- }
-
- 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++;
- }
- if(isFromChild) {
- Hashtable ht = rr.getReportParamValues();
- Set set = ht.entrySet();
- HashMap hashMap = new HashMap();
- Iterator itr = set.iterator();
- while(itr.hasNext()){
- Map.Entry entry = (Map.Entry)itr.next();
- Object key = entry.getKey();
- Object val = entry.getValue();
- if(key==null){
- key = ""; // Or whatever you want
- }
- if(val==null){
- val = ""; // Or whatever you want
- }
- hashMap.put(fieldNameMap.get((String)key),val);
- }
- return hashMap;
-
- } else {
- List formParameter = new ArrayList();
- String formField = "";
-
-// for(int i = 1 ; i < (countOfFields+1); i++)
-// {
-// formField ="ff"+i;
-//
-// if(request.getParameterValues(formField) != null && request.getParameterValues(formField).length > 1 )
-// {
-// String[] vals = request.getParameterValues(formField);
-// boolean isMultiValue = false;
-// StringBuffer value = new StringBuffer("");
-// if(vals.length > 1) {
-// isMultiValue = true;
-// value.append("(");
-// }
-// for(int j = 0 ; j < vals.length; j++)
-// {
-// if(isMultiValue) value.append("'");
-// try {
-// if(vals[j] !=null && vals[j].length() > 0)
-// 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 > 1) {
-// value.append(")");
-// }
-//
-// //value = value.substring(0 , value.length());
-//
-// valuesMap.put(fieldNameMap.get(formField), value.toString());
-// value = new StringBuffer("");
-//
-// }
-// else if(request.getParameter(formField) != null)
-// {
-// String value = "";
-// value = request.getParameter(formField);
-// try {
-// if(value !=null && value.length() > 0)
-// value = java.net.URLDecoder.decode(request.getParameter(formField), "UTF-8");
-// } catch (UnsupportedEncodingException ex) {}
-// catch (IllegalArgumentException ex1){}
-// catch (Exception ex2){}
-// valuesMap.put(fieldNameMap.get(formField), value);
-//
-// }else
-// {
-// valuesMap.put(fieldNameMap.get(formField), "NULL" );
-// }
-// }
- 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);
-/* try {
- value = java.net.URLDecoder.decode(value, "UTF-8");
- } catch (UnsupportedEncodingException ex) {}
- catch (IllegalArgumentException ex1){}
- catch (Exception ex2){}
-*/
- 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);
- /*try {
- value = java.net.URLDecoder.decode(value, "UTF-8");
- } catch (UnsupportedEncodingException ex) {}
- catch (IllegalArgumentException ex1){}
- catch (Exception ex2){}
-*/
- valuesMap.put(fieldNameMap.get(formField), Utils.oracleSafe(value));
- }
-
- } else {
- valuesMap.put(fieldNameMap.get(formField), "" );
- }
-
- }
-
- return valuesMap;
- }
- }
-
- //new method added to get the help message for schedule tab
- public static String getScheduleHelpMessage() {
- return nvls(raptorProperties.getProperty("schedule_help_text"),"").trim();
- }
-
- //new method added to get the help message for schedule tab
- public static String getUseLoginIdInSchedYN() {
- return nvls(raptorProperties.getProperty("use_loginid_in_schedYN"),"N").trim();
- }
-
- //new method to check if map is allowed or not
- public static String getMapAllowedYN() {
- return nvls(raptorProperties.getProperty("map_allowed"),"").trim();
- }
-
- //new method added to get gmap key
- public static String getGmapKey() {
- return nvls(raptorProperties.getProperty("gmap_key"),"").trim();
- }
-
-// new method added to get gmap
- public static String getProjectFolder() {
- return nvls(raptorProperties.getProperty("PROJECT-FOLDER"),"").trim();
- }
-
-
- //new method added to get gmap
- public static String getMarketShapefileFolder() {
- return nvls(raptorProperties.getProperty("MARKET-SHAPEFILE-FOLDER"),"").trim();
- }
-
- //new method added to get gmap
- public static String getTileSize() {
- return nvls(raptorProperties.getProperty("TILE-SIZE"),"").trim();
- }
-
- // new method added to get gmap
- public static String getOutputFolder() {
- return nvls(raptorProperties.getProperty("OUTPUT-FOLDER"),"").trim();
- }
-
- //getting server details
- public static boolean isWeblogicServer() {
- return nvls(raptorProperties.getProperty("application_server"),"tomcat").trim().toUpperCase().startsWith("WEBLOGIC");
- }
-
- public static String getTempFolderURL() {
- return nvls(AppUtils.getTempFolderURL(),"").trim();
- }
-
- public static int getMaxDrillDownLevel() {
- int drillDownLevel = 1;
- try {
- drillDownLevel = Integer.parseInt(nvls(raptorProperties.getProperty("max_drilldown_level")).trim());
- } catch (Exception ex) {
-
- }
- return drillDownLevel;
- }
-
- public static int getMemoryThreshold() {
- int threshold = Integer.parseInt(nvls(raptorProperties.getProperty("memory_threshold_percentage"),"0").trim());
- if(threshold <= 0) threshold = 0;
- return threshold;
- }
-
- public static boolean showParamsInAllDashboardReports() {
- return nvls(raptorProperties.getProperty("show_params_in_all_dashboard_reports"),"N").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean isAdminRoleEquivalenttoSuperRole() {
- return nvls(raptorProperties.getProperty("admin_role_equiv_to_super_role"),"N").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean showLoadingMsgDuringFormFieldChain() {
- return nvls(raptorProperties.getProperty("show_loading_during_formfield_chain"),"Y").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean showPrintIcon() {
- return nvls(raptorProperties.getProperty("show_print_icon"),"Y").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean IsGlobalNoWrap() {
- return nvls(raptorProperties.getProperty("globally_nowrap"),"N").trim().toUpperCase().startsWith("Y");
- }
-
- public static String getCalendarOutputDateFormat() {
- return nvls(raptorProperties.getProperty("calendar_output_date_format"),"MM/dd/yyyy");
- }
-
- public static String getUserDefinedMessageForMemoryLimitReached() {
- return nvls(raptorProperties.getProperty("user_defined_message_memory_limit"),"Please note: Due to limited computing resource at this time,");
- }
-
- public static String getAdhocUserRoldId() {
- return nvls(raptorProperties.getProperty("adhoc_user_roleId"),"");
- }
-
- public static String getAdhocReportSequence() {
- return nvls(raptorProperties.getProperty("adhoc_report_sequence"),"");
- }
-
- public static boolean hideToolTipsGlobally() {
- return nvls(raptorProperties.getProperty("hide_tooltips_in_chart"),"N").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean showScheduleIconBeforeRun() {
- return nvls(raptorProperties.getProperty("show_schedule_icon_before_run"),"Y").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean hideRaptorFooter() {
- return nvls(raptorProperties.getProperty("hide_raptor_footer"),"N").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean getPrintParamsInCSVDownload() {
- return nvls(raptorProperties.getProperty("print_params_in_csv_download"),"N").trim().toUpperCase().startsWith("Y");
- }
-
- public static String getLogVariablesInSession() {
- return nvls(raptorProperties.getProperty("log_variable_in_session"), "");
- }
-
- public static boolean hideTitleInDashboard() {
- return nvls(raptorProperties.getProperty("notitle_in_dashboard"), "N").trim().toUpperCase().startsWith("Y");
- }
-
- public static String getEncryptedSMTPServer() {
- return nvls(raptorProperties.getProperty("secure_smtp_server"), "");
- }
-
- public static boolean generateSchedReportsInFileSystem() {
- return nvls(raptorProperties.getProperty("generate_store_sched_reports"), "N").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean showExcel2007DownloadIcon() {
- return nvls(raptorProperties.getProperty("show_excel_2007_download"), "N").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean printExcelInLandscapeMode() {
- return nvls(raptorProperties.getProperty("print_excel_in_landscape"), "").trim().toUpperCase().startsWith("Y");
- }
-
- public static String getAppDefinedMessageForSendingSchedAsAttachment() {
- return nvls(raptorProperties.getProperty("app_defined_message_schedule_attachment"),"Send as Attachment");
- }
-
- public static String getReportEmptyMessage() {
- return nvls(raptorProperties.getProperty("no_rows_found"),"Your Search didn't yield any results.");
- }
-
- public static boolean showAnimatedChartOption() {
- return nvls(raptorProperties.getProperty("show_animated_chart_option"),"N").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean showAnimatedChartOnly() {
- return nvls(raptorProperties.getProperty("show_animated_chart_only"),"N").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean adjustContentBasedOnHeight() {
- return nvls(raptorProperties.getProperty("adjust_content_based_on_height"),"N").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean disclaimerPositionedTopInCSVExcel() {
- return nvls(raptorProperties.getProperty("disclaimer_positioned_top_in_csvexcel"),"N").trim().toUpperCase().startsWith("Y");
- }
-
- public static String customizedSubmitButtonText() {
- return nvls(raptorProperties.getProperty("custom_submit_button_text"),"submit");
- }
-
- public static String customizedResetButtonText() {
- return nvls(raptorProperties.getProperty("custom_reset_button_text"),"reset");
- }
- public static boolean customizeFormFieldLayout() {
- return nvls(raptorProperties.getProperty("customize_formfield_layout"),"N").trim().toUpperCase().startsWith("Y");
- }
- public static String getRaptorTheme() {
- return nvls(raptorProperties.getProperty("raptor_theme"),"default");
- }
-
- public static String getFormfieldAlignment() {
- return nvls(raptorProperties.getProperty("formfield_alignment"),"left");
- }
-
- public static boolean displayExcelOptionInDashboard() {
- return nvls(raptorProperties.getProperty("display_excel_option_in_dashboard"),"N").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean displayRuntimeOptionsAsDefault() {
- return nvls(raptorProperties.getProperty("display_runtime_options_as_default"),"Y").trim().toUpperCase().startsWith("Y");
- }
-
- public static boolean displayHiddenFormfieldinExcel() {
- return nvls(raptorProperties.getProperty("display_hidden_field_in_excel"),"N").trim().toUpperCase().startsWith("Y");
- }
-
- //ReportLoader.java
- public static String getLoadCustomReportXml(){
- return nvls(sqlProperty.getProperty("load.custom.report.xml"));
- }
-
- public static String getDBUpdateReportXml(){
- return nvls(sqlProperty.getProperty("db.update.report.xml"));
- }
-
- public static String getDBUpdateReportXmlMySql(){
- return nvls(sqlProperty.getProperty("db.update.report.xml.mysql"));
- }
-
- public static String getDBUpdateReportXmlMySqlSelect(){
- return nvls(sqlProperty.getProperty("db.update.report.xml.mysql.select"));
- }
-
- public static String getUpdateCustomReportRec(){
- return nvls(sqlProperty.getProperty("update.custom.report.rec"));
- }
-
- public static String getIsReportAlreadyScheduled(){
- return nvls(sqlProperty.getProperty("is.report.already.scheduled"));
- }
-
- public static String getCreateCustomReportRec(){
- return nvls(sqlProperty.getProperty("create.custom.report.rec"));
- }
-
- public static String getTheUserReportNames(){
- return nvls(sqlProperty.getProperty("get.user.report.names"));
- }
-
- public static String getTheReportOwnerId(){
- return nvls(sqlProperty.getProperty("get.report.owner.id"));
- }
-
- public static String getReportSecurity(){
- return nvls(sqlProperty.getProperty("report.security.create"));
- }
-
- public static String getDeleteReportRecordLog(){
- return nvls(sqlProperty.getProperty("delete.report.record.log"));
- }
-
- public static String getDeleteReportRecordUsers(){
- return nvls(sqlProperty.getProperty("delete.report.record.users"));
- }
-
- public static String getDeleteReportRecordSchedule(){
- return nvls(sqlProperty.getProperty("delete.report.record.schedule"));
- }
-
- public static String getDeleteReportRecordAccess(){
- return nvls(sqlProperty.getProperty("delete.report.record.access"));
- }
-
- public static String getDeleteReportRecordEmail(){
- return nvls(sqlProperty.getProperty("delete.report.record.email"));
- }
-
- public static String getDeleteReportRecordFavorite(){
- return nvls(sqlProperty.getProperty("delete.report.record.favorite"));
- }
-
- public static String getDeleteReportRecordReport(){
- return nvls(sqlProperty.getProperty("delete.report.record.report"));
- }
-
- public static String getLoadQuickLinks(){
- return nvls(sqlProperty.getProperty("load.quick.links"));
- }
-
- public static String getLoadFolderReports(){
- return nvls(sqlProperty.getProperty("load.folder.reports"));
- }
-
- public static String getLoadFolderReportsUser(){
- return nvls(sqlProperty.getProperty("load.folder.reports.user"));
- }
-
- public static String getLoadFolderReportsPublicSql(){
- return nvls(sqlProperty.getProperty("load.folder.reports.publicsql"));
- }
-
- public static String getLoadQuickDownloadLinks(){
- return nvls(sqlProperty.getProperty("load.quick.download.links"));
- }
-
- public static String getLoadReportsToSchedule(){
- return nvls(sqlProperty.getProperty("load.reports.to.schedule"));
- }
-
- public static String getLoadReportsToAddInDashboard(){
- return nvls(sqlProperty.getProperty("load.reports.to.add.in.dashboard"));
- }
-
- public static String getLoadMyRecentLinks(){
- return nvls(sqlProperty.getProperty("load.my.recent.links"));
- }
-
- public static String getCreateReportLogEntry(){
- return nvls(sqlProperty.getProperty("create.report.log.entry"));
- }
-
- public static String getCreateReportLogEntryExecTime(){
- return nvls(sqlProperty.getProperty("create.report.log.entry.exec.time"));
- }
-
- public static String getClearReportLogEntries(){
- return nvls(sqlProperty.getProperty("clear.report.log.entries"));
- }
-
- public static String getLoadReportLogEntries(){
- return nvls(sqlProperty.getProperty("load.report.log.entries"));
- }
-
- public static String getDoesUserCanScheduleReport(){
- return nvls(sqlProperty.getProperty("does.user.can.schedule.report"));
- }
-
- public static String getDoesUserCanSchedule(){
- return nvls(sqlProperty.getProperty("does.user.can.schedule"));
- }
-
- public static String getTheSystemDateTime(){
- return nvls(sqlProperty.getProperty("get.system.date.time"));
- }
-
- public static String getTheNextDayDateTime(){
- return nvls(sqlProperty.getProperty("get.next.day.date.time"));
- }
-
- public static String getTheNextFifteenMinDateTime(){
- return nvls(sqlProperty.getProperty("get.next.fifteen.minutes.date.time"));
- }
-
- public static String getTheNextThirtyMinDateTime(){
- return nvls(sqlProperty.getProperty("get.next.thirty.minutes.date.time"));
- }
-
- public static String getTheTemplateFile(){
- return nvls(sqlProperty.getProperty("get.template.file"));
- }
-
- public static String getLoadPdfImgLookup(){
- return nvls(sqlProperty.getProperty("load.pdf.img.lookup"));
- }
-
- public static String getLoadActionImgLookup(){
- return nvls(sqlProperty.getProperty("load.action.img.lookup"));
- }
-
- //ActionHandler.java
-
- public static String getReportValuesMapDefA(){
- return nvls(sqlProperty.getProperty("report.values.map.def.a"));
- }
- public static String getReportValuesMapDefB(){
- return nvls(sqlProperty.getProperty("report.values.map.def.b"));
- }
- public static String getReportValuesMapDefC(){
- return nvls(sqlProperty.getProperty("report.values.map.def.c"));
- }
- public static String getReportValuesMapDefD(){
- return nvls(sqlProperty.getProperty("report.values.map.def.d"));
- }
-
- public static String getTestSchedCondPopup(){
- return nvls(sqlProperty.getProperty("test.sched.cond.popup"));
- }
-
- public static String getDownloadAllEmailSent(){
- return nvls(sqlProperty.getProperty("download.all.email.sent"));
- }
-
- public static String getDownloadAllGenKey(){
- return nvls(sqlProperty.getProperty("download.all.gen.key"));
- }
-
- public static String getDownloadAllRetrieve(){
- return nvls(sqlProperty.getProperty("download.all.retrieve"));
- }
-
- public static String getDownloadAllInsert(){
- return nvls(sqlProperty.getProperty("download.all.insert"));
- }
-
- //ReportWrapper.java
-
- public static String getReportWrapperFormat(){
- return nvls(sqlProperty.getProperty("report.wrapper.format"));
- }
-
- public static String getGenerateSubsetSql(){
- return nvls(sqlProperty.getProperty("generate.subset.sql"));
- }
-
- public static String getReportSqlForFormfield(){
- return nvls(sqlProperty.getProperty("formfield.id.name.sql"));
- }
-
- public static String getReportSqlForFormfieldPrefix(){
- return nvls(sqlProperty.getProperty("formfield.id.name.sql.prefix"));
- }
-
- public static String getReportSqlForFormfieldSuffix(){
- return nvls(sqlProperty.getProperty("formfield.id.name.sql.suffix"));
- }
-
- public static String getReportSqlOnlyFirstPart(){
- return nvls(sqlProperty.getProperty("report.sql.only.first.part"));
- }
-
- public static String getReportSqlOnlySecondPartA(){
- return nvls(sqlProperty.getProperty("report.sql.only.second.part.a"));
- }
-
- public static String getReportSqlOnlySecondPartB(){
- return nvls(sqlProperty.getProperty("report.sql.only.second.part.b"));
- }
-
- public static String getReportSqlOnlySecondPartBNoOrderBy(){
- return nvls(sqlProperty.getProperty("report.sql.only.second.part.b.noorderby"));
- }
-
- public static String getGenerateSqlVisualSelect(){
- return nvls(sqlProperty.getProperty("generate.sql.visual.select"));
- }
-
- public static String getGenerateSqlVisualCount(){
- return nvls(sqlProperty.getProperty("generate.sql.visual.count"));
- }
-
- public static String getGenerateSqlVisualDual(){
- return nvls(sqlProperty.getProperty("generate.sql.visual.select"));
- }
-
- //ReportRuntime.java
-
- public static String getLoadCrosstabReportData(){
- return nvls(sqlProperty.getProperty("load.crosstab.report.data"));
- }
-
- //ReportRunHandler.java
-
- public static String getGenerateSqlHandler(){
- return nvls(sqlProperty.getProperty("generate.sql.handler"));
- }
-
- public static String getGenerateSqlSelect(){
- return nvls(sqlProperty.getProperty("generate.sql.select"));
- }
-
- public static String getRemoteDbSchemaSql() {
- return nvls(sqlProperty.getProperty("load.remoteDB.schema"));
- }
-
- public static String getRemoteDbSchemaSqlWithWhereClause() {
- return nvls(sqlProperty.getProperty("load.remoteDB.schema.where"));
- }
-
- //ReportSchedule.java
-
- public static String getLoadScheduleData(){
- return nvls(sqlProperty.getProperty("load.schedule.data"));
- }
-
- public static String getLoadScheduleGetId(){
- return nvls(sqlProperty.getProperty("load.schedule.getid"));
- }
-
- public static String getLoadScheduleUsers(){
- return nvls(sqlProperty.getProperty("load.schedule.users"));
- }
-
- public static String getNewScheduleData(){
- return nvls(sqlProperty.getProperty("new.schedule.data"));
- }
-
- public static String getNewReportData(){
- return nvls(sqlProperty.getProperty("new.report.data"));
- }
-
- public static String getExecuteUpdate(){
- return nvls(sqlProperty.getProperty("execute.update"));
- }
-
- public static String getExecuteUpdateUsers(){
- return nvls(sqlProperty.getProperty("execute.update.users"));
- }
-
- public static String getExecuteUpdateRoles(){
- return nvls(sqlProperty.getProperty("execute.update.roles"));
- }
-
- public static String getExecuteUpdateActivity(){
- return nvls(sqlProperty.getProperty("execute.update.activity"));
- }
-
- public static String getDeleteScheduleData(){
- return nvls(sqlProperty.getProperty("delete.schedule.data"));
- }
-
- public static String getDeleteScheduleDataUsers(){
- return nvls(sqlProperty.getProperty("delete.schedule.data.users"));
- }
-
- public static String getDeleteScheduleDataId(){
- return nvls(sqlProperty.getProperty("delete.schedule.data.id"));
- }
-
- public static String getLoadCondSql(){
- return nvls(sqlProperty.getProperty("load.cond.sql"));
- }
-
- public static String getLoadCondSqlSelect(){
- return nvls(sqlProperty.getProperty("load.cond.sql.select"));
- }
-
- public static String getPersistCondSqlUpdate(){
- return nvls(sqlProperty.getProperty("persist.cond.sql.update"));
- }
-
- public static String getPersistCondSqlLarge(){
- return nvls(sqlProperty.getProperty("persist.cond.sql.large"));
- }
-
- public static String getPersistCondSqlSet(){
- return nvls(sqlProperty.getProperty("persist.cond.sql.set"));
- }
-
- //DataCache.java
-
- public static String getTheDataViewActions(){
- return nvls(sqlProperty.getProperty("get.data.view.actions"));
- }
-
- public static String getThePublicReportIdNames(){
- return nvls(sqlProperty.getProperty("get.public.report.id.names"));
- }
-
- public static String getThePrivateAccessibleNamesA(){
- return nvls(sqlProperty.getProperty("get.private.accessible.names.a"));
- }
- public static String getThePrivateAccessibleNamesIf(){
- return nvls(sqlProperty.getProperty("get.private.accessible.names.if"));
- }
- public static String getThePrivateAccessibleNamesB(){
- return nvls(sqlProperty.getProperty("get.private.accessible.names.b"));
- }
-
- public static String getTheGroupAccessibleNamesA(){
- return nvls(sqlProperty.getProperty("get.group.accessible.names.a"));
- }
-
- public static String getTheGroupAccessibleNamesB(){
- return nvls(sqlProperty.getProperty("get.group.accessible.names.b"));
- }
-
- public static String getTheReportTableSourcesA(){
- return nvls(sqlProperty.getProperty("get.report.table.sources.a"));
- }
-
- public static String getTheReportTableSourcesWhere(){
- return nvls(sqlProperty.getProperty("get.report.table.sources.where"));
- }
-
- public static String getTheReportTableSourcesIf(){
- return nvls(sqlProperty.getProperty("get.report.table.sources.if"));
- }
-
- public static String getTheReportTableSourcesElse(){
- return nvls(sqlProperty.getProperty("get.report.table.sources.else"));
- }
-
- public static String grabTheReportTableA(){
- return nvls(sqlProperty.getProperty("grab.report.table.a"));
- }
-
- public static String grabTheReportTableIf(){
- return nvls(sqlProperty.getProperty("grab.report.table.if"));
- }
-
- public static String grabTheReportTableElse(){
- return nvls(sqlProperty.getProperty("grab.report.table.else"));
- }
-
- public static String grabTheReportTableB(){
- return nvls(sqlProperty.getProperty("grab.report.table.b"));
- }
-
- public static String grabTheReportTableC(){
- return nvls(sqlProperty.getProperty("grab.report.table.c"));
- }
-
- public static String getTheReportTableCrJoin(){
- return nvls(sqlProperty.getProperty("get.report.table.crjoin"));
- }
-
- public static String getTheReportTableJoins(){
- return nvls(sqlProperty.getProperty("get.report.table.joins"));
- }
-
- public static String getGenerateReportTableCol(){
- return nvls(sqlProperty.getProperty("generate.report.table.col"));
- }
-
-
- public static String getGenerateDbUserSqlA(){
- return nvls(sqlProperty.getProperty("generate.db.user.sql.a"));
- }
-
- public static String getGenerateDbUserSqlIf(){
- return nvls(sqlProperty.getProperty("generate.db.user.sql.if"));
- }
-
- public static String getGenerateDbUserSqlElse(){
- return nvls(sqlProperty.getProperty("generate.db.user.sql.else"));
- }
-
- public static String getGenerateDbUserSqlB(){
- return nvls(sqlProperty.getProperty("generate.db.user.sql.b"));
- }
-
- public static String getGenerateDbUserSqlC(){
- return nvls(sqlProperty.getProperty("generate.db.user.sql.c"));
- }
-
- public static String getGenerateDbUserSqlD(){
- return nvls(sqlProperty.getProperty("generate.db.user.sql.d"));
- }
-
- //SearchHandler.java
-
- public static String getLoadReportSearchResult(){
- return nvls(sqlProperty.getProperty("load.report.search.result"));
- }
-
- public static String getLoadReportSearchRepIdSql(){
- return nvls(sqlProperty.getProperty("load.report.search.rep_id_sql"));
- }
-
- public static String getLoadReportSearchInstr(){
- return nvls(sqlProperty.getProperty("load.report.search.instr"));
- }
-
- public static String getLoadReportSearchResultUser(){
- return nvls(sqlProperty.getProperty("load.report.search.result.user"));
- }
-
- public static String getLoadReportSearchResultPublic(){
- return nvls(sqlProperty.getProperty("load.report.search.result.public"));
- }
-
- public static String getLoadReportSearchResultFav(){
- return nvls(sqlProperty.getProperty("load.report.search.result.fav"));
- }
-
- public static String getLoadReportSearchResultSort(){
- return nvls(sqlProperty.getProperty("load.report.search.result.sort"));
- }
-
- public static String getLoadFolderReportResult(){
- return nvls(sqlProperty.getProperty("load.folder.report.result"));
- }
-
- public static String getLoadFolderReportResultSort(){
- return nvls(sqlProperty.getProperty("load.folder.report..result.sort"));
- }
-
- //WizardProcessor.java
-
- public static String getProcessFilterAddEdit(){
- return nvls(sqlProperty.getProperty("process.filter.add.edit"));
- }
-
- //ReportDefinition.java
-
- public static String getPersistReportAdhoc(){
- return nvls(sqlProperty.getProperty("persist.report.adhoc"));
- }
-
- //Globals.java
- public static String getInitializeRoles(){
- return nvls(sqlProperty.getProperty("initialize.roles"));
- }
-
- public static String getInitializeVersion(){
- return nvls(sqlProperty.getProperty("initialize.version"));
- }
-
- public static String getDBType(){
- return nvls(raptorProperties.getProperty("db_type"), "oracle");
- }
-
- public static boolean isPostgreSQL(){
- return getDBType().equals("postgresql");
- }
- public static boolean isMySQL(){
- return getDBType().equals("mysql");
- }
- public static boolean isOracle(){
- return getDBType().equals("oracle");
- }
-
- //scheduler
- public static String getAvailableSchedules(){
- return nvls(sqlProperty.getProperty("scheduler.available.schedules"));
- }
-
- public static String getCurrentDateString(){
- return nvls(sqlProperty.getProperty("current.date.string"));
- }
-
- public static String getSchedulerUserEmails(){
- return nvls(sqlProperty.getProperty("scheduler.user.emails"));
- }
-
- public static String getSqlConvertToRaw(){
- return nvls(sqlProperty.getProperty("convert.to.raw"));
- }
-
- public static Properties getRaptorPdfProperties() {
- return raptorPdfProperties;
- }
-
- public static void setRaptorPdfProperties(Properties raptorPdfProperties) {
- Globals.raptorPdfProperties = raptorPdfProperties;
- }
-
- public static Properties getRaptorProperties() {
- return raptorProperties;
- }
-
- public static void setRaptorProperties(Properties raptorProperties) {
- Globals.raptorProperties = raptorProperties;
- }
-
- public static Properties getSqlProperty() {
- return sqlProperty;
- }
-
- public static void setSqlProperty(Properties sqlProperty) {
- Globals.sqlProperty = sqlProperty;
- }
-
- public static String getSequenceNextVal() {
- return nvls(sqlProperty.getProperty("seq.next.val"));
- }
-
- public static String getRandomString() {
- return nvls(sqlProperty.getProperty("seq.next.val"));
- }
-
- public static String getReportUserAccess(){
- return nvls(sqlProperty.getProperty("report.user.access"));
- }
-
- public static String getAddUserAccess(){
- return nvls(sqlProperty.getProperty("add.user.access"));
- }
-
- public static String getUpdateUserAccess(){
- return nvls(sqlProperty.getProperty("update.user.access"));
- }
-
- public static String getRemoveUserAccess(){
- return nvls(sqlProperty.getProperty("remove.user.access"));
- }
-
- public static String getAddRoleAccess(){
- return nvls(sqlProperty.getProperty("add.role.access"));
- }
-
- public static String getUpdateRoleAccess(){
- return nvls(sqlProperty.getProperty("update.role.access"));
- }
-
- public static String getRemoveRoleAccess(){
- return nvls(sqlProperty.getProperty("remove.role.access"));
- }
-
- public static boolean isSystemInitialized() {
- return systemInitialized;
- }
-
-} // Globals
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system;
-
-import java.util.*;
-import javax.servlet.*;
-import javax.servlet.http.*;
-
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.error.ReportSQLException;
-
-public interface IAppUtils {
- void initializeAppUtils(ServletContext servletContext);
-
- /** Returns ID of the user currently logged in */
- String getUserID(HttpServletRequest request);
-
- /** Obtains user name by ID */
- String getUserName(HttpServletRequest request);
- String getUserName(String userId);
-
- /** Obtains user email by ID */
- String getUserEmail(HttpServletRequest request);
- String getUserEmail(String userId);
-
- /** Obtains user login ID */
- String getUserLoginId(HttpServletRequest request);
- String getUserLoginId(String userId);
-
- /** Obtains user back door log id */
- String getUserBackdoorLoginId(HttpServletRequest request);
-
- /** Obtains list of all users (in IdNameValue objects) */
- Vector getAllUsers(String customizedQuery, String param, boolean isAdmin);
-
- /** Obtains role name by ID */
- String getRoleName(String roleId);
-
- /** Obtains list of all roles (in IdNameValue objects) */
- Vector getAllRoles(String customizedQuery, String param, boolean isAdmin);
-
- /** Checks whether the user currently logged in has the specified role */
- // boolean isUserInRole(HttpServletRequest request, String roleId);
- /** Checks whether the specified user has the specified role */
- boolean isUserInRole(HttpServletRequest request, String roleId) throws RaptorException ;
-
- /**
- * Returns Vector containing the IDs of all the roles to which the user
- * currently logged in belongs
- */
- // Vector getUserRoles(HttpServletRequest request);
- /**
- * Returns Vector containing the IDs of all the roles to which the specified
- * user belongs
- */
- Vector getUserRoles(HttpServletRequest request)throws RaptorException;
-
- Vector getUserRoles(String userID)throws RaptorException;
- /** Empties cached lists of app users and roles */
- void resetUserCache();
-
- /** Returns the ID of the super role (all powerful) */
- String getSuperRoleID();
-
- /** Returns Vector containing the IDs of all Admin roles */
- Vector getAdminRoleIDs();
-
- /** Returns Temp folder file path */
- String getTempFolderPath();
-
- /** Returns Upload folder file path */
- String getUploadFolderPath();
-
- /** Returns Temp folder web URL */
- String getTempFolderURL();
-
- /** Returns Upload folder web URL */
- String getUploadFolderURL();
-
- /** Returns SMTP server to be used for notifications */
- String getSMTPServer()throws RaptorException ;
-
- /** Returns Encrypted SMTP server to be used for notifications */
- String getEncryptedSMTPServer()throws RaptorException ;
-
- /**
- * Returns email address used for the "From" field in the system
- * notifications
- */
- String getDefaultEmailSender() throws RaptorException;
-
- /** Returns the application error page */
- String getErrorPage();
-
- /** Returns the application error page with menu for fusion*/
- String getErrorPageWMenu();
-
- /** Returns path to the folder containing JSP pages */
- String getJspContextPath();
-
- /** Returns web URL of the folder containing the images */
- String getImgFolderURL();
-
- /** Returns web URL to the base raptor folder */
- String getBaseFolderURL();
-
- /** Returns the URL used for executing a report - system specific */
- // String getReportExecuteActionURL();
- /** Returns the URL used for displaying data record - system specific */
- // String getDataViewActionURL();
- /**
- * Returns the parameter name of the ID value used for displaying data
- * record - system specific
- */
- // String getDataViewActionParam();
- /** Returns full web URL for direct access to execute a report */
- String getDirectAccessURL();
-
- /** Returns the URL of the controller servlet - system specific */
- String getBaseActionURL();
-
- /** Returns the base URL of the NG report - system specific */
- String getBaseActionURLNG();
-
- /** Returns the URL of the Report Run specifc to AngularJS */
- String getDrillActionURL();
-
- /** Returns the primary parameter name - system specific */
- String getBaseActionParam();
-
- /** Returns Vector containing menu IDs for quick links */
- Vector getQuickLinksMenuIDs();
-
- /** Obtains menu label by ID */
- String getMenuLabel(String menuId);
-
- /**
- * SQL for loading the screen labels and restricting to active cols only for
- * report columns; can return null => use straight data dictionary For
- * PRISMS - based on "useFieldTable" config parameter
- */
- String getReportDbColsMaskSQL();
-
- /**
- * SQL for replacing lookup tables with id and name values; can return null =>
- * do NOT replace lookups Returns SQL with columns - Table_name, Field_name,
- * New_Lookup_Table_name, New_Lookup_Id_Field_name,
- * New_Lookup_Name_Field_name For PRISMS - based on "useFieldTable" config
- * parameter
- */
- String getReportDbLookupsSQL();
-
- /** Obtains menu label by ID */
- void processErrorNotification(HttpServletRequest request, RaptorException e);
-
- /** Returns Excel template PATH web URL */
- String getExcelTemplatePath();
-
- String getFolderPathAdj();
-} // IAppUtils
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system;
-
-import java.sql.*;
-import java.util.*;
-import javax.servlet.*;
-
-import org.openecomp.portalsdk.analytics.error.RaptorRuntimeException;
-import org.openecomp.portalsdk.analytics.error.ReportSQLException;
-
-public interface IDbUtils {
- void initializeDbUtils(ServletContext servletContext);
-
- Connection getConnection() throws ReportSQLException ;
-
- void clearConnection(Connection con) throws ReportSQLException ;
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system;
-
-import java.sql.*;
-import javax.servlet.*;
-
-import org.openecomp.portalsdk.analytics.error.ReportSQLException;
-
-public interface RDbUtils {
-
- void initializeDbUtils(ServletContext servletContext);
-
- Connection getRemoteConnection(String dbKey)throws ReportSQLException;
-
- void clearConnection(Connection con)throws ReportSQLException;
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system;
-
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-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.util.DataSet;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
-public class RemDbUtils /* implements IDbUtils */{
-
- static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RemDbUtils.class);
-
-
-
- public RemDbUtils() {
- }
-
- public static Connection getConnection(String dbKey) throws ReportSQLException {
- return Globals.getRDbUtils().getRemoteConnection(dbKey);
- } // getConnection
-
- public static void clearConnection(Connection con) throws ReportSQLException {
- try {
- if ((con != null) && !con.isClosed())
- Globals.getRDbUtils().clearConnection(con);
- } catch (SQLException ex) { throw new ReportSQLException(ex.getMessage()); }
-
- } // clearConnection
-
- public static Connection startTransaction(String dbKey) throws RaptorException {
- Connection con = null;
- try {
- con = getConnection(dbKey);
- con.setAutoCommit(false);
- } catch (SQLException ex) {
- throw new RaptorRuntimeException (ex.getMessage(), ex.getCause());
- } catch (Exception ex2 ) {
- throw new RaptorException (ex2.getMessage(), ex2.getCause());
- }
- return con;
- } // startTransaction
-
- public static void commitTransaction(Connection con) throws RaptorException {
- try {
- con.commit();
- } catch (SQLException ex) {
- throw new RaptorRuntimeException (ex.getMessage(), ex.getCause());
- } catch (Exception ex2 ) {
- throw new RaptorException (ex2.getMessage(), ex2.getCause());
- }
- //clearConnection(con);
- } // commitTransaction
-
- public static void rollbackTransaction(Connection con) throws RaptorException {
- try {
- con.rollback();
- clearConnection(con);
- } catch (SQLException ex) {
- throw new RaptorRuntimeException (ex.getMessage(), ex.getCause());
- } catch (Exception ex2 ) {
- throw new RaptorException (ex2.getMessage(), ex2.getCause());
- }
- } // rollbackTransaction
-
-// public static String executeCall(Connection con, String sql, boolean expectResult)
-// throws ReportSQLException, Exception {
-// String result = null;
-//
-// try {
-// if(con.isClosed()) con = getConnection();
-// Log.write("[SQL Call] " + sql, 4);
-// CallableStatement stmt = con.prepareCall(sql);
-// if (expectResult)
-// stmt.registerOutParameter(1, Types.CHAR);
-// stmt.executeUpdate();
-// if (expectResult)
-// result = stmt.getString(1);
-// stmt.close();
-// con.commit();
-// } catch (SQLException e) {
-// throw new ReportSQLException(e.getMessage(), sql);
-// } finally {
-// clearConnection(con);
-// }
-//
-// return result;
-// } // executeCall
-//
-// public static String executeCall(String sql, boolean expectResult)
-// throws ReportSQLException, Exception {
-// Connection con = null;
-// try {
-// con = getConnection();
-// String result = executeCall(con, sql, expectResult);
-// return result;
-// } catch (SQLException e) {
-// throw new ReportSQLException(e.getMessage(), sql);
-// }
-// } // executeCall
-//
-// public static int executeUpdate(Connection con, String sql) throws ReportSQLException, Exception {
-// try {
-// if(con.isClosed()) con = getConnection();
-// Statement stmt = con.createStatement();
-//
-// int rcode = -1;
-// try {
-// Log.write("[SQL Update] " + sql, 4);
-// rcode = stmt.executeUpdate(sql);
-// stmt.close();
-// con.commit();
-// } finally {
-// clearConnection(con);
-// }
-//
-// return rcode;
-// } catch (SQLException e) {
-// throw new ReportSQLException(e.getMessage(), sql);
-// } finally {
-// clearConnection(con);
-// }
-// } // executeUpdate
-//
-// public static int executeUpdate(String sql) throws ReportSQLException, Exception {
-// Connection con = null;
-// try {
-// con = getConnection();
-// int rcode = executeUpdate(con, sql);
-// return rcode;
-// } catch (SQLException e) {
-// throw new ReportSQLException(e.getMessage(), sql);
-// }
-// } // executeUpdate
-
- public static DataSet executeQuery(Connection con, String sql, String dbKey) throws ReportSQLException, Exception {
- return executeQuery(con, sql, Integer.MAX_VALUE,dbKey);
- } // executeQuery
-
- public static DataSet executeQuery(Connection con, String sql, int maxRowLimit, String dbKey)
- throws ReportSQLException {
- try {
- if (con==null || con.isClosed()) con = getConnection(dbKey);
- if(con==null) throw new ReportSQLException("Remote Connection not configured for "+ dbKey);
- Statement stmt = con.createStatement();
- logger.debug(EELFLoggerDelegate.debugLogger, ("[SQL CALL FROM RAPTOR] [SQL] " + sql));
- ResultSet rs = stmt.executeQuery(sql);
- DataSet ds = new DataSet(rs, maxRowLimit);
- if(rs!=null)
- rs.close();
- if(stmt!=null)
- stmt.close();
-
- return ds;
- } catch (SQLException e) {
- throw new ReportSQLException(e.getMessage(), sql, e.getCause());
- }
- } // executeQuery
-
- public static DataSet executeQuery(String sql,String dbKey) throws ReportSQLException {
- return executeQuery(sql, Integer.MAX_VALUE, dbKey);
- } // executeQuery
-
- public static DataSet executeQuery(String sql, int maxRowLimit, String dbKey) throws ReportSQLException{
- Connection con = null;
- try {
- con = getConnection(dbKey);
- return executeQuery(con, sql, maxRowLimit,dbKey);
- } catch (ReportSQLException e) {
- throw new ReportSQLException(e.getMessage(), sql, e.getCause());
- } finally {
- clearConnection(con);
- }
- } // executeQuery
-
-} // DbUtils
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion;
-
-import java.io.IOException;
-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_fusion.jar" command.
- */
-public class AntBuild {
-
- public static void main(String[] args) {
- System.out.println("Jar (raptor_fusion.jar) Information: ");
- readManifest();
- }
-
- public static void readManifest() {
- try {
- JarFile jar = new JarFile("./raptor_fusion.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("JDK Version " + " : " + attributeValue);
- else if (attributeName.toString().equals("Ant-Version"))
- System.out.println(attributeName.toString() + " : " + attributeValue);
- else {
- if(attributeName.toString().startsWith("Raptor"))
- System.out.println(attributeName.toString() + " : " + attributeValue);
- }
- }
-
- } catch (IOException e) {
- System.err.println("Cannot read jar-file manifest: "
- + e.getMessage());
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion;
-
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.analytics.config.ConfigLoader;
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.model.base.IdNameValue;
-import org.openecomp.portalsdk.analytics.system.Globals;
-import org.openecomp.portalsdk.analytics.system.IAppUtils;
-import org.openecomp.portalsdk.analytics.system.fusion.adapter.RaptorAdapter;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;;
-
-public class AppUtils extends org.openecomp.portalsdk.analytics.RaptorObject implements IAppUtils {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppUtils.class);
-
-
- private static String tempFolderPath = "/artemis/PROJECT1/MSA/databank/WEB-INF/temp/";
- private static String uploadFolderPath = "/artemis/PROJECT1/MSA/databank/WEB-INF/upload/";
- private static String tempFolderURL = "temp/";
- private static String uploadFolderURL = "upload/";
- private static String SMTPServer = "todo.smtp.server.com";
- private static String defaultEmailSender = "todo.email.sender.com";
- private static String errorPage = "error_page";
- private static String errorPageWMenu = "error_page_wmenu";
- private static String jspContextPath = "raptor/";
- private static String imgFolderURL = "raptor/images/";
- private static String baseFolderURL = "raptor/";
- //private static String reportExecuteActionURL = "dispatcher?action=raptor&r_action=report.run&c_master=";
- //private static String dataViewActionURL = "dispatcher?action="; // dispatcher?action=ACTION_ID&c_master=REC_ID
- //private static String dataViewActionParam = "c_master=";
- private static String directAccessURL = "http://localhost:8082/databank/dispatcher?direct.access=raptor&r_action=report.run&show=";
- private static String baseActionURL = "dispatcher?action="; // dispatcher?action=ACTION_ID&c_master=REC_ID or dispatcher?action=raptor&r_action=RAPTOR_ACTION_ID&c_master=REC_ID
- private static String baseActionURLNG = "report#/"; // dispatcher?action=ACTION_ID&c_master=REC_ID or dispatcher?action=raptor&r_action=RAPTOR_ACTION_ID&c_master=REC_ID
- private static String drillActionURL = "dispatcher?action="; // dispatcher?action=ACTION_ID&c_master=REC_ID or dispatcher?action=raptor&r_action=RAPTOR_ACTION_ID&c_master=REC_ID
- private static String baseActionParam = "c_master=";
- private static String superRoleID = "1";
- private static Vector adminRoleIDs = new Vector();
- private static Vector quickLinksMenuIDs = new Vector();
-
- private static Properties raptorAppProperties;
-
- private static String encryptedSMTPServer = "";
- public AppUtils() {}
-
- public void initializeAppUtils(ServletContext servletContext) {
- try {
- Properties appProperties = ConfigLoader.getProperties(servletContext, ConfigLoader.APP_PROPERTIES, Globals.getSystemType());
- raptorAppProperties = appProperties;
- tempFolderPath = appProperties.getProperty("temp_folder_path");
- uploadFolderPath = appProperties.getProperty("upload_folder_path");
- tempFolderURL = appProperties.getProperty("temp_folder_url");
- uploadFolderURL = appProperties.getProperty("upload_folder_url");
- SMTPServer = appProperties.getProperty("smtp_server");
- encryptedSMTPServer = appProperties.getProperty("encrypted_smtp_server");
- defaultEmailSender = appProperties.getProperty("default_email_sender");
- errorPage = appProperties.getProperty("error_page");
- jspContextPath = appProperties.getProperty("jsp_context_path");
- imgFolderURL = appProperties.getProperty("img_folder_url");
- baseFolderURL = appProperties.getProperty("base_folder_url");
-/* reportExecuteActionURL = appProperties.getProperty("report_execute_action_url");
- dataViewActionURL = appProperties.getProperty("data_view_action_url");
- dataViewActionParam = appProperties.getProperty("data_view_action_param");*/
- directAccessURL = appProperties.getProperty("direct_access_url");
- baseActionURL = appProperties.getProperty("base_action_url");
- baseActionURLNG = appProperties.getProperty("base_action_url_ng");
- drillActionURL = appProperties.getProperty("drill_action_url");
- baseActionParam = appProperties.getProperty("base_action_param");
- superRoleID = appProperties.getProperty("super_role_id");
-
- adminRoleIDs.removeAllElements();
- StringTokenizer st = new StringTokenizer(appProperties.getProperty("admin_role_ids"), ",");
- while(st.hasMoreTokens())
- adminRoleIDs.add(st.nextToken());
-
- quickLinksMenuIDs.removeAllElements();
- st = new StringTokenizer(appProperties.getProperty("quick_links_menu_ids"), ",");
- while(st.hasMoreTokens())
- quickLinksMenuIDs.add(st.nextToken());
- } catch(Exception e) {
- logger.error(EELFLoggerDelegate.debugLogger, ("[EXCEPTION ENCOUNTERED IN RAPTOR] AppUtils.initializeAppUtils: Unable to load properties ["+Globals.getSystemType()+"_"+ConfigLoader.APP_PROPERTIES+"]. Exception: "+e.getMessage()));
- //throw new RuntimeException(e.getMessage());
- }
- } // initializeAppUtils
-
- public static void getFullURL(HttpServletRequest req) {
- String applicationBase = "";
- if (applicationBase == null) {
- applicationBase = req.getScheme() + "://" + req.getServerName() +
- getPort(req) + req.getContextPath();
- }
- }
-
- private static String getPort(HttpServletRequest req) {
- if ("http".equalsIgnoreCase(req.getScheme()) && req.getServerPort() != 80 ||
- "https".equalsIgnoreCase(req.getScheme()) && req.getServerPort() != 443 ) {
- return (":" + req.getServerPort());
- } else {
- return "";
- }
- }
- public String getUserID(HttpServletRequest request) {
- String pdfAttachmentKey = org.openecomp.portalsdk.analytics.system.AppUtils.getRequestValue(request, "pdfAttachmentKey");
- String report_email_sent_log_id = org.openecomp.portalsdk.analytics.system.AppUtils.getRequestValue(request, "log_id");
- boolean isEmailAttachment = false;
- if(pdfAttachmentKey != null && report_email_sent_log_id !=null)
- isEmailAttachment = true;
- if(isEmailAttachment) {
- return RaptorAdapter.getUserID(org.openecomp.portalsdk.analytics.system.AppUtils.getRequestValue(request, "user_id"));
- } else
- return RaptorAdapter.getUserID(request);
- } // getUserID
-
- public Vector getAllUsers(String customizedQuery, String param, boolean isAdmin) {
- Map map = RaptorAdapter.getAllUsers(customizedQuery, param, isAdmin);
-
- Vector vector = new Vector(map.size());
- for(Iterator iter=map.keySet().iterator(); iter.hasNext(); ) {
- Long key = (Long) iter.next();
- vector.add(new IdNameValue(""+key, (String) map.get(key)));
- } // for
-
- return vector;
- } // getAllUsers
-
- public String getRoleName(String roleId) {
- return RaptorAdapter.getRoleName(roleId);
- } // getRoleName
-
- public Vector getAllRoles(String customizedQuery, String param, boolean isAdmin) {
- Map map = RaptorAdapter.getAllRolesUsingCustomizedQuery(customizedQuery, param, isAdmin);
-
- Vector vector = new Vector(map.size());
- for(Iterator iter=map.keySet().iterator(); iter.hasNext(); ) {
- Long key = (Long) iter.next();
- vector.add(new IdNameValue(""+key, (String) map.get(key)));
- } // for
-
- return vector;
- } // getAllRoles
-
- public String getUserName(HttpServletRequest request) {
- return RaptorAdapter.getUserName(request);
- } // getUserName
-
- public String getUserName(String userId) {
- return RaptorAdapter.getUserName(userId);
- } // getUserName
-
- public String getUserEmail(String userId) {
- return RaptorAdapter.getUserEmail(userId);
- } // getUserEmail
-
- public String getUserEmail(HttpServletRequest request) {
- return RaptorAdapter.getUserEmail(request);
- } // getUserEmail
-
- public String getUserLoginId(HttpServletRequest request) {
- return RaptorAdapter.getUserLoginId(request);
- } // getUserLoginId
-
- public String getUserLoginId(String userId) {
- return RaptorAdapter.getUserLoginId(userId);
- } // getUserLoginId
-
- public String getUserBackdoorLoginId(HttpServletRequest request) {
- String pdfAttachmentKey = org.openecomp.portalsdk.analytics.system.AppUtils.getRequestValue(request, "pdfAttachmentKey");
- String report_email_sent_log_id = org.openecomp.portalsdk.analytics.system.AppUtils.getRequestValue(request, "log_id");
- boolean isEmailAttachment = false;
- if(pdfAttachmentKey != null && report_email_sent_log_id !=null)
- isEmailAttachment = true;
- if(isEmailAttachment) {
- return RaptorAdapter.getUserBackdoorLoginId(org.openecomp.portalsdk.analytics.system.AppUtils.getRequestValue(request, "user_id"));
- } else
- return RaptorAdapter.getUserBackdoorLoginId(request);
- } // getUserBackdoorLoginId
-
- public boolean isUserInRole(HttpServletRequest request, String roleId) {
- return RaptorAdapter.isCurrentUserInRole(request, roleId);
- } // isUserInRole
-
- public Vector getUserRoles(HttpServletRequest request) {
-// Map map = RaptorAdapter.getAllRoles(userId);
- Set set = RaptorAdapter.getUserRoles(request);
-
- Vector vector = new Vector(set.size());
- for(Iterator iter=set.iterator(); iter.hasNext(); ) {
- Long key = (Long) iter.next();
- vector.add(""+key);
- //vector.add(new IdNameValue(""+key, (String) map.get(key)));
- } // for
-
- return vector;
- } // getUserRoles
-
- public Vector getUserRoles(String userId) {
- Set set = RaptorAdapter.getUserRoles(userId);
-
- Vector vector = new Vector(set.size());
- for(Iterator iter=set.iterator(); iter.hasNext(); ) {
- Long key = (Long) iter.next();
- vector.add(""+key);
- //vector.add(new IdNameValue(""+key, (String) map.get(key)));
- } // for
-
- return vector;
- //return null;
- } // getUserRoles
-
- public void resetUserCache() {
- //org.openecomp.portalsdk.core.web.support.AppUtils.removeObjectFromCache(RaptorAdapter.KEY_USER_ROLES_CACHE);
- } // resetUserCache
-
- public String getSuperRoleID(){
- return superRoleID;
- } // getSuperRoleID
-
- public Vector getAdminRoleIDs(){
- return adminRoleIDs;
- } // getAdminRoleIDs
-
-
- public String getTempFolderPath() {
- return tempFolderPath;
- } // getTempFolderPath
-
- public String getUploadFolderPath() {
- return uploadFolderPath;
- } // getUploadFolderPath
-
- public String getTempFolderURL() {
- return tempFolderURL;
- } // getTempFolderURL
-
- public String getUploadFolderURL() {
- return uploadFolderURL;
- } // getUploadFolderURL
-
- public String getSMTPServer() {
- return SMTPServer;
- } // getSMTPServer
-
- public String getDefaultEmailSender() {
- return defaultEmailSender;
- } // getDefaultEmailSender
-
- public String getErrorPage() {
- return errorPage;
- } // getErrorPage
-
- public String getJspContextPath() {
- return jspContextPath;
- } // getJspContextPath
-
- public String getImgFolderURL() {
- return imgFolderURL;
- } // getImgFolderURL
-
- public String getBaseFolderURL() {
- return baseFolderURL;
- } // getBaseFolderURL
-
-/* public String getReportExecuteActionURL() {
- return reportExecuteActionURL;
- } // getReportExecuteActionURL
-
- public String getDataViewActionURL() {
- return dataViewActionURL;
- } // getDataViewActionURL
-
- public String getDataViewActionParam() {
- return dataViewActionParam;
- } // getDataViewActionParam
-*/
- public String getDirectAccessURL() {
- return directAccessURL.trim();
- } // getDirectAccessURL
-
- public String getBaseActionURL() {
- return baseActionURL;
- } // getBaseActionURL
-
- public String getBaseActionURLNG() {
- return baseActionURLNG;
- } // getBaseActionURLNG
-
- public String getDrillActionURL() {
- return drillActionURL;
- } // getBaseActionURL
-
- public String getBaseActionParam() {
- return baseActionParam;
- } // getBaseActionParam
-
- public Vector getQuickLinksMenuIDs(){
- return quickLinksMenuIDs;
- } // getQuickLinksMenuIDs
-
- public String getMenuLabel(String menuId) {
- //return menuId.substring(0, 1).toUpperCase()+menuId.substring(1).toLowerCase();
- return menuId;
- } // getMenuLabel
-
- public String getReportDbColsMaskSQL() {
- return null;
-/* Example:
- return "SELECT f.table_name, UPPER(f.column_name) column_name, f.label "+
- "FROM fields f WHERE f.active_yn = 'Y'"; */
- } // getReportDbColsMaskSQL
-
- public String getReportDbLookupsSQL() {
- return null;
-/* Example:
- return "SELECT DISTINCT f.table_name, UPPER(f.column_name) column_name, f.lookup_table, f.lookup_id_field, f.lookup_name_field "+
- "FROM fields f WHERE f.active_yn = 'Y'"; */
- } // getReportDbLookupsSQL
-
- public void processErrorNotification(HttpServletRequest request, RaptorException e) {
- //RaptorAdapter.processErrorNotification(request, e);
-} // processErrorNotification
-
- public String getErrorPageWMenu() {
- return errorPageWMenu;
- }
-
- public String getExcelTemplatePath() {
- return nvls(raptorAppProperties.getProperty("excel_template_path"), "");
- }
- /**
- * @return the encryptedSMTPServer
- */
- public String getEncryptedSMTPServer() {
- return encryptedSMTPServer;
- }
-
- public String getFolderPathAdj(){
- return nvls(raptorAppProperties.getProperty("folder_path_adj"), "");
- }
-
-} // AppUtils
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion;
-
-import java.sql.*;
-import java.util.*;
-
-import javax.servlet.*;
-
-import org.openecomp.portalsdk.analytics.config.*;
-import org.openecomp.portalsdk.analytics.system.*;
-import org.openecomp.portalsdk.analytics.system.fusion.adapter.FusionAdapter;
-import org.openecomp.portalsdk.analytics.system.fusion.adapter.RaptorAdapter;
-import org.openecomp.portalsdk.analytics.system.fusion.adapter.SpringContext;
-import org.openecomp.portalsdk.analytics.util.*;
-import org.springframework.beans.factory.annotation.Autowired;
-
-
-
-public class DbUtils implements IDbUtils {
-
- @Autowired
- public RaptorAdapter raptorAdapter;
- @Autowired
- public FusionAdapter fusionAdapter;
-
- public DbUtils() {}
-
- public void initializeDbUtils(ServletContext servletContext) {
- raptorAdapter = (RaptorAdapter)SpringContext.getApplicationContext().getBean("raptorAdapter");
- } // initializeDbUtils
-
- public Connection getConnection() {
- return raptorAdapter.getConnection();
- } // getConnection
-
- public void clearConnection(Connection con) {
- raptorAdapter.releaseConnection(con);
- } // clearConnection
-
- public RaptorAdapter getRaptorAdapter() {
- return raptorAdapter;
- }
-
- public void setRaptorAdapter(RaptorAdapter raptorAdapter) {
- this.raptorAdapter = raptorAdapter;
- }
-
- public FusionAdapter getFusionAdapter() {
- return fusionAdapter;
- }
-
- public void setFusionAdapter(FusionAdapter fusionAdapter) {
- this.fusionAdapter = fusionAdapter;
- }
-
-
-
-
-
-} // DbUtils
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion;
-
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-import javax.servlet.ServletContext;
-
-import org.openecomp.portalsdk.analytics.error.ReportSQLException;
-import org.openecomp.portalsdk.analytics.system.RDbUtils;
-import org.openecomp.portalsdk.analytics.system.fusion.adapter.RaptorAdapter;
-import org.openecomp.portalsdk.analytics.system.fusion.adapter.SpringContext;
-import org.openecomp.portalsdk.analytics.util.DataSet;
-import org.openecomp.portalsdk.analytics.util.Log;
-import org.springframework.beans.factory.annotation.Autowired;
-
-
-
-public class RemoteDbUtils implements RDbUtils{
-
- private RaptorAdapter raptorAdapter;
-
-
- public void initializeDbUtils(ServletContext servletContext) {
- raptorAdapter = (RaptorAdapter)SpringContext.getApplicationContext().getBean("raptorAdapter");
- } // initializeDbUtils
-
-
- public Connection getRemoteConnection(String dbKey) {
- return raptorAdapter.getConnection(dbKey);
- }
-
- public void clearConnection(Connection conn) {
- raptorAdapter.releaseConnection(conn);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.adapter;
-
-import java.util.*;
-
-public class AdapterSessionFactoryContainer {
-
- private LinkedHashMap sessionFactories;
-
- public AdapterSessionFactoryContainer() {
- }
-
- public LinkedHashMap getSessionFactories() {
- return sessionFactories;
- }
-
- public void setSessionFactories(LinkedHashMap sessionFactories) {
- this.sessionFactories = sessionFactories;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.adapter;
-
-
-import java.io.Serializable;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.List;
-import java.util.TimeZone;
-
-import org.openecomp.portalsdk.core.FusionObject;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-
-
-public class DateUtils implements Serializable, FusionObject{
-
- public static final String US_PACIFIC = "US/Pacific";
- public static final String US_MOUNTAIN = "US/Mountain";
- public static final String US_CENTRAL = "US/Central";
- public static final String US_EASTERN = "US/Eastern";
- public static final String US_HAWAII = "US/Hawaii";
- public static final String US_ALASKA = "US/Alaska";
-
- //Arizona State has Mountain Time with no Daylight Savings
- public static final String US_ARIZONA = "America/Phoenix";
-
- private static final String DB_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
- private static final String GET_CURRENT_DATE = "getCurrentDate";
-
- private static DataAccessService dataAccessService;
-
- public static DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- /**
- * Parses a date value with given pattern,
- * to return a Date Object
- *
- * @param dateValue
- * @param inPattern
- * @return Date Object
- * @throws Exception
- *
- */
- public static Date parseDate(String dateValue,String inPattern) throws Exception{
- return parseDate(dateValue,inPattern,null);
- }
-
- /**
- * Parses a date value with the given pattern for the specific TimeZone,
- * to return a Date Object
- *
- * @param dateValue
- * @param inPattern
- * @param currentTimeZone
- * @return Date Object
- * @throws Exception
- *
- */
- public static Date parseDate(String dateValue,String inPattern,
- String currentTimeZone) throws Exception{
- DateFormat df = new SimpleDateFormat(inPattern);
- if(currentTimeZone !=null && !(currentTimeZone.trim().equals(""))){
- df.setTimeZone(TimeZone.getTimeZone(currentTimeZone));
- }
- Date date = df.parse(dateValue);
- return date;
- }
-
- /**
- * Parses a date value with the given pattern for the specific User(in User TimeZone),
- * to return a Date Object
- *
- * @param dateValue
- * @param inPattern
- * @param userId
- * @return Date Object
- * @throws Exception
- *
- */
- public static Date parseUserDate(String dateValue, String inPattern, Long userId) throws Exception{
- User user = (User)getDataAccessService().getDomainObject(User.class, userId, null);
-
- String userTimeZone = null;
- Long timezoneId = user.getTimeZoneId();
-
- if (timezoneId != null) {
- userTimeZone = AppUtils.getLookupValueByLabel(timezoneId.toString(), "fn_lu_timezone", "timezone_id", "timezone_value");
- }
-
- return parseDate(dateValue,inPattern,userTimeZone);
- }
-
- /**
- * Formats a given date object to the desired pattern
- *
- * @param date
- * @param outPattern
- * @return Formatted date value
- * @throws Exception
- */
- public static String formatDate(Date date,String outPattern)throws Exception{
- return formatDate(date,outPattern,null);
- }
-
- /**
- * Formats a date value with the given pattern into a date value with the desired pattern
- *
- * @param dateValue
- * @param inPattern
- * @param outPattern
- * @return Formatted date value
- * @throws Exception
- *
- */
- public static String formatDate(String dateValue,String inPattern,
- String outPattern) throws Exception{
- return formatDate(dateValue,inPattern,null,outPattern,null);
- }
-
- /**
- * Formats a given date object to the desired pattern for the TimeZone provided
- * @param date
- * @param outPattern
- * @param requiredTimeZone
- * @return Formatted date value
- * @throws Exception
- */
- public static String formatDate(Date date,String outPattern,
- String requiredTimeZone) throws Exception{
- DateFormat df = new SimpleDateFormat(outPattern);
- if(requiredTimeZone != null && !requiredTimeZone.trim().equals("")){
- df.setTimeZone(TimeZone.getTimeZone(requiredTimeZone));
- }
- return df.format(date);
- }
-
- /**
- * Formats a date value with the given pattern
- * into a date value with the desired pattern for the TimeZone provided
- *
- * @param dateValue
- * @param inPattern
- * @param outPattern
- * @param requiredTimeZone
- * @return Formatted date value
- * @throws Exception
- *
- */
- public static String formatDate(String dateValue,String inPattern,
- String outPattern,String requiredTimeZone) throws Exception{
- return formatDate(dateValue,inPattern,null,outPattern,requiredTimeZone);
- }
-
- /**
- * Formats a date value with the given pattern for a specific TimeZone,
- * into a date value with the desired pattern for the TimeZone provided
- *
- * @param dateValue
- * @param inPattern
- * @param currentTimeZone
- * @param outPattern
- * @param requiredTimeZone
- * @return Formatted date value
- * @throws Exception
- *
- */
- public static String formatDate(String dateValue,String inPattern,String currentTimeZone,
- String outPattern,String requiredTimeZone) throws Exception{
- Date date = parseDate(dateValue,inPattern,currentTimeZone);
- return formatDate(date,outPattern,requiredTimeZone);
- }
-
- /**
- * Formats a date value with the given pattern, for a specific User(in User TimeZone),
- * into a date value with the desired pattern for the TimeZone provided
- *
- * @param dateValue
- * @param inPattern
- * @param userId
- * @param outPattern
- * @param requiredTimeZone
- * @return Formatted date value
- * @throws Exception
- *
- */
- public static String formatUserDate(String dateValue,String inPattern, Long userId,String outPattern,String requiredTimeZone) throws Exception{
- User user = (User)getDataAccessService().getDomainObject(User.class, userId, null);
-
- String userTimeZone = null;
- Long timezoneId = user.getTimeZoneId();
-
- if (timezoneId != null) {
- userTimeZone = AppUtils.getLookupValueByLabel(timezoneId.toString(), "fn_lu_timezone", "timezone_id", "timezone_value");
- }
-
- return formatDate(dateValue,inPattern,userTimeZone,outPattern,requiredTimeZone);
- }
-
- /**
- * Formats a date value with a given pattern for a specific User(User TimeZone),
- * into a date value with the desired pattern for Database TimeZone
- *
- * @param dateValue
- * @param inPattern
- * @param userId
- * @param outPattern
- * @return Formatted date value
- * @throws Exception
- *
- */
- public static String formatUserDateForDBTimeZone(String dateValue,String inPattern, Long userId,String outPattern) throws Exception{
- User user = (User)getDataAccessService().getDomainObject(User.class, userId, null);
-
- String userTimeZone = null;
- Long timezoneId = user.getTimeZoneId();
-
- /*if (timezoneId != null) {
- userTimeZone = AppUtils.getLookupValueByLabel(timezoneId.toString(), "fn_lu_timezone", "timezone_id", "timezone_value");
- }*/
-
- String dbTimeZone = SystemProperties.getProperty(SystemProperties.DATABASE_TIME_ZONE);
-
- return formatDate(dateValue,inPattern,userTimeZone,outPattern,dbTimeZone);
- }
-
- /**
- * Get the current database Date/Time
- * @return Date object
- */
- public static Date getCurrentDBDate()throws Exception{
- String dbTimeZone = SystemProperties.getProperty(SystemProperties.DATABASE_TIME_ZONE);
- List results = (List)getDataAccessService().executeNamedQuery(GET_CURRENT_DATE, null, null);
- return parseDate(((Object[])results.get(0))[0]+" "+((Object[])results.get(0))[1],DB_DATE_FORMAT,dbTimeZone);
- }
-
- /**
- * Get the current date value formatted for the User's TimeZone in the desired pattern
- *
- * @param outPattern
- * @param userId
- * @return Date value
- * @throws Exception
- */
- public static String getCurrentDBDateForUser(String outPattern,Long userId)throws Exception{
- User user = (User)getDataAccessService().getDomainObject(User.class, userId, null);
-
- String userTimeZone = null;
- Long timezoneId = user.getTimeZoneId();
-
- /*if (timezoneId != null) {
- userTimeZone = AppUtils.getLookupValueByLabel(timezoneId.toString(), "fn_lu_timezone", "timezone_id", "timezone_value");
- }*/
-
- Date dbDate = getCurrentDBDate();
-
- return formatDate(dbDate,outPattern,userTimeZone);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.adapter;
-
-import java.sql.*;
-import java.util.*;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.servlet.*;
-
-import com.mchange.v2.c3p0.ComboPooledDataSource;
-
-import org.hibernate.SessionFactory;
-import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
-import org.hibernate.engine.spi.SessionFactoryImplementor;
-import org.hibernate.engine.spi.SessionImplementor;
-import org.openecomp.portalsdk.core.FusionObject;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-
-public class FusionAdapter implements FusionObject {
-
- public static final String LOCAL_SESSION_FACTORY_KEY = "local";
-
-
- private ComboPooledDataSource dataSource;
- private Map<String,ComboPooledDataSource> dataSourceMap;
-
- //private SessionFactory sessionFactory;
- private ServletContext servletContext;
-
- public FusionAdapter() {
- }
-
-
- public ServletContext getServletContext() {
- return servletContext;
- }
-
- public void setServletContext(ServletContext servletContext) {
- this.servletContext = servletContext;
- }
-
- /** Gets connection to the database **/
- public Connection getConnection() {
- Connection connection = null;
- try {
- connection = getDataSource().getConnection();
- } catch(Exception ex) {
- ex.printStackTrace();
- }
- return connection;
- }
-
-
- /** Gets connection to the database indicated via the session factory key **/
- public synchronized Connection getConnection(String schemaId) {
- Connection connection = null;
- try {
- connection = getDataSourceMap().get(schemaId).getConnection();
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return connection;
- }
-
-
- /** Releases connection to the database **/
- public void releaseConnection(Connection conn) {
- try {
- conn.close();
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
- public ComboPooledDataSource getDataSource() {
- return dataSource;
- }
-
-
- @Autowired
- public void setDataSource(ComboPooledDataSource dataSource) {
- this.dataSource = dataSource;
- }
-
- public Map<String,ComboPooledDataSource> getDataSourceMap() {
- if(dataSourceMap==null)
- dataSourceMap = (Map<String,ComboPooledDataSource>)SpringContext.getApplicationContext().getBean("dataSourceMap");
-
- return dataSourceMap;
- }
-
- public void setdataSourceMap(Map<String,ComboPooledDataSource> dataSourceMap) {
- this.dataSourceMap = dataSourceMap;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.adapter;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-/**
- * <p>IdName.java</p>
- * <p>Represents a id/name data object.</p>
-*/
-@Entity
-public class IdName extends DomainVo {
-
- private String name;
- private Long id;
-
- public IdName() {}
-
- @Id
- @GeneratedValue
- @Column(name = "ID", unique = true, nullable = false)
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int compareTo(Object obj){
- String c1 = getName();
- String c2 = ((IdName)obj).getName();
-
- return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.adapter;
-
-
-public class Item {
- private String _id;
- private String _name;
-
- public Item() {
- }
-
- public Item(String id, String name) {
- this._id = id;
- this._name = 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;
- }
-
- public String toString() {
- return _name;
- }
-}
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.adapter;
-
-
-import java.io.*;
-
-import org.openecomp.portalsdk.core.domain.FusionVo;
-import org.openecomp.portalsdk.core.domain.support.NameValueId;
-
-
-
-public class Lookup extends FusionVo implements Serializable {
-
- private NameValueId nameValueId = new NameValueId();
-
- public Lookup() {}
-
- public Lookup(String label, String value) {
- this();
- setLabel(label);
- setValue(value);
- }
-
- public String getValue() {
- return getNameValueId().getVal();
- }
-
- public String getLabel() {
- return getNameValueId().getLab();
- }
-
- public void setValue(String value) {
- getNameValueId().setVal(value);
- }
-
- public void setLabel(String label) {
- getNameValueId().setLab(label);
- }
-
- public NameValueId getNameValueId() {
- return nameValueId;
- }
-
- public void setNameValueId(NameValueId nameValueId) {
- this.nameValueId = nameValueId;
- }
-
- // required by ZK for to set the selectedItems of Listboxes (used heavily for <select>-style drop-downs)
- public int hashCode() {
- int hash = getValue().hashCode();
- hash = hash + getLabel().hashCode();
-
- return hash;
- }
-
- public boolean equals( Object obj ) {
- boolean equivalent = false;
-
- Lookup lookup = (Lookup)obj;
- if( lookup.getValue().equals(getValue()) && lookup.getLabel().equals(getLabel())) {
- equivalent = true;
- }
-
- return equivalent;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.adapter;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
-import org.openecomp.portalsdk.analytics.system.AppUtils;
-import org.openecomp.portalsdk.core.domain.Menu;
-import org.openecomp.portalsdk.core.domain.MenuData;
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-@Service("raptorAdapter")
-public class RaptorAdapter extends FusionAdapter {
-
- @Autowired
- private static DataAccessService dataAccessService;
-
- static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RaptorAdapter.class);
-
-
- public static final int RAPTOR_USER_ID = 20000; // RAPTOR system user id (for auditing purposes)
- public static final String RAPTOR_CONTROLLER_CLASSNAME = "org.openecomp.portalsdk.analytics.controller.Controller";
- public static final String KEY_USER_ROLES_CACHE = "userRoles";
-
- public void initializeRaptor() {
- org.openecomp.portalsdk.analytics.config.ConfigLoader.setConfigFilesPath(SystemProperties.getProperty(SystemProperties.RAPTOR_CONFIG_FILE_PATH));
- org.openecomp.portalsdk.analytics.system.Globals.initializeSystem(getServletContext());
- }
-
-
- /** Returns ID of the user currently logged in */
- public static String getUserID(HttpServletRequest request) {
- return String.valueOf(UserUtils.getUserId(request));
- //return null;
- }
-
- public static String getUserID(String user_id) {
- return user_id;
- }
-
-
- public static String getUserBackdoorLoginId(HttpServletRequest request) {
- if(AppUtils.getRequestNvlValue(request, "login_id").length()>0) return AppUtils.getRequestNvlValue(request, "login_id");
- return String.valueOf(UserUtils.getUserSession(request).getLoginId());
- }
-
- public static String getUserBackdoorLoginId(String user_id) {
- return getUserLoginId(user_id);
- }
-
- /** Obtains user name by ID */
- public static String getUserName(String userId) {
- Map<String, Long> params = new HashMap<String, Long>();
- params.put("user_id", new Long(userId));
-
- List list = getDataAccessService().executeNamedQuery("getUserNameById", params, null);
-
- String firstName = "";
- String lastName = "";
-
- if (list != null) {
- if (!list.isEmpty()) {
- Object[] user = (Object[]) list.get(0);
- firstName = (String) user[0]; // firstName scalar
- lastName = (String) user[1]; // lastName scalar
- }
- }
-
- return lastName + ", " + firstName;
- }
-
- public static String getUserName(HttpServletRequest request) {
- User user = UserUtils.getUserSession(request);
- return user.getLastName() + ", " + user.getFirstName();
- }
-
- public static String getUserEmail(String userId) {
- Map<String, Long> params = new HashMap<String, Long>();
- params.put("user_id", new Long(userId));
- List list = getDataAccessService().executeNamedQuery("getUserEmail", params, null);
- String email = "";
- if (list != null && !list.isEmpty())
- email = (String) list.get(0);
- return email;
- }
-
- public static String getUserEmail(HttpServletRequest request) {
- User user = UserUtils.getUserSession(request);
- return user.getEmail();
- }
-
- public static String getUserLoginId(String userId) {
-
- String loginId = "";
- try{
- List list = getDataAccessService().getList(User.class, " where user_id = " + userId, null, null);
- if (list != null) {
- if (!list.isEmpty()) {
- User user = (User)list.get(0);
- loginId = user.getLoginId(); // firstName scalar
- }
- }
- }catch(Exception e){
- logger.error(EELFLoggerDelegate.debugLogger, ("error while getting login id : Exception" + e.getMessage()));
- }
- return loginId;
- }
-
-
- public static String getUserLoginId(HttpServletRequest request) {
- User user = UserUtils.getUserSession(request);
- return user.getLoginId();
- }
-
- /** Obtains list of all users (in IdNameValue objects) */
- public static Map<Long, String> getAllUsers(String customizedQuery, String param, boolean isAdmin) {
- List users = null;
- Map<Long, String> map = new LinkedHashMap<Long, String>();
-
- if(customizedQuery.length()>0 && !isAdmin) {
-
- users = getDataAccessService().executeSQLQuery(customizedQuery, IdName.class, null);
-
- if (users != null) {
- Iterator i = users.iterator();
- while (i.hasNext()) {
- IdName item = (IdName)i.next();
- map.put(item.getId(), item.getName());
- }
- }
-
- } else {
- users = getDataAccessService().executeNamedQuery("getAllUsers", null, null);
- if (users != null) {
- Iterator i = users.iterator();
- while (i.hasNext()) {
- Object[] user = (Object[])i.next();
- Long id = (Long)user[0]; // id scalar
- String firstName = (String)user[1]; // firstName scalar
- String lastName = (String)user[2]; // lastName scalar
- map.put(id, lastName + ", " + firstName);
- }
- }
- }
- return map;
- }
-
- /** Obtains role name by ID */
- public static String getRoleName(String roleId) {
- Map<String, Long> params = new HashMap<String, Long>();
- params.put("role_id", new Long(roleId));
-
- List list = getDataAccessService().executeNamedQuery("getRoleNameById", params, null);
-
- String roleName = "";
-
- if (list != null) {
- if (!list.isEmpty()) {
- roleName = (String) list.get(0); // name scalar
- }
- }
-
- return roleName;
- }
-
- /** Obtains list of all roles (in IdNameValue objects) */
- public static Map<Long, String> getAllRolesUsingCustomizedQuery(String customizedQuery, String param, boolean isAdmin) {
- List roles = null;
-
- Map<Long, String> map = new LinkedHashMap<Long, String>();
-
- if(customizedQuery.length()>0 && !isAdmin) {
-
- roles = getDataAccessService().executeSQLQuery(customizedQuery, IdName.class, null);
-
- if (roles != null) {
- Iterator i = roles.iterator();
- while (i.hasNext()) {
- IdName item = (IdName)i.next();
- map.put(item.getId(), item.getName());
- }
- }
- } else {
-
- roles = getDataAccessService().executeNamedQuery("getAllRoles", null, null);
-
- if (roles != null) {
- Iterator i = roles.iterator();
- while (i.hasNext()) {
- Object[] role = (Object[])i.next();
- Long id = (Long)role[0]; // id scalar
- String name = (String)role[1]; // firstName scalar
- map.put(id, name);
- }
- }
- }
-
- return map;
- }
-
- public static Set getUserRoles(HttpServletRequest request) {
- return UserUtils.getRoles(request).keySet();
- }
-
- public static Set getUserRoles(String userId) {
- Set userRoles = new HashSet<Long>();
-// Map usersRolesMap = new LinkedHashMap<Long, Set>();
-// Map<String, Long> params = new HashMap<String, Long>();
-//
-// params.put("user_id", new Long(userId));
-//
-// List usersRolesList = getDataAccessService().executeNamedQuery("getAllUsersRoles", params, null);
-// Iterator i = usersRolesList.iterator();
-// while (i.hasNext()) {
-// Object[] userRole = (Object[]) i.next();
-//
-// Long roleId = (Long) userRole[1]; // role id scalar
-// userRoles.add(roleId);
-//
-// }
- userRoles = getActiveUsersRoleIds(new Long(userId));
-
-
- return userRoles;
- }
-
- /** this is used to get role for the current user. **/
- public static synchronized boolean isCurrentUserInRole(HttpServletRequest request, String roleId) {
- HttpSession session = request.getSession(false);
- if(session!=null && session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME))!=null)
- return UserUtils.hasRole(request, roleId);
- else
- return false;
- }
-
- // public static void processErrorNotification(HttpServletRequest request, Exception e) {
- //org.openecomp.portalsdk.core.web.support.AppUtils.processError(e, logger, request);
- //}
-
- /** Obtains menu label by ID */
- public static String getMenuLabel(String menuId) {
- return ((Menu) getDataAccessService().getDomainObject(MenuData.class, new Long(menuId), null)).getLabel();
- }
-
- public static String formatUserDateForDBTimeZone(String dateValue,String inPattern,
- Long userId, String outPattern)throws Exception{
- return DateUtils.formatUserDateForDBTimeZone(dateValue,inPattern,userId,outPattern);
- }
-
- public static String getCurrentDBDateForUser(String inPattern,Long userId)throws Exception{
- return DateUtils.getCurrentDBDateForUser(inPattern, userId);
- }
-
- public static Set<Long> getActiveUsersRoleIds(Long userId) {
- Set<Role> allActiveUserRoles = getActiveUserRoles(userId);
- Iterator<Role> allActiveUserRolesIterator = allActiveUserRoles.iterator();
- Set<Long> allActiveUserRoleIds = new TreeSet<Long>();
- while(allActiveUserRolesIterator.hasNext()){
- Role role = allActiveUserRolesIterator.next();
- allActiveUserRoleIds.add(role.getId());
- }
-
- return allActiveUserRoleIds;
- }
-
- public static Set<Long> getActiveUserRoleIds(Long userId) {
- Set<Role> allActiveUserRoles = getActiveUserRoles(userId);
- Iterator<Role> allActiveUserRolesIterator = allActiveUserRoles.iterator();
- Set<Long> allActiveUserRoleIds = new TreeSet<Long>();
- while(allActiveUserRolesIterator.hasNext()){
- Role role = allActiveUserRolesIterator.next();
- allActiveUserRoleIds.add(role.getId());
- }
-
- return allActiveUserRoleIds;
- }
-
- public static Set<RoleFunction> getActiveRoleFunctions(Long userId) {
- Set<Role> allActiveUserRoles = getActiveUserRoles(userId);
- Iterator<Role> allActiveUserRolesIterator = allActiveUserRoles.iterator();
- Set<RoleFunction> allActiveRoleFunctions = new TreeSet<RoleFunction>();
- while(allActiveUserRolesIterator.hasNext()){
- Role role = allActiveUserRolesIterator.next();
- allActiveRoleFunctions.addAll(role.getRoleFunctions());
- }
-
- return allActiveRoleFunctions;
- }
-
- public static Set<Role> getActiveUserRoles(Long userId) {
- User user = (User)getDataAccessService().getDomainObject(User.class,userId,null);
- Set<Role> allActiveUserRoles = new TreeSet<Role>();
- allActiveUserRoles.addAll(user.getRoles());
- Iterator<Role> userRolesIterator = user.getRoles().iterator();
- while(userRolesIterator.hasNext()){
- getAllChildRoles( userRolesIterator.next(),allActiveUserRoles);
- }
-
- Iterator<Role> allActiveUserRolesIterator = allActiveUserRoles.iterator();
- while(allActiveUserRolesIterator.hasNext()){
- Role role = allActiveUserRolesIterator.next();
- if(!role.getActive()){
- allActiveUserRolesIterator.remove();
- }
- }
-
- return allActiveUserRoles;
- }
-
- public static Set<Role> getAllChildRoles(Role role, Set<Role> allchildRoles) {
- Set<Role> childRoles = role.getChildRoles();
- allchildRoles.addAll(childRoles);
- Iterator<Role> childRolesIterator = childRoles.iterator();
- while (childRolesIterator.hasNext()) {
- getAllChildRoles(childRolesIterator.next(),allchildRoles);
- }
- return allchildRoles;
- }
-
-
- public static DataAccessService getDataAccessService() {
- return org.openecomp.portalsdk.core.web.support.AppUtils.getDataAccessService();
- }
-
-
- public static void setDataAccessService(DataAccessService dataAccessService) {
- dataAccessService = dataAccessService;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.adapter;
-
-import org.springframework.beans.BeansException;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.stereotype.Component;
-
-@Component("springContext")
-public class SpringContext implements ApplicationContextAware {
- private static ApplicationContext context;
-
- public void setApplicationContext(ApplicationContext context) throws BeansException {
- this.context = context;
- }
- public static ApplicationContext getApplicationContext() {
- return context;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.controller;
-/**
- * Raptor Blob Extract Servlet
- *
- */
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.sql.Blob;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.springframework.web.servlet.ModelAndView;;
-
-
-public class FileServletController {
-
- private DataAccessService dataAccessService;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FileServletController.class);
-
-
- public ModelAndView handleRequestInternal(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- logger.debug(EELFLoggerDelegate.debugLogger, ("FileServletController:: f=" + request.getParameter("f")));
-
- String fname = request.getParameter("f");
-
- try {
- Map params = new HashMap();
- params.put("fname", fname);
-
- logger.debug(EELFLoggerDelegate.debugLogger, ("executing query: select file_blob from cr_report_file_history where file_name = :"
- + fname));
-
- List<Object> fileFromDB = (List<Object>) getDataAccessService().executeNamedQuery("getFileWithName", params, null);
-
- byte[] allBytesInBlob = null;
-
- if (fileFromDB != null && fileFromDB.size() > 0) {
-
- logger.debug(EELFLoggerDelegate.debugLogger, ("reading file blob from DB..."));
- try {
-
- /*for weblogic setup
- * if(Globals.isWeblogicServer()) {
- weblogic.jdbc.vendor.oracle.OracleThinBlob aBlob = (weblogic.jdbc.vendor.oracle.OracleThinBlob) ((org.hibernate.lob.SerializableBlob) fileFromDB
- .get(0)).getWrappedBlob();
- InputStream inBlob = ((java.sql.Blob) aBlob).getBinaryStream();
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buf = new byte[1024];
- int n = 0;
- while ((n=inBlob.read(buf))>=0) {
- baos.write(buf, 0, n);
- }
- inBlob.close();
- allBytesInBlob = baos.toByteArray();
- } else { */
- /* works in Hinernate3 [ oracle.sql.BLOB aBlob = (oracle.sql.BLOB) ((org.hibernate.lob.SerializableBlob) fileFromDB
- .get(0)).getWrappedBlob();
- allBytesInBlob = aBlob.getBytes(1, (int) aBlob.length()); ] */
- // }
-
- Object fileFromDBType = fileFromDB.get(0);
- if(fileFromDBType instanceof byte[] ) // postgres
- allBytesInBlob = (byte[]) fileFromDB.get(0);
- else if (fileFromDBType instanceof Blob ) // oracle
- allBytesInBlob = ((Blob) fileFromDB.get(0)).getBytes(1, (int) ((Blob) fileFromDB.get(0)).length());
-
-
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.debugLogger, ("An exception has occurred: " + e.getMessage()));
- throw (e);
- }
-
- } else {
- logger.error(EELFLoggerDelegate.debugLogger, ("ERROR: No BLOB returned from DB..."));
- throw (new Exception("ERROR: No BLOB returned from DB..."));
- }
-
- serveFile(response, allBytesInBlob, fname);
- return null;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.debugLogger, ("Exception occurred..." + e.getMessage()));
- Map<String, Object> errView = new HashMap<String, Object>();
- errView.put("error", "The requested resource was not found.");
- //return new ModelAndView(getExceptionView(), "model", errView);
- return null;
- }
-
- }
-
- private void serveFile(HttpServletResponse response, File inFile)
- throws Exception {
- OutputStream os = null;
- InputStream is = null;
- try {
- response.reset();
- is = new BufferedInputStream(new FileInputStream(inFile));
- os = new BufferedOutputStream(response.getOutputStream());
- response.setContentLength((int) inFile.length());
- response.setContentType("application/octet-stream");
- response.setHeader("Content-disposition", "attachment; filename=\""
- + inFile.getName() + "\"");
- copyStream(is, os);
- os.flush();
- } catch (Exception ex) {
- if (os == null)
- throw new Exception("Could not open output stream for file ");
- if (is == null)
- throw new Exception("Could not open input stream for file ");
- } finally {
- if (os != null) {
- os.close();
- }
- if (is != null)
- is.close();
- }
- }
-
- private void serveFile(HttpServletResponse response, byte[] outStream,
- String name) throws Exception {
- OutputStream os = null;
- InputStream is = null;
- try {
- response.reset();
- response.setContentLength((int) outStream.length);
- response.setContentType("application/octet-stream");
- response.setHeader("Content-disposition", "attachment; filename=\""
- + name + "\"");
- copyStream(response, outStream);
- } catch (Exception ex) {
- if (os == null)
- throw new Exception("Could not open output stream for file ");
- if (is == null)
- throw new Exception("Could not open input stream for file ");
- } finally {
- if (os != null) {
- os.close();
- }
- if (is != null)
- is.close();
- }
- }
-
- private int copyStream(InputStream in, OutputStream out) throws IOException {
- int bytes, totalBytes = 0;
-
- byte[] b = new byte[4096];
-
- while ((bytes = in.read(b, 0, b.length)) != -1) {
- totalBytes += bytes;
- out.write(b, 0, bytes);
- }
- return totalBytes;
- }
-
- private int copyStream(HttpServletResponse response, byte[] outStream)
- throws IOException {
-
- OutputStream os = new BufferedOutputStream(response.getOutputStream());
- os.write(outStream);
- os.flush();
- return outStream.length;
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.domain;
-
-
-import java.util.*;
-
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;;
-
-/**
- * <p>CR_Report.java</p>
- * <p>Represents a RAPTOR report data object.</p>
- *
- * @author Sundar Ramalingam
- * @version 1.0
- */
-public class CR_Report extends DomainVo {
-
- private String title;
- private String descr;
- private String public_yn;
- //private String report_xml;
- private Date createDate;
- private Date maintDate;
- private String menuId;
- private String menuApproved_YN;
- private User ownerId;
- private Long folderId;
- private String dashboard_type_YN;
- private String dashboard_yn;
- private User createId;
- private User maintId;
-
-/*
- //New Buttons
- private String copyImagePath = "/static/fusion/raptor/img/cross-small.png" ;
- private String editImagePath = "/static/fusion/raptor/img/pencil-small.png" ;
- private String deleteImagePath = "/static/fusion/raptor/img/DeleteCross-16x16.png" ;
- private String scheduleImagePath = "/static/fusion/raptor/img/Calendar-16x16.png" ;
- private String runImagePath = "/static/fusion/raptor/img/tick-small.png" ;
-
-*/
- //private Set reportAccess = new TreeSet();
-
- public CR_Report() {}
-
-
-
- /**
- * @return the title
- */
- public String getTitle() {
- return title;
- }
-
-
-
- /**
- * @param title the title to set
- */
- public void setTitle(String title) {
- this.title = title;
- }
-
-
-
- /**
- * @return the descr
- */
- public String getDescr() {
- return descr;
- }
-
-
-
- /**
- * @param descr the descr to set
- */
- public void setDescr(String descr) {
- this.descr = descr;
- }
-
-
-
- /**
- * @return the public_yn
- */
- public String getPublic_yn() {
- return public_yn;
- }
-
-
-
- /**
- * @param public_yn the public_yn to set
- */
- public void setPublic_yn(String public_yn) {
- this.public_yn = public_yn;
- }
-
-
- /**
- * @return the createDate
- */
- public Date getCreateDate() {
- return createDate;
- }
-
-
-
- /**
- * @param createDate the createDate to set
- */
- public void setCreateDate(Date createDate) {
- this.createDate = createDate;
- }
-
-
- /**
- * @return the maintDate
- */
- public Date getMaintDate() {
- return maintDate;
- }
-
-
-
- /**
- * @param maintDate the maintDate to set
- */
- public void setMaintDate(Date maintDate) {
- this.maintDate = maintDate;
- }
-
-
-
- /**
- * @return the menuId
- */
- public String getMenuId() {
- return menuId;
- }
-
-
-
- /**
- * @param menuId the menuId to set
- */
- public void setMenuId(String menuId) {
- this.menuId = menuId;
- }
-
-
-
- /**
- * @return the menuApproved_YN
- */
- public String getMenuApproved_YN() {
- return menuApproved_YN;
- }
-
-
-
- /**
- * @param menuApproved_YN the menuApproved_YN to set
- */
- public void setMenuApproved_YN(String menuApproved_YN) {
- this.menuApproved_YN = menuApproved_YN;
- }
-
-
-
-
- /**
- * @return the folderId
- */
- public Long getFolderId() {
- return folderId;
- }
-
-
-
- /**
- * @param folderId the folderId to set
- */
- public void setFolderId(Long folderId) {
- this.folderId = folderId;
- }
-
-
-
- /**
- * @return the dashboard_type_YN
- */
- public String getDashboard_type_YN() {
- return dashboard_type_YN;
- }
-
-
-
- /**
- * @param dashboard_type_YN the dashboard_type_YN to set
- */
- public void setDashboard_type_YN(String dashboard_type_YN) {
- this.dashboard_type_YN = dashboard_type_YN;
- }
-
-
-
- /**
- * @return the dashboard_yn
- */
- public String getDashboard_yn() {
- return dashboard_yn;
- }
-
-
-
- /**
- * @param dashboard_yn the dashboard_yn to set
- */
- public void setDashboard_yn(String dashboard_yn) {
- this.dashboard_yn = dashboard_yn;
- }
-
-
-
- /**
- * @return the ownerId
- */
- public User getOwnerId() {
- return ownerId;
- }
-
-
-
- /**
- * @param ownerId the ownerId to set
- */
- public void setOwnerId(User ownerId) {
- this.ownerId = ownerId;
- }
-
-
-
- /**
- * @return the createId
- */
- public User getCreateId() {
- return createId;
- }
-
-
-
- /**
- * @param createId the createId to set
- */
- public void setCreateId(User createId) {
- this.createId = createId;
- }
-
-
-
- /**
- * @return the maintId
- */
- public User getMaintId() {
- return maintId;
- }
-
-
-
- /**
- * @param maintId the maintId to set
- */
- public void setMaintId(User maintId) {
- this.maintId = maintId;
- }
-
-
-
- public int compareTo(Object obj){
- String c1 = getTitle();
- String c2 = ((CR_Report)obj).getTitle();
-
- return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.domain;
-
-public class QuickLink {
-
- private String reportURL;
- private String reportName;
- private String reportDescr;
- private Boolean showDescr;
-
- public String getReportURL() {
- return reportURL;
- }
-
- public void setReportURL(String reportURL) {
- this.reportURL = reportURL;
- }
-
- 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 Boolean getShowDescr() {
- return showDescr;
- }
-
- public void setShowDescr(Boolean showDescr) {
- this.showDescr = showDescr;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.domain;
-
-import java.util.Date;
-
-import org.openecomp.portalsdk.analytics.system.Globals;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;;
-
-public class RaptorSearch extends DomainVo {
-
- private Long repId;
- private String title;
- private String descr;
- private String ownerName;
- private Date createDate;
- private String canEdit;
- private String readOnly;
- private String schedule;
- // private Long countRows;
-
- /**
- * @return the repId
- */
- public Long getRepId() {
- return repId;
- }
-
- /**
- * @param repId
- * the repId to set
- */
- public void setRepId(Long repId) {
- this.repId = repId;
- }
-
- /**
- * @return the title
- */
- public String getTitle() {
- return title;
- }
-
- /**
- * @param title
- * the title to set
- */
- public void setTitle(String title) {
- this.title = title;
- }
-
- /**
- * @return the descr
- */
- public String getDescr() {
- return descr;
- }
-
- /**
- * @param descr
- * the descr to set
- */
- public void setDescr(String descr) {
- this.descr = descr;
- }
-
- /**
- * @return the createDate
- */
- public Date getCreateDate() {
- return createDate;
- }
-
- /**
- * @param createDate
- * the createDate to set
- */
- public void setCreateDate(Date createDate) {
- this.createDate = createDate;
- }
-
- /**
- * @return the ownerName
- */
- public String getOwnerName() {
- return ownerName;
- }
-
- /**
- * @param ownerName
- * the ownerName to set
- */
- public void setOwnerName(String ownerName) {
- this.ownerName = ownerName;
- }
-
- /**
- * @return the schedule
- */
- public String getSchedule() {
- return schedule;
- }
-
- /**
- * @param schedule
- * the schedule to set
- */
- public void setSchedule(String schedule) {
- this.schedule = schedule;
- }
-
- /**
- * @return the canEdit
- */
- public String getCanEdit() {
- return canEdit;
- }
-
- /**
- * @param canEdit
- * the canEdit to set
- */
- public void setCanEdit(String canEdit) {
- this.canEdit = canEdit;
- }
-
- /**
- * @return the canDelete
- */
- public boolean canDelete() {
- String s = getCanEdit();
- if (s != null && s.length() > 0 && s.equals("Y")) {
- return true;
- }
- return false;
- }
-
- /**
- * @return the canCopy
- */
- public boolean canCopy() {
- String s = getReadOnly();
- if (returnTrueOrFalse(s)) {
- return Globals.getCanCopyOnReadOnly() ? true : returnTrueOrFalse(getCanEdit());
- }
- return true;
- }
-
- /**
- * @return the readOnly
- */
- public String getReadOnly() {
- return readOnly;
- }
-
- /**
- * @param readOnly
- * the readOnly to set
- */
- public void setReadOnly(String readOnly) {
- this.readOnly = readOnly;
- }
-
- private boolean returnTrueOrFalse(String s) {
- if (s != null && s.length() > 0 && s.equals("Y")) {
- return true;
- }
- return false;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.domain;
-
-import java.util.Date;
-
-public class ReportInfo {
-
- private Long repId;
- private String title;
- private String createUser;
- private String ownerName;
- private Date createDate;
- private Long lastAccessed = -1L;
- private Long lastWeekAccess;
- private Long lastMonthAccess;
- private Long lastYearAccess;
- private Long userAccessCount;
- /**
- * @return the repId
- */
- public Long getRepId() {
- return repId;
- }
- /**
- * @param repId the repId to set
- */
- public void setRepId(Long repId) {
- this.repId = repId;
- }
- /**
- * @return the title
- */
- public String getTitle() {
- return title;
- }
- /**
- * @param title the title to set
- */
- public void setTitle(String title) {
- this.title = title;
- }
- /**
- * @return the createUser
- */
- public String getCreateUser() {
- return createUser;
- }
- /**
- * @param createUser the createUser to set
- */
- public void setCreateUser(String createUser) {
- this.createUser = createUser;
- }
- /**
- * @return the ownerName
- */
- public String getOwnerName() {
- return ownerName;
- }
- /**
- * @param ownerName the ownerName to set
- */
- public void setOwnerName(String ownerName) {
- this.ownerName = ownerName;
- }
- /**
- * @return the createDate
- */
- public Date getCreateDate() {
- return createDate;
- }
- /**
- * @param createDate the createDate to set
- */
- public void setCreateDate(Date createDate) {
- this.createDate = createDate;
- }
- /**
- * @return the lastAccessed
- */
- public Long getLastAccessed() {
- return lastAccessed;
- }
- /**
- * @param lastAccessed the lastAccessed to set
- */
- public void setLastAccessed(Long lastAccessed) {
- this.lastAccessed = lastAccessed;
- }
- /**
- * @return the lastWeekAccess
- */
- public Long getLastWeekAccess() {
- return lastWeekAccess;
- }
- /**
- * @param lastWeekAccess the lastWeekAccess to set
- */
- public void setLastWeekAccess(Long lastWeekAccess) {
- this.lastWeekAccess = lastWeekAccess;
- }
- /**
- * @return the lastMonthAccess
- */
- public Long getLastMonthAccess() {
- return lastMonthAccess;
- }
- /**
- * @param lastMonthAccess the lastMonthAccess to set
- */
- public void setLastMonthAccess(Long lastMonthAccess) {
- this.lastMonthAccess = lastMonthAccess;
- }
- /**
- * @return the lastYearAccess
- */
- public Long getLastYearAccess() {
- return lastYearAccess;
- }
- /**
- * @param lastYearAccess the lastYearAccess to set
- */
- public void setLastYearAccess(Long lastYearAccess) {
- this.lastYearAccess = lastYearAccess;
- }
- /**
- * @return the userAccessCount
- */
- public Long getUserAccessCount() {
- return userAccessCount;
- }
- /**
- * @param userAccessCount the userAccessCount to set
- */
- public void setUserAccessCount(Long userAccessCount) {
- this.userAccessCount = userAccessCount;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.service;
-
-import java.util.*;
-
-
-
-public interface RaptorService {
- public void deleteReport(Long reportId);
- public List getReportInfo(Map params);
- public int getTotalSize();
- public int executeCountQuery(Class entity, String query, Map params, String whereClause);
- public List executeGridQuery(String query, Map params, Integer fromIndex, Integer toIndex);
- public List executeGridQueryOrderByWithLimit(Class entity, String query, Map params, String _orderBy, boolean _asc, Integer fromIndex, Integer toIndex);
- public List executeGridQuery(Class entity, String query, String whereClause, Map params, Integer fromIndex, Integer toIndex);
- public List executeGridQueryOrderByWithLimit(Class entity, String query, String whereClause, Map params, String _orderBy, boolean _asc, Integer fromIndex, Integer toIndex);
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.service;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.math.BigDecimal;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.sql.DataSource;
-
-import org.hibernate.Query;
-import org.hibernate.Session;
-import org.openecomp.portalsdk.analytics.system.fusion.domain.CR_Report;
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.service.support.FusionService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.context.ApplicationContext;
-import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
-import org.springframework.orm.hibernate3.SessionFactoryUtils;
-import org.springframework.web.multipart.MultipartFile;
-
-public class RaptorServiceImpl extends FusionService implements RaptorService {
-
- private DataAccessService dataAccessService;
-
- private int totalSize;
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- private ApplicationContext applicationContext;
-
- //raptorSearchAllReportsCount
-
- public int executeCountQuery(Class entity, String query, Map params, String whereClause) {
- List l = getDataAccessService().executeNamedCountQuery(entity, query, whereClause, params);
- //List l = getDataAccessService().executeNamedQuery(query, params, null);
- int searchCount = 0;
- if(l != null) {
- if (!l.isEmpty()) {
- searchCount = (((Long) l.get(0))).intValue();
- }
- }
- totalSize = searchCount;
- return totalSize;
- }
-
- //raptorSearchAllReports
- public List executeGridQuery(String query, Map params, Integer fromIndex, Integer toIndex) {
- return getDataAccessService().executeNamedQuery(query, params, fromIndex, toIndex, null);
- }
-
- public List executeGridQueryOrderByWithLimit(Class entity, String query, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex) {
- return getDataAccessService().executeNamedQueryWithOrderBy(entity, query, params, _orderBy, asc, fromIndex, toIndex, null);
- }
-
- //with where clause
- public List executeGridQuery(Class entity, String query, String whereClause, Map params, Integer fromIndex, Integer toIndex) {
- return getDataAccessService().executeNamedQuery(entity, query, whereClause, params, fromIndex, toIndex, null);
- }
-
- public List executeGridQueryOrderByWithLimit(Class entity, String query, String whereClause, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex) {
- return getDataAccessService().executeNamedQueryWithOrderBy(entity, query, whereClause, params, _orderBy, asc, fromIndex, toIndex, null);
- }
-
- /*
- public int getUserReportsCount(Map params) {
- List l = getDataAccessService().executeNamedQuery("raptorSearchUserReportsCount", params, null);
- int count = 0;
- if(l != null) {
- if (!l.isEmpty()) {
- Object[] result = (Object[]) l.get(0);
- count = ((Long)result[0]).intValue();
- }
- }
- totalSize = count;
- return totalSize;
- }
-
- public List getUserReports(Map params, Integer fromIndex, Integer toIndex) {
- return getDataAccessService().executeNamedQuery("raptorSearchUserReports", params, fromIndex, toIndex, null);
- }
-
- public int getPublicReportsCount(Map params) {
- List l = getDataAccessService().executeNamedQuery("raptorPublicUserReportsCount", params, null);
- int count = 0;
- if(l != null) {
- if (!l.isEmpty()) {
- Object[] result = (Object[]) l.get(0);
- count = ((Long)result[0]).intValue();
- }
- }
- totalSize = count;
- return totalSize;
- }
-
- public List getPublicReports(Map params, Integer fromIndex, Integer toIndex) {
- return getDataAccessService().executeNamedQuery("raptorPublicUserReports", params, fromIndex, toIndex, null);
- }
-
- public int getFavReportsCount(Map params) {
- List l = getDataAccessService().executeNamedQuery("raptorSearchFavReportsCount", params, null);
- int count = 0;
- if(l != null) {
- if (!l.isEmpty()) {
- Object[] result = (Object[]) l.get(0);
- count = ((Long)result[0]).intValue();
- }
- }
- totalSize = count;
- return totalSize;
- }
-
- public List getFavReports(Map params, Integer fromIndex, Integer toIndex) {
- return getDataAccessService().executeNamedQuery("raptorSearchFavReports", params, fromIndex, toIndex, null);
- }
- */
- public int getTotalSize() {
- return totalSize;
- }
-
- public void deleteReport(Long reportId) {
- getDataAccessService().deleteDomainObject(getDataAccessService().getDomainObject(CR_Report.class, reportId, null), null);
- }
-
- public List getReportInfo(Map params) {
- return getDataAccessService().executeNamedQuery("raptorInfoQuery", params, null);
- }
-
-/* public List executeGridQueryWithOrderBy(String query, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex) {
- query = String.format(query, _orderBy, asc ? "ASC" : "DESC", fromIndex, toIndex);
- DataSource ds = (DataSource)getApplicationContext().getBean(searchBean.getDatasourceName());
- NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(ds);
- }*/
-
- /**
- * @return the applicationContext
- */
- public ApplicationContext getApplicationContext() {
- return applicationContext;
- }
-
- /**
- * @param applicationContext the applicationContext to set
- */
- public void setApplicationContext(ApplicationContext applicationContext) {
- this.applicationContext = applicationContext;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.web;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.lang.reflect.Method;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalsdk.analytics.controller.Action;
-import org.openecomp.portalsdk.analytics.controller.ErrorHandler;
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.error.RaptorRuntimeException;
-import org.openecomp.portalsdk.analytics.model.runtime.ErrorJSONRuntime;
-import org.openecomp.portalsdk.analytics.system.Globals;
-import org.openecomp.portalsdk.analytics.util.AppConstants;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
-
-@Controller
-@RequestMapping("/")
-public class RaptorController extends RestrictedBaseController {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RaptorController.class);
-
- @RequestMapping(value = { "/report" }, method = RequestMethod.GET)
- public ModelAndView report(HttpServletRequest request) {
- request.getSession().setAttribute("isEmbedded", false);
- return new ModelAndView("report");
- }
-
- @RequestMapping(value = { "/reportDS1" }, method = RequestMethod.GET)
- public ModelAndView reportDS1(HttpServletRequest request) {
- request.getSession().setAttribute("isEmbedded", false);
- return new ModelAndView("reportDS1");
- }
-
- @RequestMapping(value = { "/report_embedded" }, method = RequestMethod.GET)
- public ModelAndView reportEmbedded(HttpServletRequest request) {
- request.getSession().setAttribute("isEmbedded", true);
- return new ModelAndView("report_embedded");
- }
-
- @RequestMapping(value = { "/report_sample" }, method = RequestMethod.GET)
- public ModelAndView reportSample(HttpServletRequest request) {
- return new ModelAndView("report_sample");
- }
-
- @RequestMapping(value = { "/report_import.htm" }, method = RequestMethod.GET)
- public ModelAndView reportImport(HttpServletRequest request) throws IOException {
- String viewName = "report_import";
- Action action = null;
- String actionKey = "report.import";
- ServletContext servletContext = request.getSession().getServletContext();
- if (!Globals.isSystemInitialized()) {
- Globals.initializeSystem(servletContext);
- }
- 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()));
- viewName = new ErrorHandler().processFatalError(request,
- new RaptorRuntimeException("[Controller.processRequest]Invalid raptor action [" + actionKey
- + "]. Exception: " + e.getMessage()));
- }
- return new ModelAndView(viewName, "model", null);
- }
-
- @RequestMapping(value = { "/report_wizard.htm" }, method = { RequestMethod.POST, RequestMethod.GET })
- public ModelAndView reportWizard(HttpServletRequest request, HttpServletResponse response) throws IOException {
- String viewName = "";
- String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action"));
- actionKey = nvl(actionKey, "report.run");
- Action action = null;
- ServletContext servletContext = request.getSession().getServletContext();
- if (!Globals.isSystemInitialized()) {
- Globals.initializeSystem(servletContext);
- }
- 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()));
- viewName = (new ErrorHandler()).processFatalError(request,
- new RaptorRuntimeException("[Controller.processRequest]Invalid raptor action [" + actionKey
- + "]. Exception: " + e.getMessage()));
- ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
- errorJSONRuntime.setErrormessage(e.toString());
- errorJSONRuntime.setStacktrace(getStackTrace(e));
- ObjectMapper mapper = new ObjectMapper();
- 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();
-
- }
- }
-
- 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();
- viewName = (String) handlerMethod.invoke(handler, paramValues);
- } catch (Exception e) {
- logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action ["
- + actionKey + "]. Exception: " + e.getMessage()));
- viewName = (new ErrorHandler()).processFatalError(request,
- new RaptorRuntimeException(
- "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: "
- + e.getMessage()));
-
- ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
- errorJSONRuntime.setErrormessage(e.toString());
- errorJSONRuntime.setStacktrace(getStackTrace(e));
- ObjectMapper mapper = new ObjectMapper();
- 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 new ModelAndView(viewName, "model", null);
- }
-
- private String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- private String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
- public static String getStackTrace(Throwable aThrowable) {
- Writer result = new StringWriter();
- PrintWriter printWriter = new PrintWriter(result);
- aThrowable.printStackTrace(printWriter);
- return result.toString();
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.web;
-
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import org.openecomp.portalsdk.analytics.controller.Action;
-import org.openecomp.portalsdk.analytics.controller.ErrorHandler;
-import org.openecomp.portalsdk.analytics.controller.WizardSequence;
-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.model.DataCache;
-import org.openecomp.portalsdk.analytics.model.ReportHandler;
-import org.openecomp.portalsdk.analytics.model.base.IdNameValue;
-import org.openecomp.portalsdk.analytics.model.base.ReportUserRole;
-import org.openecomp.portalsdk.analytics.model.definition.ReportDefinition;
-import org.openecomp.portalsdk.analytics.model.definition.SecurityEntry;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.ColumnEditJSON;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.ColumnJSON;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.DefinitionJSON;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.FormEditJSON;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.IdNameBooleanJSON;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.ImportJSON;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.MessageJSON;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.NameBooleanJSON;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.QueryJSON;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.QueryResultJSON;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.RaptorResponse;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.SearchFieldJSON;
-import org.openecomp.portalsdk.analytics.model.definition.wizard.WizardJSON;
-import org.openecomp.portalsdk.analytics.model.pdf.PdfReportHandler;
-import org.openecomp.portalsdk.analytics.model.runtime.CategoryAxisJSON;
-import org.openecomp.portalsdk.analytics.model.runtime.ChartJSON;
-import org.openecomp.portalsdk.analytics.model.runtime.ErrorJSONRuntime;
-import org.openecomp.portalsdk.analytics.model.runtime.FormField;
-import org.openecomp.portalsdk.analytics.model.runtime.RangeAxisJSON;
-import org.openecomp.portalsdk.analytics.model.runtime.ReportFormFields;
-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.system.fusion.adapter.Item;
-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.util.XSSFilter;
-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.analytics.xmlobj.ObjectFactory;
-import org.openecomp.portalsdk.analytics.xmlobj.PredefinedValueList;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-import org.springframework.web.context.request.async.DeferredResult;
-
-import com.fasterxml.jackson.core.JsonFactory;
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
-
-@Controller
-@RequestMapping("/")
-public class RaptorControllerAsync extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RaptorControllerAsync.class);
-
- private String viewName;
-
- @RequestMapping(value = { "/raptor.htm" }, method = RequestMethod.GET)
- public void RaptorSearch(HttpServletRequest request, HttpServletResponse response)
- throws IOException, RaptorException {
-
- viewName = "";
- String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action"));
- actionKey = nvl(actionKey, "report.run");
-
- HttpSession session = request.getSession();
- User user = UserUtils.getUserSession(request);
-
- if (actionKey.equals("report.download.excel2007.session") || actionKey.equals("report.download.csv.session")
- || actionKey.equals("report.download.excel.session")
- || actionKey.equals("report.download.pdf.session")) {
- if (session != null && user != null) {
- ServletContext servletContext = request.getSession().getServletContext();
- if (!Globals.isSystemInitialized()) {
- Globals.initializeSystem(servletContext);
- }
- ReportRuntime 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");
- }
-
- boolean isEmbedded = false;
- Object temp = request.getSession().getAttribute("isEmbedded");
- if (temp != null) {
- isEmbedded = (boolean) temp;
- }
- if (isEmbedded) {
- String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
- if (rr == null)
- rr = (ReportRuntime) ((HashMap) request.getSession()
- .getAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP)).get(reportID);
- if (rd == null)
- rd = (ReportData) ((HashMap) request.getSession()
- .getAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP)).get(reportID);
- } else {
- if (rr == null)
- rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
- if (rd == null)
- rd = (ReportData) request.getSession().getAttribute(AppConstants.RI_REPORT_DATA);
- }
- String user_id = AppUtils.getUserID(request);
- int downloadLimit = 0;
- if (rr != null)
- downloadLimit = (rr.getMaxRowsInExcelDownload() > 0) ? rr.getMaxRowsInExcelDownload()
- : Globals.getDownloadLimit();
- if (actionKey.equals("report.csv.download"))
- downloadLimit = Globals.getCSVDownloadLimit();
- String sql_whole = rr.getReportDataSQL(user_id, downloadLimit, request);
- request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sql_whole);
- try {
- OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());
-
- if (actionKey.equals("report.download.pdf.session")) {
- new PdfReportHandler().createPdfFileContent(request, response, 3);
- } else if (actionKey.equals("report.download.csv.session")) {
- (new ReportHandler()).createCSVFileContent(out, rd, rr, request, response);
- } else if (actionKey.equals("report.download.excel.session")) {
- new ReportHandler().createExcelFileContent(out, rd, rr, request, response, user_id, 3); // 3
- // whole
- } else {
-
- new ReportHandler().createExcel2007FileContent(out, rd, rr, request, response, user_id, 3); // 3
- // whole
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [" + actionKey + "].", e);
- }
- } else {
- response.sendRedirect("login.htm");
- }
- } else {
- if (session != null && user != null) {
- Action action = null;
- ServletContext servletContext = request.getSession().getServletContext();
- if (!Globals.isSystemInitialized()) {
- Globals.initializeSystem(servletContext);
- }
- try {
- action = Globals.getRaptorActionMapping().getAction(actionKey);
- if (action == null)
- throw new RaptorRuntimeException("Action not found");
- } catch (RaptorException e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [" + actionKey + "].", e);
-
- viewName = (new ErrorHandler()).processFatalErrorJSON(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();
- ;
-
- viewName = (String) handlerMethod.invoke(handler, paramValues);
- if (!actionKey.equals("chart.run"))
- response.setContentType("application/json");
- else
- response.setContentType("text/html");
-
- } catch (ClassNotFoundException e) {
- logger.debug(EELFLoggerDelegate.debugLogger, ("[Controller.processRequest]Invalid raptor action ["
- + actionKey + "]. ClassNotFoundException: " + e.getMessage()));
- viewName = (new ErrorHandler()).processFatalErrorJSON(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()));
- viewName = (new ErrorHandler()).processFatalErrorJSON(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()));
- viewName = (new ErrorHandler()).processFatalErrorJSON(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()));
- viewName = (new ErrorHandler()).processFatalErrorJSON(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()));
- viewName = (new ErrorHandler()).processFatalErrorJSON(request,
- new RaptorRuntimeException(
- "[Controller.processRequest] Unable to instantiate and invoke action handler. Exception: "
- + e.getMessage()));
- } finally {
- PrintWriter out = response.getWriter();
- out.write(viewName);
- }
- } else {
- PrintWriter out = response.getWriter();
- out.write("session has timed out for user");
- }
-
- }
- }
-
- @RequestMapping(value = "/report/wizard/list_columns", method = RequestMethod.GET, produces = "application/json")
- public @ResponseBody ArrayList<ColumnJSON> listColumns(HttpServletRequest request, HttpServletResponse response)
- throws IOException, RaptorException {
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- List<DataColumnType> reportColumnList = rdef.getAllColumns();
- ArrayList<ColumnJSON> listJSON = new ArrayList<ColumnJSON>();
- ColumnJSON columnJSON = new ColumnJSON();
-
- for (DataColumnType reportColumnType : reportColumnList) {
- columnJSON = new ColumnJSON();
- columnJSON.setId(reportColumnType.getColId());
- columnJSON.setName(reportColumnType.getColName());
- listJSON.add(columnJSON);
- }
- return listJSON;
- }
-
- @RequestMapping(value = "/report/wizard/list_drilldown_reports", method = RequestMethod.GET, produces = "application/json")
- public @ResponseBody ArrayList<ColumnJSON> list_drilldown_reports(HttpServletRequest request,
- HttpServletResponse response) throws IOException, RaptorException {
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- Vector<IdNameValue> publicReportIdNames = DataCache.getPublicReportIdNames();
- Vector groupReportIdNames = DataCache.getGroupAccessibleReportIdNames(AppUtils.getUserID(request),
- AppUtils.getUserRoles(request));
- Vector privateReportIdNames = DataCache.getPrivateAccessibleReportIdNames(AppUtils.getUserID(request),
- AppUtils.getUserRoles(request));
-
- ArrayList<ColumnJSON> listJSON = new ArrayList<ColumnJSON>();
- ColumnJSON columnJSON = new ColumnJSON();
-
- ServletContext servletContext = request.getSession().getServletContext();
- if (!Globals.isSystemInitialized()) {
- Globals.initializeSystem(servletContext);
- }
-
- for (int i = 0; i < publicReportIdNames.size(); i++) {
- IdNameValue reportIdName = (IdNameValue) publicReportIdNames.get(i);
- columnJSON = new ColumnJSON();
- columnJSON.setId(reportIdName.getId());
- columnJSON.setName("Public Report: " + reportIdName.getName());
- if (!rdef.getReportID().equals(reportIdName.getId()))
- listJSON.add(columnJSON);
- }
-
- for (int i = 0; i < groupReportIdNames.size(); i++) {
- IdNameValue reportIdName = (IdNameValue) groupReportIdNames.get(i);
- columnJSON = new ColumnJSON();
- columnJSON.setId(reportIdName.getId());
- columnJSON.setName("Group Report: " + reportIdName.getName());
- if (!rdef.getReportID().equals(reportIdName.getId()))
- listJSON.add(columnJSON);
- }
-
- for (int i = 0; i < privateReportIdNames.size(); i++) {
- IdNameValue reportIdName = (IdNameValue) privateReportIdNames.get(i);
- columnJSON = new ColumnJSON();
- columnJSON.setId(reportIdName.getId());
- columnJSON.setName("Private Report: " + reportIdName.getName());
- if (!rdef.getReportID().equals(reportIdName.getId()))
- listJSON.add(columnJSON);
- }
-
- return listJSON;
- }
-
- @RequestMapping(value = "/report/wizard/list_formfields", method = RequestMethod.GET, produces = "application/json")
- public @ResponseBody ArrayList<SearchFieldJSON> listFormFields(HttpServletRequest request,
- HttpServletResponse response) throws IOException, RaptorException {
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- ArrayList<SearchFieldJSON> listJSON = new ArrayList<SearchFieldJSON>();
- SearchFieldJSON fieldJSON = new SearchFieldJSON();
- if (rdef.getFormFieldList() != null) {
- for (Iterator iter = rdef.getFormFieldList().getFormField().iterator(); iter.hasNext();) {
- fieldJSON = new SearchFieldJSON();
- FormFieldType fft = (FormFieldType) iter.next();
- String fieldId = fft.getFieldId();
- String fieldDisplay = fft.getFieldName();
- fieldJSON.setId(fieldId);
- fieldJSON.setName(fieldDisplay);
- listJSON.add(fieldJSON);
- }
- }
-
- return listJSON;
- }
-
- @RequestMapping(value = "/report/wizard/list_child_report_col/{reportID}", method = RequestMethod.GET, produces = "application/json")
- public @ResponseBody ArrayList<ColumnJSON> listChildReportCols(@PathVariable("reportID") String reportID,
- HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
- ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, reportID, false);
-
- List<DataColumnType> reportColumnList = ddRr.getAllColumns();
- ArrayList<ColumnJSON> listJSON = new ArrayList<ColumnJSON>();
- ColumnJSON columnJSON = new ColumnJSON();
-
- for (DataColumnType reportColumnType : reportColumnList) {
- columnJSON = new ColumnJSON();
- columnJSON.setId(reportColumnType.getColId());
- columnJSON.setName(reportColumnType.getColName());
- listJSON.add(columnJSON);
- }
- return listJSON;
- }
-
- @RequestMapping(value = "/report/wizard/list_child_report_ff/{reportID}", method = RequestMethod.GET, produces = "application/json")
- public @ResponseBody ArrayList<SearchFieldJSON> listChildReportFormFields(@PathVariable("reportID") String reportID,
- HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
- ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, reportID, false);
- ArrayList<SearchFieldJSON> listJSON = new ArrayList<SearchFieldJSON>();
- SearchFieldJSON fieldJSON = new SearchFieldJSON();
-
- ReportFormFields ddReportFormFields = ddRr.getReportFormFields();
- if (ddReportFormFields != null) {
- for (ddReportFormFields.resetNext(); ddReportFormFields.hasNext();) {
- FormField ff = ddReportFormFields.getNext();
- if (!ff.getFieldType().equals(FormField.FFT_BLANK)) {
- fieldJSON = new SearchFieldJSON();
- fieldJSON.setId(ff.getFieldName());
- fieldJSON.setName(ff.getFieldDisplayName());
- listJSON.add(fieldJSON);
- }
- }
- }
- return listJSON;
- }
-
- @RequestMapping(value = "report/wizard/copy_report/{reportID}", method = RequestMethod.GET, produces = "application/json")
- public @ResponseBody MessageJSON copyReport(@PathVariable("reportID") String reportID, HttpServletRequest request,
- HttpServletResponse response) throws IOException, RaptorException {
- MessageJSON messageJSON = new MessageJSON();
- try {
-
- ReportHandler rh = new ReportHandler();
- ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
- rdef.setAsCopy(request);
- request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
- messageJSON.setMessage("Success- Report Copied.");
- messageJSON.setAnyStacktrace(rdef.getReportID() + " is Modified and added to session and DB.");
-
- } catch (RaptorException e) {
- request.setAttribute("error_extra_msg", "While copying report " + reportID);
- messageJSON.setMessage("Failed - While copying report " + reportID);
- messageJSON.setAnyStacktrace(getStackTrace(e));
- logger.debug(EELFLoggerDelegate.debugLogger,
- ("[Controller.processRequest]Invalid raptor action [copyReport]. RaptorException: "
- + e.getMessage()));
- return messageJSON;
- }
-
- return messageJSON;
- }
-
- @RequestMapping(value = "report/wizard/import_report", method = RequestMethod.POST, consumes = "application/json")
- public @ResponseBody MessageJSON importReport(@RequestBody ImportJSON importJSON, HttpServletRequest request,
- HttpServletResponse response) throws IOException, RaptorException {
- MessageJSON messageJSON = new MessageJSON();
- try {
- String reportXML = importJSON.getReportXML();
-
- 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);
-
- messageJSON.setMessage("Success- Report imported.");
- messageJSON.setAnyStacktrace(rdef.getReportID() + " is Modified and added to session and DB.");
-
- } catch (RaptorException e) {
- request.setAttribute("error_extra_msg", "Unable to parse XML. Nested error: ");
- messageJSON.setMessage("Unable to parse XML. Nested error: ");
- messageJSON.setAnyStacktrace(getStackTrace(e));
-
- return messageJSON;
- }
-
- return messageJSON;
-
- }
-
- @RequestMapping(value = "report/wizard/save_formfield_tab_data", method = RequestMethod.POST)
- public @ResponseBody MessageJSON saveFFTabWiseData(@RequestBody FormEditJSON formEditJSON,
- HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
- ReportDefinition rdef = null;
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
-
- MessageJSON messageJSON = new MessageJSON();
- try {
- if (rdef != null) {
-
- String fieldId = formEditJSON.getFieldId();
-
- if (rdef.getFormFieldList() != null) {
- for (FormFieldType fft : rdef.getFormFieldList().getFormField()) {
- if (fft.getFieldId().equals(fieldId)) {
- fft.setFieldName(formEditJSON.getFieldName());
- fft.setFieldType(formEditJSON.getFieldType());
- fft.setVisible(formEditJSON.isVisible() ? "Y" : "N");
- fft.setDefaultValue(formEditJSON.getDefaultValue());
- fft.setFieldDefaultSQL(formEditJSON.getFieldDefaultSQL());
- fft.setFieldSQL(formEditJSON.getFieldSQL());
- fft.setValidationType(formEditJSON.getValidationType());
-
- // clear predefined value
- if (fft.getPredefinedValueList() != null) {
- for (Iterator<String> iter = fft.getPredefinedValueList().getPredefinedValue()
- .iterator(); iter.hasNext();)
- iter.remove();
- }
-
- List<IdNameBooleanJSON> predefList = formEditJSON.getPredefinedValueList();
- if (predefList != null && predefList.size() > 0) {
- for (IdNameBooleanJSON item : predefList) {
- PredefinedValueList predefinedValueList = new ObjectFactory()
- .createPredefinedValueList();
- fft.setPredefinedValueList(predefinedValueList);
- fft.getPredefinedValueList().getPredefinedValue().add(item.getId());
- }
- }
-
- }
- }
- }
-
- persistReportDefinition(request, rdef);
- messageJSON.setMessage("Success formfield Details of given report is saved in session.");
- messageJSON.setAnyStacktrace(rdef.getReportID() + " is Modified and added to session and DB.");
-
- } else {
- messageJSON.setMessage("Report Definition is not in session");
- messageJSON.setAnyStacktrace("Report Definition is not in session");
-
- }
- } catch (Exception ex) {
- messageJSON.setMessage("Error occured while formfield details Tab");
- messageJSON.setAnyStacktrace(getStackTrace(ex));
- return messageJSON;
- }
-
- return messageJSON;
- }
-
- @RequestMapping(value = "report/wizard/save_col_tab_data", method = RequestMethod.POST)
- public @ResponseBody MessageJSON saveColTabWiseData(@RequestBody ColumnEditJSON columnEditJSON,
- HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
- ReportDefinition rdef = null;
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
-
- MessageJSON messageJSON = new MessageJSON();
-
- try {
- if (rdef != null) {
- String colId = columnEditJSON.getColId();
- List<DataColumnType> reportColumnList = rdef.getAllColumns();
-
- for (DataColumnType reportColumnType : reportColumnList) {
- // columnJSON = new ColumnJSON();
- if (reportColumnType.getColId().equals(colId)) {
- reportColumnType.setColName(columnEditJSON.getColName());
- reportColumnType.setDisplayAlignment(columnEditJSON.getDisplayAlignment());
- reportColumnType.setDisplayHeaderAlignment(columnEditJSON.getDisplayHeaderAlignment());
- reportColumnType.setIsSortable(columnEditJSON.isSortable());
- reportColumnType.setVisible(columnEditJSON.isVisible());
- reportColumnType.setDrillDownURL(columnEditJSON.getDrilldownURL());
- reportColumnType.setDrillDownParams(columnEditJSON.getDrilldownParams());
- reportColumnType.setDrillDownType(columnEditJSON.getDrilldownType());
-
- }
-
- }
- persistReportDefinition(request, rdef);
- messageJSON.setMessage("Success Column Details of given report is saved in session.");
- messageJSON.setAnyStacktrace(rdef.getReportID() + " is Modified and added to session and DB.");
-
- } else {
- messageJSON.setMessage("Report Definition is not in session");
- messageJSON.setAnyStacktrace("");
-
- }
- } catch (Exception ex) {
- messageJSON.setMessage("Error occured while saving column details Tab");
- messageJSON.setAnyStacktrace(getStackTrace(ex));
-
- return messageJSON;
- }
-
- return messageJSON;
- }
-
- @RequestMapping(value = "report/wizard/save_def_tab_data/{id}", method = RequestMethod.POST)
- public @ResponseBody MessageJSON saveDefTabWiseData(@PathVariable("id") String id,
- @RequestBody DefinitionJSON definitionJSON, HttpServletRequest request, HttpServletResponse response)
- throws IOException, RaptorException {
- ReportDefinition rdef = null;
- ReportRuntime rr = null;
- boolean newReport = false;
- MessageJSON messageJSON = new MessageJSON();
-
- try {
- if (id.equals("InSession")) {
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- newReport = false;
-
- } else if (id.equals("Create")) {
- removeVariablesFromSession(request);
- rdef = (new ReportHandler()).loadReportDefinition(request, "-1");
- newReport = true;
- System.out.println("&&&&&&&&&&&&&&&&&&&&&& CHECK Report Type "
- + (AppUtils.nvl(rdef.getReportType()).length() <= 0));
- if (AppUtils.nvl(rdef.getReportType()).length() <= 0) {
- rdef.setReportType(AppConstants.RT_LINEAR);
- System.out.println("&&&&&&&&&&&&&&&&&&&&&& ADDED Report Type in session ");
- }
-
- } else if (AppUtils.nvl(id).length() > 0) {
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
-
- if (rdef != null && !rdef.getReportID().equals(id)) {
- request.getSession().removeAttribute(AppConstants.SI_REPORT_DEFINITION);
- removeVariablesFromSession(request);
- rdef = (new ReportHandler()).loadReportDefinition(request, id);
- } else if (rr != null && !rr.getReportID().equals(id)) {
- request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
- removeVariablesFromSession(request);
- rdef = (new ReportHandler()).loadReportDefinition(request, id);
- } else if (rdef == null) {
- rdef = (new ReportHandler()).loadReportDefinition(request, id);
- }
- newReport = false;
-
- } else {
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- newReport = true;
- }
- // }
-
- if (rdef != null) {
- String reportName = definitionJSON.getReportName();
- String errorString = "";
- if (AppUtils.nvl(reportName).length() <= 0)
- errorString = "ReportName cannot be null;";
- rdef.setReportName(reportName);
-
- String reportDescr = definitionJSON.getReportDescr();
- rdef.setReportDescr(reportDescr);
-
- String formHelpText = definitionJSON.getFormHelpText();
- rdef.setFormHelpText(formHelpText);
-
- Integer pageSize = definitionJSON.getPageSize();
- rdef.setPageSize(pageSize);
-
- List<IdNameBooleanJSON> menuIds = definitionJSON.getDisplayArea();
- for (IdNameBooleanJSON menuId : menuIds) {
- if (menuId.isSelected()) {
- rdef.setMenuID(menuId.getName());
- }
-
- }
-
- Boolean hideFormFieldsAfterRun = definitionJSON.getHideFormFieldsAfterRun();
- rdef.setHideFormFieldAfterRun(hideFormFieldsAfterRun);
- Integer maxRowsInExcelCSVDownload = definitionJSON.getMaxRowsInExcelCSVDownload();
- rdef.setMaxRowsInExcelDownload(maxRowsInExcelCSVDownload);
- Integer frozenColumns = definitionJSON.getFrozenColumns();
- rdef.setFrozenColumns(frozenColumns);
- String dataGridAlign = definitionJSON.getDataGridAlign();
- rdef.setDataGridAlign(dataGridAlign);
- String emptyMessage = definitionJSON.getEmptyMessage();
- rdef.setEmptyMessage(emptyMessage);
- String dataContainerHeight = definitionJSON.getDataContainerHeight();
- rdef.setDataContainerHeight(dataContainerHeight);
- String dataContainerWidth = definitionJSON.getDataContainerWidth();
- rdef.setDataContainerWidth(dataContainerWidth);
- boolean runtimeColSortDisabled = definitionJSON.getRuntimeColSortDisabled();
- rdef.setRuntimeColSortDisabled(runtimeColSortDisabled);
- Integer numFormCols = definitionJSON.getNumFormCols();
- rdef.setNumFormCols(Integer.toString(numFormCols));
- String reportTitle = definitionJSON.getReportTitle();
- rdef.setReportTitle(reportTitle);
- String reportSubTitle = definitionJSON.getReportSubTitle();
- rdef.setReportSubTitle(reportSubTitle);
-
- List<NameBooleanJSON> displayOptions = definitionJSON.getDisplayOptions();
- StringBuffer displayOptionStr = new StringBuffer("NNNNNNN");
- for (NameBooleanJSON displayOption : displayOptions) {
- if (displayOption.isSelected()) {
- if (displayOption.getName().equals("HideFormFields")) {
- displayOptionStr.setCharAt(0, 'Y');
- } else if (displayOption.getName().equals("HideChart")) {
- displayOptionStr.setCharAt(1, 'Y');
- } else if (displayOption.getName().equals("HideReportData")) {
- displayOptionStr.setCharAt(2, 'Y');
- } else if (displayOption.getName().equals("HideExcel")) {
- displayOptionStr.setCharAt(5, 'Y');
- } else if (displayOption.getName().equals("HidePdf")) {
- displayOptionStr.setCharAt(6, 'Y');
- }
- }
-
- }
-
- rdef.setDisplayOptions(displayOptionStr.toString());
- }
- if (id.equals("Create")) {
- rdef.persistReport(request);
- } else
- persistReportDefinition(request, rdef);
- messageJSON.setMessage("Success Definition of given report is saved in session.");
- messageJSON.setAnyStacktrace((newReport ? " New Report info is added to Session "
- : rdef.getReportID() + " is Modified and added to session and DB."));
-
- } catch (Exception ex) {
- messageJSON.setMessage("Error occured while saving definition Tab");
- messageJSON.setAnyStacktrace(getStackTrace(ex));
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveTabWiseData].", ex);
- return messageJSON;
- }
-
- return messageJSON;
- }
-
- @RequestMapping(value = { "/report/wizard/retrieve_form_tab_wise_data/{id}",
- "/report/wizard/retrieve_form_tab_wise_data/{id}/{action}" }, method = RequestMethod.GET)
- public @ResponseBody FormEditJSON retrieveFormTabWiseData(@PathVariable Map<String, String> pathVariables,
- HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
- ReportDefinition rdef = null;
- String id = "";
- String action = "";
- String detailId = "";
- FormEditJSON wizardJSON = new FormEditJSON();
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
-
- if (pathVariables.containsKey("id")) {
- id = pathVariables.get("id");
- }
- if (pathVariables.containsKey("action")) {
- action = pathVariables.get("action");
- }
-
- ServletContext servletContext = request.getSession().getServletContext();
- if (!Globals.isSystemInitialized()) {
- Globals.initializeSystem(servletContext);
- }
- wizardJSON.setTabId("FormEdit");
- wizardJSON.setTabName("Form Edit");
- FormFieldType currField = null;
- try {
- if (id.equals("add")) {
-
- currField = rdef.addFormFieldType(new ObjectFactory(), "", "", "", "", "", "", "", "", null, null, "",
- "");
- wizardJSON.setFieldId(currField.getFieldId());
- wizardJSON.setFieldName(currField.getFieldName());
- wizardJSON.setFieldType(currField.getFieldType());
- wizardJSON.setVisible(AppUtils.nvls(currField.getVisible(), "Y").toUpperCase().startsWith("Y"));
- wizardJSON.setDefaultValue(currField.getDefaultValue());
- wizardJSON.setFieldDefaultSQL(currField.getFieldDefaultSQL());
- wizardJSON.setFieldSQL(currField.getFieldSQL());
- wizardJSON.setValidationType(currField.getValidationType());
- persistReportDefinition(request, rdef);
-
- } else if (action.equals("delete")) {
- rdef.deleteFormField(id);
- persistReportDefinition(request, rdef);
- wizardJSON.setMessage("Formfield " + detailId + " Deleted");
- }
- if (rdef.getFormFieldList() != null) {
- for (FormFieldType fft : rdef.getFormFieldList().getFormField()) {
- if (fft.getFieldId().equals(id)) {
- wizardJSON.setFieldId(fft.getFieldId());
- wizardJSON.setFieldName(fft.getFieldName());
- wizardJSON.setFieldType(fft.getFieldType());
- wizardJSON.setVisible(fft.getVisible().toUpperCase().startsWith("Y"));
- wizardJSON.setDefaultValue(fft.getDefaultValue());
- wizardJSON.setFieldDefaultSQL(fft.getFieldDefaultSQL());
- wizardJSON.setFieldSQL(fft.getFieldSQL());
- wizardJSON.setValidationType(fft.getValidationType());
-
- PredefinedValueList preDefined = fft.getPredefinedValueList();
-
- if (preDefined != null) {
- List<IdNameBooleanJSON> preDefinedList = new ArrayList<IdNameBooleanJSON>();
- IdNameBooleanJSON idNameBooleanJSON = new IdNameBooleanJSON();
-
- for (String v : preDefined.getPredefinedValue()) {
- idNameBooleanJSON = new IdNameBooleanJSON();
- idNameBooleanJSON.setId(v);
- idNameBooleanJSON.setName(v);
- preDefinedList.add(idNameBooleanJSON);
- }
- wizardJSON.setPredefinedValueList(preDefinedList);
- }
- }
- }
- }
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveFormTabWiseData].", ex);
- ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
- errorJSONRuntime.setErrormessage("Error occured while retreiving formedit definition Tab");
- errorJSONRuntime.setStacktrace(getStackTrace(ex));
- wizardJSON.setErrorMessage("Error occured while retreiving formedit definition Tab");
- wizardJSON.setErrorStackTrace(getStackTrace(ex));
-
- }
-
- return wizardJSON;
- }
-
- @RequestMapping(value = { "/report/wizard/retrieve_col_tab_wise_data/{id}" }, method = RequestMethod.GET)
- public @ResponseBody ColumnEditJSON retrieveColTabWiseData(@PathVariable Map<String, String> pathVariables,
- HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
- ReportDefinition rdef = null;
- String id = "";
- ColumnEditJSON wizardJSON = new ColumnEditJSON();
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
-
- if (pathVariables.containsKey("id")) {
- id = pathVariables.get("id");
- }
- ServletContext servletContext = request.getSession().getServletContext();
- if (!Globals.isSystemInitialized()) {
- Globals.initializeSystem(servletContext);
- }
- if (rdef != null) {
- wizardJSON.setTabId("ColEdit");
- wizardJSON.setTabName("Column Edit");
-
- List<DataColumnType> reportColumnList = rdef.getAllColumns();
-
- for (DataColumnType reportColumnType : reportColumnList) {
- if (reportColumnType.getColId().equals(id)) {
- wizardJSON.setColId(reportColumnType.getColId());
- wizardJSON.setColName(reportColumnType.getColName());
- wizardJSON.setDisplayAlignment(reportColumnType.getDisplayAlignment());
- wizardJSON.setDisplayHeaderAlignment(reportColumnType.getDisplayHeaderAlignment());
- wizardJSON.setSortable(
- reportColumnType.isIsSortable() == null ? false : reportColumnType.isIsSortable());
- wizardJSON.setVisible(reportColumnType.isVisible());
- wizardJSON.setDrilldownURL(
- reportColumnType.getDrillDownURL() == null ? "" : reportColumnType.getDrillDownURL());
- wizardJSON.setDrilldownParams(
- reportColumnType.getDrillDownParams() == null ? "" : reportColumnType.getDrillDownParams());
- wizardJSON.setDrilldownType(
- reportColumnType.getDrillDownType() == null ? "" : reportColumnType.getDrillDownType());
-
- }
- }
- } else {
- wizardJSON.setErrorMessage("Report is not in session");
- }
-
- return wizardJSON;
- }
-
- @RequestMapping(value = { "/report/wizard/retrieve_sql_tab_wise_data/{id}",
- "/report/wizard/retrieve_sql_tab_wise_data/" }, method = RequestMethod.GET)
- public @ResponseBody QueryJSON retrieveSqlTabWiseData(@PathVariable Map<String, String> pathVariables,
- HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
- ReportDefinition rdef = null;
- ReportRuntime rr = null;
- String id = "";
- String detailId = "";
- QueryJSON wizardJSON = new QueryJSON();
-
- if (pathVariables.containsKey("id")) {
- id = pathVariables.get("id");
- }
- if (pathVariables.containsKey("detailId")) {
- detailId = pathVariables.get("detailId");
- }
- ServletContext servletContext = request.getSession().getServletContext();
- if (!Globals.isSystemInitialized()) {
- Globals.initializeSystem(servletContext);
- }
- if (id.equals("InSession") || AppUtils.nvl(id).length() <= 0) {
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- } else if (AppUtils.nvl(id).length() > 0) {
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
-
- if (rdef != null && !rdef.getReportID().equals(id)) {
- request.getSession().removeAttribute(AppConstants.SI_REPORT_DEFINITION);
- removeVariablesFromSession(request);
- rdef = (new ReportHandler()).loadReportDefinition(request, id);
- } else if (rr != null && !rr.getReportID().equals(id)) {
- request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
- removeVariablesFromSession(request);
- rdef = (new ReportHandler()).loadReportDefinition(request, id);
- } else if (rdef == null) {
- rdef = (new ReportHandler()).loadReportDefinition(request, id);
- }
- }
-
- if (rdef != null) {
-
- wizardJSON.setTabId("Sql");
- wizardJSON.setTabName("Sql");
- wizardJSON.setQuery(rdef.getReportSQL());
- }
- return wizardJSON;
- }
-
- @RequestMapping(value = { "/report/wizard/security/retrieveReportUserList" }, method = RequestMethod.GET)
- public @ResponseBody List<SecurityEntry> getReportUserList(HttpServletRequest request)
- throws IOException, RaptorException {
- List<SecurityEntry> reportUserList = new ArrayList<SecurityEntry>();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- Vector reportUsers = rdef.getReportUsers(request);
- for(Iterator iter=reportUsers.iterator(); iter.hasNext();) {
- SecurityEntry rUser = (SecurityEntry) iter.next();
- reportUserList.add(rUser);
- }
- return reportUserList;
- };
-
- @RequestMapping(value = { "/report/wizard/security/retrieveReportRoleList" }, method = RequestMethod.GET)
- public @ResponseBody List<IdNameValue> getReportRoleList(HttpServletRequest request)
- throws IOException, RaptorException {
- List<IdNameValue> reportRoleList = new ArrayList<IdNameValue>();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- Vector reportRoles = rdef.getReportRoles(request);
- Vector remainingRoles = Utils.getRolesNotInList(reportRoles,request);
- for(int i=0; i<remainingRoles.size(); i++) {
- IdNameValue role = (IdNameValue) remainingRoles.get(i);
- reportRoleList.add(role);
- }
- return reportRoleList;
- };
-
- @RequestMapping(value = { "/report/wizard/security/retrieveReportUserList_query" }, method = RequestMethod.GET)
- public @ResponseBody List<Map<String, String>> getReportUserListQuery(HttpServletRequest request)
- throws IOException, RaptorException {
- List<Map<String, String>> reportUserList = new ArrayList();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- String reportId = rdef.getReportID();
- Map<String, Object> params = new HashMap<String, Object>();
- params.put("report_id", new Long(reportId));
- List<ReportUserRole> queriedUserList = getDataAccessService().executeNamedQuery("getReportSecurityUsers", params, null);
- for (int i=0; i<queriedUserList.size();i++){
- Map<String, String> reportUser = new HashMap<String, String>();
- Object tmp = queriedUserList.get(i);
- reportUser.put("rep_id", queriedUserList.get(i).toString());
- reportUser.put("order_no", queriedUserList.get(i).getOrderNo().toString());
- reportUser.put("user_id", queriedUserList.get(i).getUserId().toString());
- reportUser.put("role_id", queriedUserList.get(i).getRoleId().toString());
- reportUser.put("read_only_yn", queriedUserList.get(i).getReadOnlyYn());
- reportUserList.add(reportUser);
- }
- return reportUserList;
- };
-
-
-
- @RequestMapping(value = "/report/security/addReportUser", method = RequestMethod.POST)
- public @ResponseBody Map<String,String> addSelectedReportUser(
- @RequestBody String userIdToAdd, HttpServletRequest request, HttpServletResponse response)
- throws IOException, RaptorException {
- Map<String, String> JsonResponse = new HashMap<String, String>();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- try {
- JsonResponse.put("status","success");
- JsonResponse.put("userId",userIdToAdd);
- String action = "Add User";
- rdef.getReportSecurity().addUserAccess(userIdToAdd, "Y");
- WizardSequence ws = rdef.getWizardSequence();
- ws.performAction(action,rdef);
- return JsonResponse;
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
- return null;
- }
- }
-
- @RequestMapping(value = "/report/security/removeReportUser", method = RequestMethod.POST)
- public @ResponseBody Map<String,String> removeSelectedReportUser(
- @RequestBody String userIdToRemove, HttpServletRequest request, HttpServletResponse response)
- throws IOException, RaptorException {
- Map<String, String> JsonResponse = new HashMap<String, String>();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- try {
- JsonResponse.put("status","success");
- JsonResponse.put("userId",userIdToRemove);
- String action = "Delete User";
- rdef.getReportSecurity().removeUserAccess(userIdToRemove);
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- WizardSequence ws = rdef.getWizardSequence();
- ws.performAction(action,rdef);
- return JsonResponse;
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
- return null;
- }
- }
-
- @RequestMapping(value = "/report/security/addReportRole", method = RequestMethod.POST)
- public @ResponseBody Map<String,String> addSelectedReportRole(
- @RequestBody String roleIdToAdd, HttpServletRequest request, HttpServletResponse response)
- throws IOException, RaptorException {
- Map<String, String> JsonResponse = new HashMap<String, String>();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- try {
- JsonResponse.put("status","success");
- JsonResponse.put("roleId",roleIdToAdd);
- String action = "Add Role";
- rdef.getReportSecurity().addRoleAccess(roleIdToAdd, "Y");
- WizardSequence ws = rdef.getWizardSequence();
- ws.performAction(action,rdef);
- return JsonResponse;
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
- return null;
- }
- }
-
- @RequestMapping(value = "/report/security/removeReportRole", method = RequestMethod.POST)
- public @ResponseBody Map<String,String> removeSelectedReportRole(
- @RequestBody String roleIdToRemove, HttpServletRequest request, HttpServletResponse response)
- throws IOException, RaptorException {
- Map<String, String> JsonResponse = new HashMap<String, String>();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- try {
- JsonResponse.put("status","success");
- JsonResponse.put("roleId",roleIdToRemove);
- String action = "Delete Role";
- rdef.getReportSecurity().removeRoleAccess(roleIdToRemove);
- WizardSequence ws = rdef.getWizardSequence();
- ws.performAction(action,rdef);
- return JsonResponse;
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
- return null;
- }
- }
-
- @RequestMapping(value = "/report/security/updateReportSecurityInfo", method = RequestMethod.POST)
- public @ResponseBody Map<String,String> updateReportSecurityInfo(
- @RequestBody Map<String,String> securityInfo, HttpServletRequest request, HttpServletResponse response)
- throws IOException, RaptorException {
-
- Map<String, String> JsonResponse = new HashMap<String, String>();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- try {
- JsonResponse.put("status","success");
- String OwnerUserId = securityInfo.get("userId");
- String isPublic = securityInfo.get("isPublic");
- boolean rPublic = isPublic.equals("true");
- rdef.getReportSecurity().setOwnerID(OwnerUserId);
- rdef.setPublic(rPublic);
- persistReportDefinition(request, rdef);
- return JsonResponse;
-
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
- return null;
- }
- }
-
- @RequestMapping(value = "/report/security/toggleUserEditAccess/{userID}", method = RequestMethod.POST)
- public @ResponseBody Map<String,String> toggleUserEditAccess(
- @PathVariable("userID") String userId,
- @RequestBody String readOnly, HttpServletRequest request, HttpServletResponse response)
- throws IOException, RaptorException {
- Map<String, String> JsonResponse = new HashMap<String, String>();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- try {
- String action ="";
- JsonResponse.put("status","success");
- if (readOnly.equals("N")) {
- action = "Grant User Access";
- } else {
- action = "Revoke User Access";
- }
- rdef.getReportSecurity().updateUserAccess(userId, readOnly);
- WizardSequence ws = rdef.getWizardSequence();
- ws.performAction(action,rdef);
-
- return JsonResponse;
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
- return null;
- }
- };
-
- @RequestMapping(value = "/report/security/toggleRoleEditAccess/{roleID}", method = RequestMethod.POST)
- public @ResponseBody Map<String,String> toggleRoleEditAccess(
- @PathVariable("roleID") String roleId,
- @RequestBody String readOnly, HttpServletRequest request, HttpServletResponse response)
- throws IOException, RaptorException {
- Map<String, String> JsonResponse = new HashMap<String, String>();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- try {
- String action ="";
- JsonResponse.put("status","success");
- if (readOnly.equals("N")) {
- action = "Grant Role Access";
- } else {
- action = "Revoke Role Access";
- }
- rdef.getReportSecurity().updateRoleAccess(roleId, readOnly);
- WizardSequence ws = rdef.getWizardSequence();
- ws.performAction(action,rdef);
-
- return JsonResponse;
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
- return null;
- }
- };
-
- @RequestMapping(value = { "/report/wizard/security/retrieveReportOwner" }, method = RequestMethod.GET)
- public @ResponseBody List<IdNameValue> getReportOwnerInList(HttpServletRequest request)
- throws IOException, RaptorException {
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
-
- List<IdNameValue> UserList = new ArrayList<IdNameValue>();
- List excludeValues = new java.util.ArrayList();
- HttpSession session = request.getSession();
- String query = Globals.getCustomizedScheduleQueryForUsers();
- session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
- String userId = AppUtils.getUserID(request);
- session.setAttribute("LOGGED_USERID", userId);
- 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 allUsers = AppUtils.getAllUsers(query, param, isAdmin);
- Vector result = new Vector(allUsers.size());
-
- for (Iterator iter = allUsers.iterator(); iter.hasNext();) {
- IdNameValue value = (IdNameValue) iter.next();
-
- boolean exclude = false;
- for (Iterator iterE = excludeValues.iterator(); iterE.hasNext();)
- if (((IdNameValue) iterE.next()).getId().equals(value.getId())) {
- exclude = true;
- break;
- } // if
-
- if (!exclude)
- UserList.add(value);
- } // for
- return UserList;
- }
-
-
- @RequestMapping(value = { "/report/wizard/security/getReportSecurityInfo" }, method = RequestMethod.GET)
- public @ResponseBody Map<String,String> getReportSecurityInfo(HttpServletRequest request)
- throws IOException, RaptorException {
- Map<String, String> securityInfoMap = new HashMap<String,String>();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- String isPublic = Boolean.toString(rdef.isPublic());
- String createUser = AppUtils.getUserName(rdef.getCreateID());
- String createDate = rdef.getCreateDate();
- String updateUser = AppUtils.getUserName(rdef.getUpdateID());
- String updateDate = rdef.getUpdateDate();
- String ownerId = rdef.getOwnerID();
-
- securityInfoMap.put("isPublic",isPublic);
- securityInfoMap.put("createdUser",createUser);
- securityInfoMap.put("createdDate",createDate);
- securityInfoMap.put("updateUser",updateUser);
- securityInfoMap.put("updatedDate",updateDate);
- securityInfoMap.put("ownerId",ownerId);
-
- return securityInfoMap;
- }
-
- @RequestMapping(value = { "/report/wizard/security/getReportSecurityUsers" }, method = RequestMethod.GET)
- public @ResponseBody List<SecurityEntry> getReportSecurityUsers(HttpServletRequest request)
- throws IOException, RaptorException {
-
- List<SecurityEntry> reportUserMapList = new ArrayList<SecurityEntry>();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- Vector reportUsers = rdef.getReportUsers(request);
- int iCount = 0;
-
- for(Iterator iter=reportUsers.iterator(); iter.hasNext(); iCount++) {
- Map<String, String> reportUserMap = new HashMap<String,String>();
- SecurityEntry rUser = (SecurityEntry) iter.next();
- reportUserMapList.add(rUser);
- }
-
- return reportUserMapList;
- }
-
-
- @RequestMapping(value = { "/report/wizard/security/getReportSecurityRoles" }, method = RequestMethod.GET)
- public @ResponseBody List<SecurityEntry> getReportSecurityRoles(HttpServletRequest request)
- throws IOException, RaptorException {
-
- List<SecurityEntry> reportRoleList = new ArrayList<SecurityEntry>();
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- Vector reportRoles = rdef.getReportRoles(request);
- int iCount = 0;
-
- for(Iterator iter=reportRoles.iterator(); iter.hasNext(); iCount++) {
- SecurityEntry rRole = (SecurityEntry) iter.next();
- reportRoleList.add(rRole);
- }
-
- return reportRoleList;
- }
-
-
- @RequestMapping(value = { "/report/wizard/retrieve_def_tab_wise_data/{id}",
- "/report/wizard/retrieve_def_tab_wise_data/{id}/{detailId}" }, method = RequestMethod.GET)
- public @ResponseBody DefinitionJSON retrieveDefTabWiseData(@PathVariable Map<String, String> pathVariables,
- HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException {
- ReportDefinition rdef = null;
- ReportRuntime rr = null;
- boolean newReport = false;
- String tabId = "Def";
- String id = "";
-
- if (pathVariables.containsKey("id")) {
- id = pathVariables.get("id");
- }
- String detailId = "";
- if (pathVariables.containsKey("detailId")) {
- detailId = pathVariables.get("detailId");
- }
-
- ServletContext servletContext = request.getSession().getServletContext();
- if (!Globals.isSystemInitialized()) {
- Globals.initializeSystem(servletContext);
- }
-
- if (tabId.equals("Def") && id.equals("InSession")) {
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- newReport = false;
-
- } else if (tabId.equals("Def") && id.equals("Create")) {
- removeVariablesFromSession(request);
- rdef = (new ReportHandler()).loadReportDefinition(request, "-1");
- rdef.setReportType(AppConstants.RT_LINEAR);
- newReport = true;
-
- } else if (tabId.equals("Def") && AppUtils.nvl(id).length() > 0) {
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
-
- if (rdef != null && !rdef.getReportID().equals(id)) {
- request.getSession().removeAttribute(AppConstants.SI_REPORT_DEFINITION);
- removeVariablesFromSession(request);
- rdef = (new ReportHandler()).loadReportDefinition(request, id);
- request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
- } else if (rr != null && !rr.getReportID().equals(id)) {
- request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);
- removeVariablesFromSession(request);
- rdef = (new ReportHandler()).loadReportDefinition(request, id);
- request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
- } else if (rdef == null) {
- rdef = (new ReportHandler()).loadReportDefinition(request, id);
- request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
- }
- newReport = false;
-
- } else {
- rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- }
- DefinitionJSON wizardJSON = new DefinitionJSON();
- if (tabId.equals("Def")) {
- wizardJSON.setTabId("Def");
- wizardJSON.setTabName("Definition");
-
- wizardJSON.setReportId((rdef != null) ? rdef.getReportID() + "" : "");
- wizardJSON.setReportName((rdef != null) ? rdef.getReportName() : "");
- wizardJSON.setReportDescr((rdef != null) ? rdef.getReportDescr() : "");
- wizardJSON.setReportType((rdef != null) ? rdef.getReportType() : AppConstants.RT_LINEAR);
- wizardJSON.setDbInfo((rdef != null) ? rdef.getDBInfo() : "");
- wizardJSON.setFormHelpText((rdef != null) ? rdef.getFormHelpText() : "");
- wizardJSON.setPageSize((rdef != null) ? rdef.getPageSize() : 50);
- List<IdNameBooleanJSON> displayArea = new ArrayList<IdNameBooleanJSON>();
- IdNameBooleanJSON idNameJSON = new IdNameBooleanJSON();
- String qMenu = "";
- for (int i = 0; i < AppUtils.getQuickLinksMenuIDs().size(); i++) {
- idNameJSON = new IdNameBooleanJSON();
- qMenu = (String) AppUtils.getQuickLinksMenuIDs().get(i);
- idNameJSON.setId(qMenu);
- idNameJSON.setName(qMenu);
- if (rdef != null && (rdef.getMenuID().equals(qMenu))) {
- idNameJSON.setSelected(true);
- }
- displayArea.add(idNameJSON);
- }
- wizardJSON.setDisplayArea(displayArea);
- wizardJSON.setHideFormFieldsAfterRun((rdef != null) ? rdef.isHideFormFieldAfterRun() : false);
- wizardJSON.setMaxRowsInExcelCSVDownload((rdef != null) ? rdef.getMaxRowsInExcelDownload() : 500);
- wizardJSON.setFrozenColumns((rdef != null) ? rdef.getFrozenColumns() : 0);
- wizardJSON.setDataGridAlign((rdef != null) ? rdef.getDataGridAlign() : "left");
- wizardJSON.setEmptyMessage((rdef != null) ? rdef.getEmptyMessage() : "No records found");
- wizardJSON.setDataContainerHeight((rdef != null) ? rdef.getDataContainerHeight() : "600");
- wizardJSON.setDataContainerWidth((rdef != null) ? rdef.getDataContainerWidth() : "900");
- List<NameBooleanJSON> displayOptions = new ArrayList<NameBooleanJSON>();
- NameBooleanJSON nameBooleanJSON = new NameBooleanJSON();
- nameBooleanJSON.setName("HideFormFields");
- nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideForm() : false);
- displayOptions.add(nameBooleanJSON);
-
- nameBooleanJSON = new NameBooleanJSON();
- nameBooleanJSON.setName("HideChart");
- nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideChart() : false);
- displayOptions.add(nameBooleanJSON);
-
- nameBooleanJSON = new NameBooleanJSON();
- nameBooleanJSON.setName("HideReportData");
- nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideData() : false);
- displayOptions.add(nameBooleanJSON);
-
- nameBooleanJSON = new NameBooleanJSON();
- nameBooleanJSON.setName("HideExcel");
- nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHideExcelIcons() : false);
- displayOptions.add(nameBooleanJSON);
-
- nameBooleanJSON = new NameBooleanJSON();
- nameBooleanJSON.setName("HidePdf");
- nameBooleanJSON.setSelected((rdef != null) ? rdef.isDisplayOptionHidePDFIcons() : false);
- displayOptions.add(nameBooleanJSON);
-
- wizardJSON.setDisplayOptions(displayOptions);
-
- wizardJSON.setRuntimeColSortDisabled((rdef != null) ? rdef.isRuntimeColSortDisabled() : false);
- wizardJSON.setNumFormCols((rdef != null) ? rdef.getNumFormColsAsInt() : 1);
- wizardJSON.setReportTitle((rdef != null) ? rdef.getReportTitle() : "");
- wizardJSON.setReportSubTitle((rdef != null) ? rdef.getReportSubTitle() : "");
-
- }
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-
- return wizardJSON;
-
- }
-
- @RequestMapping(value = "/report/wizard/retrieve_data/{validate}", method = RequestMethod.POST)
- public @ResponseBody RaptorResponse retrieveDataForGivenQuery(@PathVariable("validate") boolean validate,
- @RequestBody QueryJSON queryJSON, HttpServletRequest request, HttpServletResponse response)
- throws IOException, RaptorException {
- RaptorResponse raptorResponse = new RaptorResponse();
- String sql = queryJSON.getQuery();
- String jsonInString = "";
-
- ServletContext servletContext = request.getSession().getServletContext();
- if (!Globals.isSystemInitialized()) {
- Globals.initializeSystem(servletContext);
- }
-
- ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
- if (rdef == null) {
- ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
- errorJSONRuntime.setErrormessage("Report Definition is not in session;");
- errorJSONRuntime.setStacktrace("");
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-
- try {
- jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
- raptorResponse.data().put("elements", jsonInString);
- return raptorResponse;
- } catch (Exception ex1) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex1);
- }
- } else {
- if (!sql.trim().toUpperCase().startsWith("SELECT")) {
- ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
- errorJSONRuntime.setErrormessage("Invalid statement - the SQL must start with the keyword SELECT");
- errorJSONRuntime.setStacktrace("SQL Error");
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-
- try {
- jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
- raptorResponse.data().put("elements", jsonInString);
- return raptorResponse;
-
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex);
- }
- } else {
- DataSet ds = null;
- String remoteDb = request.getParameter("remoteDbPrefix");
- // comment below two lines to test
- String remoteDbPrefix = (remoteDb != null && !remoteDb.equalsIgnoreCase("null")) ? remoteDb
- : rdef.getDBInfo();
- String userId = AppUtils.getUserID(request);
- // String userId = "1";
- sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId);
- sql = Utils.replaceInString(sql, "[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++) {
- 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));
- try {
-
- response.setContentType("application/json");
- ds = ConnectionUtils.getDataSet(sql, "local", true);
-
- QueryResultJSON queryResultJSON = new QueryResultJSON();
- queryResultJSON.setQuery(queryJSON.getQuery());
- String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
- rdef.parseReportSQL(query);
- queryResultJSON.setQuery(query);
-
- int numColumns = ds.getColumnCount();
- queryResultJSON.setTotalRows(ds.getRowCount());
-
- int count = 0;
- Map<String, String> dvJSON = null;
- ArrayList<String> colList = new ArrayList<String>();
- ArrayList<Map<String, String>> reportDataRows = new ArrayList<Map<String, String>>();
- if (!ds.isEmpty()) {
- count = 0;
-
- for (int i = 0; i < ds.getColumnCount(); i++) {
- colList.add(ds.getColumnName(i));
- }
- queryResultJSON.setReportDataColumns(colList);
- if (queryResultJSON.getTotalRows() > 0) {
- count = 0;
- dvJSON = new HashMap<String, String>();
- for (int r = 0; r < Math.min(ds.getRowCount(), 100); r++) {
- dvJSON = new HashMap<String, String>();
- for (int c = 0; c < ds.getColumnCount(); c++) {
- try {
- dvJSON.put(ds.getColumnName(c), ds.getString(r, c));
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].",
- ex);
- }
- }
- reportDataRows.add(dvJSON);
-
- }
- }
-
- }
- queryResultJSON.setReportDataRows(reportDataRows);
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- if (validate) {
- query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
- request.setAttribute("sqlValidated", "N");
- rdef.parseReportSQL(query);
- request.setAttribute("sqlValidated", "Y");
- persistReportDefinition(request, rdef);
-
- }
- try {
- jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(queryResultJSON);
- raptorResponse.data().put("elements", jsonInString);
- return raptorResponse;
-
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery]. RaptorException: ",
- ex);
- }
- } catch (ReportSQLException ex) {
- ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
- if (sql.contains("[")) {
- errorJSONRuntime.setErrormessage(
- "Formfield information is present in the query, hence couldn't execute");
- errorJSONRuntime
- .setStacktrace("Formfield information is present in the query, hence couldn't execute");
- if (validate) {
- String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
- request.setAttribute("sqlValidated", "N");
- rdef.parseReportSQL(query);
- request.setAttribute("sqlValidated", "Y");
- persistReportDefinition(request, rdef);
-
- }
-
- } else {
- errorJSONRuntime.setErrormessage(ex.getMessage());
- errorJSONRuntime.setStacktrace(getStackTrace(ex));
- }
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-
- try {
- jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
- raptorResponse.data().put("elements", jsonInString);
- return raptorResponse;
-
- } catch (Exception ex1) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [retrieveDataForGivenQuery].", ex1);
- }
- }
- if (validate) {
- String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery());
- request.setAttribute("sqlValidated", "N");
- rdef.parseReportSQL(query);
- request.setAttribute("sqlValidated", "Y");
- persistReportDefinition(request, rdef);
-
- }
-
- }
- }
- raptorResponse.data().put("elements", jsonInString);
- return raptorResponse;
-
- }
-
- @RequestMapping(value = "save_chart", method = RequestMethod.POST)
- public void reportChartReceive(@RequestBody ChartJSON chartJSON, HttpServletRequest request,
- HttpServletResponse response) throws IOException {
- ReportRuntime reportRuntime;
- reportRuntime = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); // changing
- // session
- // to
- // request
- String reportID = request.getParameter("c_master");
- if (reportRuntime == null && AppUtils.nvl(reportID).length() > 0) {
- try {
- ReportHandler rh = new ReportHandler();
- reportRuntime = rh.loadReportRuntime(request, reportID);
- } catch (RaptorException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [reportChartReceive].", ex);
- }
- }
-
- if (reportRuntime != null) {
- String chartType = chartJSON.getChartType();
- reportRuntime.setChartType(chartJSON.getChartType());
- reportRuntime.setChartAnimate(chartJSON.isAnimation());
- reportRuntime.setChartWidth(chartJSON.getWidth());
- reportRuntime.setChartHeight(chartJSON.getHeight());
- reportRuntime.setShowChartTitle(chartJSON.isShowTitle());
-
- String domainAxis = null;
- domainAxis = chartJSON.getDomainAxis();
-
- List<DataColumnType> reportCols = reportRuntime.getAllColumns();
-
- for (Iterator<DataColumnType> iter = reportCols.iterator(); iter.hasNext();) {
- DataColumnType dct = (DataColumnType) iter.next();
- if (dct.getColId().equals(domainAxis)) {
- dct.setColOnChart(AppConstants.GC_LEGEND);
- } else {
- dct.setColOnChart(null);
- }
- }
-
- CategoryAxisJSON categoryAxisJSON = chartJSON.getCategoryAxisJSON();
- String categoryAxis = null;
-
- categoryAxis = (categoryAxisJSON != null ? categoryAxisJSON.getValue() : "");
-
- reportCols = reportRuntime.getAllColumns();
-
- for (Iterator<DataColumnType> iter = reportCols.iterator(); iter.hasNext();) {
- DataColumnType dct = (DataColumnType) iter.next();
- if (dct.getColId().equals(categoryAxis)) {
- dct.setChartSeries(true);
- } else {
- dct.setChartSeries(false);
- }
- }
-
- ArrayList<RangeAxisJSON> rangeAxisList = chartJSON.getRangeAxisList();
- int r = 0;
- HashSet<String> removeRangeAxisMap = new HashSet<>();
- for(RangeAxisJSON rangeAxis:chartJSON.getRangeAxisRemoveList()){
- removeRangeAxisMap.add(rangeAxis.getRangeAxis());
- }
- for (int i = 0; i < rangeAxisList.size(); i++) {
- RangeAxisJSON rangeAxisJSON = rangeAxisList.get(i);
- String rangeAxis = rangeAxisJSON.getRangeAxis();
- String rangeYAxis = AppUtils.nvl(rangeAxisJSON.getRangeYAxis());
- String rangeChartGroup = AppUtils.nvl(rangeAxisJSON.getRangeChartGroup());
- String rangeColor = AppUtils.nvl(rangeAxisJSON.getRangeColor());
- String rangeLineType = AppUtils.nvl(rangeAxisJSON.getRangeLineType());
-
- rangefor: for (Iterator<DataColumnType> iterator = reportCols.iterator(); iterator.hasNext();) {
- DataColumnType dct = (DataColumnType) iterator.next();
- if (dct.getColId().equals(rangeAxis)) {
- if(removeRangeAxisMap.contains(rangeAxis))
- dct.setChartSeq(-1); // if we set it to -1, means this range axis will not be included
- else
- dct.setChartSeq(++r);
- dct.setColOnChart("0");
- dct.setYAxis(rangeYAxis); // +"|"+dct.getColId());
- dct.setChartGroup(rangeChartGroup); // +"|"+dct.getColId());
- dct.setChartColor(rangeColor);
- dct.setChartLineType(rangeLineType);
-
- if (chartType.equals(AppConstants.GT_ANNOTATION_CHART)
- || chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS)) {
- if (rangeAxisJSON.isShowAsArea()) {
- dct.setIsRangeAxisFilled(true);
- } else {
- dct.setIsRangeAxisFilled(false);
- }
- }
- break rangefor;
- }
- }
-
- }
-
- reportRuntime.setChartLeftAxisLabel(chartJSON.getPrimaryAxisLabel());
- reportRuntime.setChartRightAxisLabel(chartJSON.getSecondaryAxisLabel());
-
- reportRuntime.setRangeAxisLowerLimit(chartJSON.getMinRange());
- reportRuntime.setRangeAxisUpperLimit(chartJSON.getMaxRange());
-
- if (chartType.equals(AppConstants.GT_ANNOTATION_CHART)
- || chartType.equals(AppConstants.GT_FLEX_TIME_CHARTS)) {
- if (chartJSON.getFlexTimeSeriesChartOptions() != null) {
- reportRuntime.setZoomIn(chartJSON.getFlexTimeSeriesChartOptions().getZoomIn());
- reportRuntime.setTimeAxisType(chartJSON.getFlexTimeSeriesChartOptions().getTimeAxisType());
- }
-
- }
-
- if (chartType.equals(AppConstants.GT_TIME_SERIES)) {
- if (chartJSON.getTimeSeriesChartOptions() != null) {
- reportRuntime.setTimeSeriesRender(chartJSON.getTimeSeriesChartOptions().getLineChartRenderer());
- reportRuntime.setShowXAxisLabel(chartJSON.getTimeSeriesChartOptions().isShowXAxisLabel());
- reportRuntime.setAddXAxisTickers(chartJSON.getTimeSeriesChartOptions().isAddXAxisTicker());
- reportRuntime.setTimeAxis(chartJSON.getTimeSeriesChartOptions().isNonTimeAxis());
- reportRuntime.setMultiSeries(chartJSON.getTimeSeriesChartOptions().isMultiSeries());
- }
-
- }
-
- if (chartType.equals(AppConstants.GT_BAR_3D)) {
- if (chartJSON.getBarChartOptions() != null) {
- reportRuntime.setChartOrientation(
- chartJSON.getBarChartOptions().isVerticalOrientation() ? "vertical" : "horizontal");
- reportRuntime.setChartStacked(chartJSON.getBarChartOptions().isStackedChart());
- reportRuntime.setBarControls(chartJSON.getBarChartOptions().isDisplayBarControls());
- reportRuntime.setXAxisDateType(chartJSON.getBarChartOptions().isxAxisDateType());
- reportRuntime.setLessXaxisTickers(chartJSON.getBarChartOptions().isMinimizeXAxisTickers());
- reportRuntime.setTimeAxis(chartJSON.getBarChartOptions().isTimeAxis());
- reportRuntime.setLogScale(chartJSON.getBarChartOptions().isyAxisLogScale());
- }
- }
-
- reportRuntime.setLegendLabelAngle(chartJSON.getCommonChartOptions().getLegendLabelAngle());
- reportRuntime.setLegendPosition(chartJSON.getCommonChartOptions().getLegendPosition());
- reportRuntime.setChartLegendDisplay(chartJSON.getCommonChartOptions().isHideLegend() ? "Y" : "N");
- reportRuntime.setAnimateAnimatedChart(chartJSON.getCommonChartOptions().isAnimateAnimatedChart());
-
- reportRuntime.setTopMargin(chartJSON.getCommonChartOptions().getTopMargin());
- reportRuntime.setBottomMargin(chartJSON.getCommonChartOptions().getBottomMargin());
- reportRuntime.setLeftMargin(chartJSON.getCommonChartOptions().getLeftMargin());
- reportRuntime.setRightMargin(chartJSON.getCommonChartOptions().getRightMargin());
-
- for (Iterator<DataColumnType> iterator = reportCols.iterator(); iterator.hasNext();) {
- DataColumnType dct = (DataColumnType) iterator.next();
- if (!(AppUtils.nvl(dct.getColOnChart()).equals(AppConstants.GC_LEGEND)
- || (dct.getChartSeq() != null && dct.getChartSeq() > 0) || dct.isChartSeries())) {
- dct.setChartSeq(-1);
- dct.setChartColor(null);
- dct.setColOnChart(null);
- dct.setCreateInNewChart(false);
- dct.setChartGroup(null);
- dct.setYAxis(null);
- }
- }
-
- try {
- reportRuntime.persistLinearReport(request);
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "[Controller.processRequest]Invalid raptor action [reportChartReceive].", ex);
- }
- }
-
- }
-
- public String getViewName() {
- return viewName;
- }
-
- public void setViewName(String viewName) {
- this.viewName = viewName;
- }
-
- public String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- public String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
- public static String getStackTrace(Throwable aThrowable) {
- Writer result = new StringWriter();
- PrintWriter printWriter = new PrintWriter(result);
- aThrowable.printStackTrace(printWriter);
- return result.toString();
- }
-
- 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
-
- // Remove from session
- 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<String> enum1 = session.getAttributeNames();
- String attributeName = "";
- while (enum1.hasMoreElements()) {
- attributeName = enum1.nextElement();
- if (attributeName.startsWith("parent_")) {
- session.removeAttribute(attributeName);
- }
- }
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.system.fusion.web;
-
-
-import java.util.*;
-
-import javax.servlet.http.*;
-
-import org.openecomp.portalsdk.analytics.system.fusion.domain.CR_Report;
-import org.openecomp.portalsdk.analytics.system.fusion.service.RaptorService;
-import org.springframework.web.bind.*;
-import org.springframework.web.servlet.*;
-
-
-public class ReportsSearchListController {
-
- private RaptorService raptorService = null;
-
- /**
- * @return the raptorService
- */
- public RaptorService getRaptorService() {
- return raptorService;
- }
-
- /**
- * @param raptorService the raptorService to set
- */
- public void setRaptorService(RaptorService raptorService) {
- this.raptorService = raptorService;
- }
-
- public ModelAndView handleRequestInternal(HttpServletRequest request,
- HttpServletResponse response) {
-
- /*List items = null;
- int reportId = ServletRequestUtils.getIntParameter(request, "report_id", 0);
- String task = ServletRequestUtils.getStringParameter(request, "task", TASK_GET);
-
- HashMap additionalParams = new HashMap();
- additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request);
-
- if (reportId != 0 && task.equals(TASK_DELETE)) { // delete the selected record
- getRaptorService().deleteReport(new Long(reportId));
- }
-
- items = getRaptorService().getReports();
-
- Map model = new HashMap();
- model.put("items", items);
-
- return new ModelAndView(getViewName(), "model", model);
- */
- //return new ModelAndView(getViewName(), "model", null);
- System.out.println("Fill with proper code");
- return null;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.util;
-
-import java.awt.Color;
-
-import org.openecomp.portalsdk.analytics.model.base.*;
-
-/**<HR/>
- * This class is part of <B><I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I></B><BR/>
- * <HR/>
- *
- * --------------------------------------------------------------------------------------------------<BR/>
- * <B>AppConstants.java</B> - This class holds almost all shareable constants for RAPTOR.
- * --------------------------------------------------------------------------------------------------<BR/>
- *
- *
- * <U>Change Log</U><BR/><BR/>
- *
- * 27-Jul-2009 : Version 8.4 (Sundar); <UL><LI> Added PUBLIC constant for SearchHandler</LI></UL>
- * 14-Jul-2009 : Version 8.4 (Sundar); <UL><LI> New constants related to Dashboard is added.</LI></UL>
- * 29-Jun-2009 : Version 8.4 (Sundar); <UL><LI> New constants related to Compare To Prev Year Chart is added.</LI></UL>
- * 22-Jun-2009 : Version 8.4 (Sundar); <UL><LI> 3 new constants related to Pareto Chart, Multiple Time
- * Series and Time difference Chart.</LI></UL>
- *
- */
-
-public class AppConstants {
- // Session attribute IDs
- public final static String SI_BACKUP_FOR_REP_ID = "backup_for_report_id";
- public final static String SI_DASHBOARD_REP_ID = "dashboard_report_id";
- public final static String SI_DASHBOARD_REPORTRUNTIME_MAP = "dashboardReportRuntimeMap";
- public final static String SI_DASHBOARD_REPORTDATA_MAP = "dashboardReportDataMap";
- public final static String SI_DASHBOARD_CHARTDATA_MAP = "dashboardChartDataMap";
- public final static String SI_DASHBOARD_DISPLAYTYPE_MAP = "dashboardDisplayTypeMap";
- public final static String SI_DASHBOARD_REPORTRUNTIME = "dashboardRuntime";
- public final static String EMBEDDED_REPORTRUNTIME_MAP = "embeddedReportRuntimeMap";
- public final static String EMBEDDED_REPORTDATA_MAP = "embeddedReportDataMap";
-
- public final static String DRILLDOWN_INDEX = "drilldown_index";
- public final static String FORM_DRILLDOWN_INDEX = "form_drilldown_index";
-
- public final static String DRILLDOWN_REPORTS_LIST = "drilldownReportsList";
-
- public final static String SI_REPORT_RUN_BACKUP = "report_runtime_backup";
-
- public final static String SI_REPORT_RUNTIME = "report_runtime";
-
- public final static String SI_FORMFIELD_INFO = "formfield_info";
-
- public final static String SI_FORMFIELD_DOWNLOAD_INFO = "formfield_download_info";
-
- public final static String SI_REPORT_DEFINITION = "report_definition";
-
- public final static String SI_DATA_SIZE_FOR_TEXTFIELD_POPUP = "dataSizeForPopUp";
-
- public final static String SI_MAP_OBJECT = "novamap";
-
- public final static String SI_MAP = "raptorMap";
-
- // Added for Adhoc Scheduling
- public final static String SI_REPORT_SCHEDULE = "report_schedule";
-
- public final static String SI_COLUMN_LOOKUP = "column_lookup";
-
- // Request attribute IDs
- public final static String RI_ACTION = "r_action";
-
- public final static String RI_JAVASCRIPT_ITEM_ID = "javascriptItemId";
-
- // added for form field chaining in schedule tab
- public final static String SCHEDULE_ACTION = "N";
-
- public final static String RI_REFRESH = "refresh";
-
- public final static String RI_EXCEPTION = "c_exception";
-
- public final static String RI_ERROR_LIST = "c_error_list";
-
- public final static String RI_REPORT_ID = "c_master"; // should be
- // reportID not
- // c_master
- public final static String RI_DASHBOARD_ID = "c_dashboard";
-
- public final static String RI_DETAIL_ID = "c_detail"; // should be
- // detailID not
- // c_detail
-
- public final static String RI_REPORT_DATA = "report_data";
-
- public final static String RI_REPORT_DATA_WHOLE = "report_data_whole";
-
- public final static String RI_REPORT_SQL_WHOLE = "report_sql_whole";
-
- public final static String RI_CHART_DATA = "chart_data";
-
- public final static String RI_CHART_FORECAST_DATA = "chart_forecast_data";
-
- public final static String RI_CHART_TOTAL_COL = "chart_total"; // to show sub-totals
-
- public final static String RI_CHART_COLOR = "chart_color"; // to specify colors
-
- public final static String RI_CHART_INCLUDE = "chart_include"; //
-
- public final static String RI_CHART_MARKER_START = "chart_marker_start"; //marker line
-
- public final static String RI_CHART_MARKER_END = "chart_marker_end"; //marker line
-
- public final static String RI_CHART_MARKER_TEXT_LEFT = "chart_marker_text_left"; //marker line
-
- public final static String RI_CHART_MARKER_TEXT_RIGHT = "chart_marker_text_right"; //marker line
-
- public final static String RI_ANOMALY_TEXT = "anomaly_text"; //marker line
-
- public final static String RI_JAVASCRIPT = "javascriptElement";
-
- public final static String RI_PAGE_TITLE = "title";
-
- public final static String RI_PAGE_SUBTITLE = "subtitle";
-
- public final static String RI_NEXT_PAGE = "r_page";
-
- public final static String RI_PAGE_SIZE = "r_page_size";
-
- public final static String RI_RECORD_NO = "r_record";
-
- public final static String RI_NEXT_PAGE_SET = "r_page_set";
-
- public final static String RI_DATA_SIZE = "r_data_size";
-
- public final static String RI_SORT_ORDER = "sort_order";
-
- public final static String RI_USER_REPORTS = "user_reports";
-
- public final static String RI_PUBLIC_REPORTS = "public_reports";
-
- public final static String RI_FAVORITE_REPORTS = "favorite_reports";
-
- public final static String RI_F_REPORT_ID = "f_report_id";
-
- public final static String RI_F_REPORT_NAME = "f_report_name";
-
- public final static String RI_F_REPORT_CREATE_DATE = "f_report_create_date";
-
- public final static String RI_F_PUBLIC = "f_public";
-
- public final static String RI_F_OWNER_ID = "f_owner_id";
-
- public final static String RI_SEARCH_RESULT = "search_result";
-
- public final static String RI_JS_TARGET_FIELD = "js_target_field";
-
- public final static String RI_FIELD_NAME = "field_name";
-
- public final static String RI_COLUMN_ID = "column_id";
-
- public final static String RI_ARG_TYPE = "arg_type";
-
- public final static String RI_VIEW_ACTION = "view_action";
-
- public final static String RI_SOURCE_PAGE = "source_page";
-
- public final static String RI_GO_TO_STEP = "go_to_step";
-
- public final static String RI_WIZARD_ACTION = "wizard_action";
-
- public final static String RI_FORMATTED_SQL = "formatted_sql";
-
- public final static String RI_DATA_SET = "data_set";
-
- public final static String RI_FORM_FIELDS = "form_fields";
-
- public final static String RI_DISPLAY_CONTENT = "display_content";
-
- public final static String RI_SHOW_BACK_BTN = "show_back_btn";
-
- public final static String RI_GO_BACK = "go_back";
-
- public final static String RI_RESET_PARAMS = "reset_params";
-
- public final static String RI_RESET_ACTION = "reset_action";
-
- public final static String RI_VISUAL_ACTION = "v_action";
-
- public final static String RI_SEARCH_STRING = "search_string";
-
- public final static String RI_CONTAIN_FLAG = "contain_flag";
-
- public final static String RI_TABLE_NAME = "table_name";
-
- public final static String RI_DISPLAY_CHART = "display_chart";
-
- public final static String RI_CHK_FIELD_SQL = "check_field_sql";
-
- public final static String RI_EDIT_LINK = "edit_link";
-
- public final static String RI_SCHEDULE_LINK = "schedule_link";
-
- public final static String RI_LIST_CATEGORY = "raptor_list_category";
-
- public final static String RI_SCHEDULE_ID = "c_schedule"; // should be
- // reportID not
- // c_master
- public final static String RI_TEXTFIELD_POP = "forTextFieldPopUp"; // should be
-
-
- // Visualization actions
- public final static String VA_SHOW = "Show";
-
- public final static String VA_HIDE = "Hide";
-
- public final static String VA_SORT = "Sort";
-
- public final static String HIDDEN = "Hidden";
-
- // Wizard steps
- public final static String WS_DEFINITION = "Definition";
-
- public final static String WS_TABLES = "Tables";
-
- public final static String WS_SQL = "SQL";
-
- public final static String WS_COLUMNS = "Columns";
-
- public final static String WS_FORM_FIELDS = "Form Fields";
-
- public final static String WS_FILTERS = "Filters";
-
- public final static String WS_JAVASCRIPT = "Javascript";
-
- public final static String WS_SORTING = "Sorting";
-
- public final static String WS_CHART = "Chart";
-
- public final static String WS_USER_ACCESS = "Security";
-
- public final static String WS_DATA_FORECASTING = "Forecasting";
-
- public final static String WS_SCHEDULE = "Schedule";
-
- public final static String WS_REPORT_LOG = "Log";
-
- public final static String WS_RUN = "Run";
-
- /*****for report map******/
- public final static String WS_MAP = "Map";
-
-
-
- // Wizard sub-steps
- public final static String WSS_ADD = "Add";
-
- public final static String WSS_ADD_MULTI = "Add Multiple";
-
- public final static String WSS_ORDER_ALL = "Re-order All";
-
- public final static String WSS_EDIT = "Edit";
-
- public final static String WSS_DELETE = "Delete";
-
- public final static String WSS_ADD_BLANK = "Add Blank";
-
- public final static String WSS_INFO_BAR = "Display parameters";
-
- // Wizard actions
- public final static String WA_NEXT = "Next";
-
- public final static String WA_BACK = "Back";
-
- public final static String WA_ADD = "Add";
-
- public final static String WA_ADD_MULTI = "Add Multiple";
-
- public final static String WA_ORDER_ALL = "Re-order All";
-
- public final static String WA_EDIT = "Edit";
-
- public final static String WA_MODIFY = "Modify";
-
- public final static String WA_DELETE = "Delete";
-
- public final static String WA_SAVE = "Save";
-
- public final static String WA_MOVE_UP = "Move Up";
-
- public final static String WA_MOVE_DOWN = "Move Down";
-
- public final static String WA_ADD_USER = "Add User";
-
- public final static String WA_DELETE_USER = "Delete User";
-
- public final static String WA_GRANT_USER = "Grant User Access";
-
- public final static String WA_REVOKE_USER = "Revoke User Access";
-
- public final static String WA_ADD_ROLE = "Add Role";
-
- public final static String WA_DELETE_ROLE = "Delete Role";
-
- public final static String WA_GRANT_ROLE = "Grant Role Access";
-
- public final static String WA_REVOKE_ROLE = "Revoke Role Access";
-
- public final static String WA_VALIDATE = "Validate";
-
- // File types
- public final static String FT_ZIP = ".zip";
- public final static String FT_TXT = ".txt";
- public final static String FT_DAT = ".dat";
- public final static String FT_CSV = ".csv";
- public final static String FT_XLS = ".xls";
- public final static String FT_XLS_ALL = "_all.xls";
-
- public final static String FT_CSV_ALL = "_all.csv";
-
-
- public final static String FT_XML = ".xml";
-
- public final static String FT_SQL = ".sql";
- public final static String FT_COLUMNS = ".head";
-
- public final static String FILE_PREFIX = "cr_";
-
- // Chart types
- public final static String GT_BAR_3D = "BarChart3D";
-
- public final static String GT_HORIZ_BAR = "HorizontalBarChart";
-
- public final static String GT_STACKED_HORIZ_BAR = "HorizontalStackedBarChart";
-
- public final static String GT_STACKED_VERT_BAR = "VerticalStackedBarChart";
-
- public final static String GT_STACKED_HORIZ_BAR_LINES = "HorizontalStackedBarLinesChart";
-
- public final static String GT_STACKED_VERT_BAR_LINES = "VerticalStackedBarLinesChart";
-
- public final static String GT_VERT_BAR = "VerticalBarChart";
-
- public final static String GT_TOTAL_BAR = "TotalBarChart";
-
- public final static String GT_PIE_3D = "Pie3DChart";
-
- public final static String GT_PIE = "PieChart";
-
- public final static String GT_PIE_MULTIPLE = "MultiplePieChart";
-
- public final static String GT_TIME_SERIES = "TimeSeriesChart";
-
- public final static String GT_LINE = "LineChart";
-
- public final static String GT_SCATTER = "ScatterPlotChart";
-
- public final static String GT_HIERARCHICAL = "HierarchicalChart";
-
- public final static String GT_HIERARCHICAL_SUNBURST = "HierarchicalSunBurstChart";
-
- public final static String GT_REGRESSION = "RegressionPlotChart";
-
- public final static String GT_BAR_LINES = "BarLinesChart";
-
- public final static String GT_MULTI_SERIES_CHART = "MultiSeriesChart";
-
- public final static String GT_PARETO_CHART = "ParetoChart";
-
- public final static String GT_MULTIPLE_TIMESERIES_CHART = "MultipleTimeSeriesChart";
-
- public final static String GT_TIME_DIFFERENCE_CHART = "TimeDifferenceChart";
-
- public final static String GT_COMPARE_PREVYEAR_CHART = "CompareToPrevYear";
-
- public final static String GT_ANNOTATION_CHART = "AnnotationChart";
-
- public final static String GT_FLEX_TIME_CHARTS = "FlexTimeChart";
-
- // Non-standard chart types
-
- public final static String GT_STACK_BAR = "StackedBarChart";
-
- public static Color GREEN_COLOR = new Color(0, 128, 0);
-
- // chart filter
- public final static int CHART_ALL_COLUMNS = 0;
- public final static int CHART_WITHOUT_NEWCHART_COLUMNS = 1;
- public final static int CHART_NEWCHART_COLUMNS = 2;
-
- // chart colors
- public static Color[] CHART_SERIES_COLORS = { Color.black, GREEN_COLOR, Color.red,
- Color.blue, Color.magenta, Color.orange, Color.cyan, Color.pink, Color.yellow };
-
- // Chart columns
- public final static String GC_LEGEND = "LEGEND";
-
- /* Datamining Constants */
- public final static String DM_DATE_ATTR = "DM_DATE_ATTR";
- public final static String DM_FORECASTING_ATTR = "DM_FORECAST_ATTR";
- public final static String DM_GAUSSIAN_CLASSIFIER = "GAUSSIAN";
- public final static String DM_SVM_CLASSIFIER = "SVM";
-
- // Schedule recurrence
-
- public final static String SR_ONETIME = "ONE_TIME";
- public final static String SR_HOURLY = "HOURLY";
-
- public final static String SR_DAILY = "DAILY";
-
- public final static String SR_DAILY_MO_FR = "DAILY_MO_FR";
-
- public final static String SR_WEEKLY = "WEEKLY";
-
- public final static String SR_MONTHLY = "MONTHLY";
-
- // User access type
- public final static String UA_READ = "read";
-
- public final static String UA_WRITE = "write";
-
- public final static String UA_DELETE = "delete";
-
- // Semaphore Type
- public static final String ST_ROW = "ROW";
-
- public static final String ST_CELL = "CELL";
-
- // Sort Order
- public static final String SO_ASC = "ASC";
-
- public static final String SO_DESC = "DESC";
-
- // Report Log Action
- public static final String RLA_CREATE = "Report Created";
-
- public static final String RLA_UPDATE = "Report Updated";
-
- public static final String RLA_DELETE = "Report Deleted"; // Not used
-
- public static final String RLA_RUN = "Report Run";
-
- public static final String RLA_EXECUTION_TIME = "Report Execution Time";
-
- public static final String RLA_SCHEDULED_DOWNLOAD_EXCEL = "Scheduled and Generated in Excel";
-
- public static final String RLA_SCHEDULED_DOWNLOAD_PDF = "Scheduled and Generated in PDF";
-
- public static final String RLA_DOWNLOAD_EXCEL = "Generated in Excel";
-
- public static final String RLA_DOWNLOAD_PAGE_EXCEL = "Generated in Excel for the current Page";
-
- public static final String RLA_DOWNLOAD_EXCELX = "Generated in Excel 2007";
-
- public static final String RLA_SCHEDULED_DOWNLOAD_EXCELX = "Scheduled and Generated in Excel 2007";
-
- public static final String RLA_DOWNLOAD_PDF = "Generated in PDF";
-
- public static final String RLA_DOWNLOAD_CSV = "Generated in CSV";
-
- public static final String RLA_DOWNLOAD_TEXT = "Generated in TEXT";
-
- public static final String RLA_ERROR = "Error Occurred";
-
- public static final String RLA_FROM_LOG = "From Log List";
-
- // Drill-down extra date columns extension
- public static final String DD_COL_EXTENSION = "_dde";
-
- // Column "don't attempt to parse as date" flag - currently placed in the
- // comment
- public static final String CF_NO_PARSE_DATE = "NO_PARSE_DATE";
-
- /**
- * *************** Transferred from CustomReportWrapper
- * *********************
- */
-
- // Default Oracle date format
- public static final String DEFAULT_DATE_FORMAT = "%m/%d/%Y";
-
- // Java date formats
- public static final String JAVA_DATE_FORMAT_MMDDYYYY = "MM/dd/yyyy";
-
- public static final String JAVA_DATE_FORMAT_MMDDYYYY_HR = "MM/dd/yyyy hh aaa" ; //01-SEP-2013 00 AM
-
- public static final String JAVA_DATE_FORMAT_MMYYYY = "MM/yyyy";
-
- public static final String JAVA_DATE_FORMAT_DDMONYYYY = "dd-MMM-yyyy";
-
- public static final String JAVA_DATE_FORMAT_DDMONYYYY_HR = "dd-MMM-yyyy hh aaa" ; //01-SEP-2013 00 AM
-
- public static final String JAVA_DATE_FORMAT_MONTHDDYYYY = "MMMMMMMM dd, yyyy";
-
- public static final String JAVA_DATE_FORMAT_MONTHYYYY = "MMMMMMMM, yyyy";
-
- // Filter predefined values
- public static final String FILTER_MAX_VALUE = "[MAX_VALUE]"; // Max value
- // in that
- // database
- // column
-
- public static final String FILTER_MIN_VALUE = "[MIN_VALUE]"; // Min value
- // in that
- // database
- // column
-
- // Column type constants
- public static final String CT_CHAR = "VARCHAR2";
-
- public static final String CT_NUMBER = "NUMBER";
-
- public static final String CT_DATE = "DATE";
-
- public static final String CT_HYPERLINK = "HYPERLINK";
-
- public static final String CT_TIMESTAMP = "TIMESTAMP";
-
- // Filter argument type constants
- public static final String AT_FORMULA = "FORMULA"; // Exact expression -
- // can be anything as
- // long as fits in the
- // SQL statement
-
- public static final String AT_VALUE = "VALUE"; // Constant value - example
- // 35 or Amsterdam or
- // 11/25/2004
-
- public static final String AT_LIST = "LIST"; // List of constant value -
- // must include formatting -
- // like 'a','b' or
- // TO_DATE('11/11/2001','MM/DD/YYYY'),TO_DATE('02/11/2001','MM/DD/YYYY')
-
- public static final String AT_COLUMN = "COLUMN"; // Column id of one of
- // the columns in the
- // report
-
- public static final String AT_FORM = "FORM"; // To be inserted in a form
- // before running the report
-
- // Report type constants
- public static final String RT_LINEAR = "Linear";
-
- public static final String RT_CROSSTAB = "Cross-Tab";
-
- public static final String RT_DASHBOARD = "Dashboard";
- public static final String RT_HIVE = "Hive";
-
- // Report definition type constants
- public static final String RD_VISUAL = "Visual";
-
- public static final String RD_SQL_BASED = "SQL-based";
-
- public static final String RD_SQL_BASED_DATAMIN = "SQL-based_Datamining";
-
- // Column cross-tab position
- public static final String CV_ROW = "ROW";
-
- public static final String CV_COLUMN = "COLUMN";
-
- public static final String CV_VALUE = "VALUE";
-
- // Outer join type constants
- public static final String OJ_CURRENT = "CURRENT"; // cur_table (+) =
- // join_table
-
- public static final String OJ_JOINED = "JOINED"; // cur_table =
- // join_table (+)
-
- // List of Available Total Functions
- public static final String TOTAL_SUM_ID = "SUM(";
-
- public static IdNameList TOTAL_FUNCTIONS = new IdNameList();
-
- public static final String DB_LOCAL = "local";
-
- public static final String DB_DEV = "dev";
-
- public static final String DB_PROD = "prod";
-
- public static final String SHELL_SCRIPT_NAME = "dwnldflatfile.sh";
-
- public static final String SCHEDULE_SHELL_SCRIPT_NAME = "dwnldflatfileschedule.sh";
-
- public static final String SHELL_QUERY_DIR = "query/";
-
- public static final String SHELL_SCRIPTS_DIR = "scripts/";
-
- public static final String SHELL_DATA_DIR = "data/";
-
- public static final int WEB_VERSION = 0;
-
- public static final int IPHONE_VERSION = 1;
-
- public static final String MYSQL = "mysql";
- public static final String ORACLE = "oracle";
- public static final String POSTGRESQL = "postgresql";
-
- // COLORS to be used in Excel
- public static String Aqua = "#00FFFF";
- public static String Black = "#000000";
- public static String Blue = "#0000FF";
- public static String Fuchsia = "#FF00FF";
- public static String Gray = "#808080";
- public static String Green = "#008000";
- public static String Lime = "#00FF00";
- public static String Maroon = "#800000";
- public static String Navy = "#000080";
- public static String Olive = "#808000";
- public static String Orange = "#FF9900";
- public static String Purple = "#800080";
- public static String Red = "#FF0000";
- public static String Silver = "#C0C0C0";
- public static String Teal = "#008080";
- public static String White = "#FFFFFF";
- public static String Yellow = "#FFFF00";
- // End
- public static void initializeAppConstants() {
- // Initialize TOTAL_FUNCTIONS
- if (TOTAL_FUNCTIONS.getCount() == 0) {
- TOTAL_FUNCTIONS.addValue(TOTAL_SUM_ID, "Sum");
- TOTAL_FUNCTIONS.addValue("MAX(", "Max");
- TOTAL_FUNCTIONS.addValue("MIN(", "Min");
- TOTAL_FUNCTIONS.addValue("COUNT(ALL ", "Count All");
- TOTAL_FUNCTIONS.addValue("COUNT(DISTINCT ", "Count Distinct");
- TOTAL_FUNCTIONS.addValue("AVG(ALL ", "Average All");
- TOTAL_FUNCTIONS.addValue("AVG(DISTINCT ", "Average Distinct");
- TOTAL_FUNCTIONS.addValue("VARIANCE(ALL ", "Variance All");
- TOTAL_FUNCTIONS.addValue("VARIANCE(DISTINCT ", "Variance Distinct");
- TOTAL_FUNCTIONS.addValue("STDDEV(ALL ", "Standard Deviation All");
- TOTAL_FUNCTIONS.addValue("STDDEV(DISTINCT ", "Standard Deviation Distinct");
- TOTAL_FUNCTIONS.addValue("AVG(ALL +STDDEV(ALL ",
- "Average + Standard Deviation All");
- TOTAL_FUNCTIONS.addValue("AVG(ALL +2*STDDEV(ALL ",
- "Average + 2 * Standard Deviation All");
- TOTAL_FUNCTIONS.addValue("AVG(ALL -STDDEV(ALL ",
- "Average - Standard Deviation All");
- TOTAL_FUNCTIONS.addValue("AVG(ALL -2*STDDEV(ALL ",
- "Average - 2 * Standard Deviation All");
- } // if
-
- // ...
- } // initializeAppConstants
-
-} // AppConstants
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.util;
-
-import java.io.Serializable;
-import java.sql.*;
-import java.util.*;
-
-import org.openecomp.portalsdk.analytics.system.Globals;
-
-public class DataSet extends Vector implements Serializable {
- private Vector columnNames = null;
-
- private Vector columnTypes = null;
-
- public DataSet(ResultSet rs) throws SQLException {
- this(rs, Integer.MAX_VALUE);
- } // DataSet
-
- public DataSet(ResultSet rs, int maxRowLimit) throws SQLException {
- ResultSetMetaData rsmd = rs.getMetaData();
- int mb = 1024*1024;
- Runtime runtime = Runtime.getRuntime();
-
- int colCount = rsmd.getColumnCount();
- columnNames = new Vector(colCount);
- columnTypes = new Vector(colCount);
- for (int i = 1; i <= colCount; i++) {
- columnNames.add(rsmd.getColumnLabel(i)); // getColumnLabel ??
- columnTypes.add(rsmd.getColumnTypeName(i));
- } // for
-
- while (rs.next() && size() < maxRowLimit) {
-// if(runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*(Globals.getMemoryThreshold()*2)/100) ) {
-// System.out.println("freeMemory " + runtime.freeMemory());
-// System.out.println("Max Memory " + runtime.maxMemory());
-// System.out.println("If Logic " + (runtime.freeMemory()/mb <= ((runtime.maxMemory()/mb)*(Globals.getMemoryThreshold()*2)/100)));
-// break;
-// }
-
- Vector v = new Vector(colCount);
- for (int i = 1; i <= colCount; i++)
- v.add(rs.getString(i));
- add(v);
- } // while
-
- if(rs!=null)
- rs.close();
- } // DataSet
-
- public DataSet() {
- columnNames = new Vector();
- columnTypes = new Vector();
- } // DataSet
-
- public void insertRow(int rowIdx) {
- if (rowIdx > size())
- rowIdx = size();
-
- Vector v = new Vector(columnNames.size());
- for (int i = 0; i < columnNames.size(); i++)
- v.add("");
- add(rowIdx, v);
- } // insertRow
-
- public void insertColumn(int colIdx, String colName) {
- insertColumn(colIdx, colName, "VARCHAR2");
- } // insertColumn
-
- public void insertColumn(int colIdx, String colName, String colType) {
- if (colIdx > columnNames.size())
- colIdx = columnNames.size();
-
- columnNames.add(colIdx, colName);
- columnTypes.add(colIdx, colType);
-
- for (int i = 0; i < size(); i++)
- ((Vector) get(i)).add(colIdx, "");
- } // insertColumn
-
- public void setValue(int rowIdx, int colIdx, String value) {
- ((Vector) get(rowIdx)).set(colIdx, value);
- } // setValue
-
- public void setValue(int rowIdx, String colName, String value) {
- ((Vector) get(rowIdx)).set(getColumnIndex(colName), value);
- } // setValue
-
- public void setString(int rowIdx, int colIdx, String value) {
- setValue(rowIdx, colIdx, value);
- } // setString
-
- public void setString(int rowIdx, String colName, String value) {
- setValue(rowIdx, colName, value);
- } // setString
-
- public int getRowCount() {
- return size();
- } // getRowCount()
-
- public int getColumnCount() {
- return columnNames.size();
- } // getColumnCount
-
- public String getColumnName(int colIdx) {
- return ((String) columnNames.get(colIdx));
- } // getColumnName
-
- public String getColumnType(int colIdx) {
- return ((String) columnTypes.get(colIdx));
- } // getColumnType
-
- public String getColumnType(String colName) {
- return getColumnType(getColumnIndex(colName));
- } // getColumnType
-
- public int getColumnIndex(String colName) {
- for (int i = 0; i < columnNames.size(); i++)
- if (colName.equalsIgnoreCase((String) columnNames.get(i)))
- return i;
-
- return -1;
- } // getColumnIndex
-
- public String getString(int rowIdx, int colIdx) {
- return nvl((String) ((Vector) get(rowIdx)).get(colIdx));
- } // getString
-
- public String getString(int rowIdx, String colName) {
- return getString(rowIdx, getColumnIndex(colName));
- } // getString
-
- public int getInt(int rowIdx, int colIdx) {
- return Integer.parseInt(getString(rowIdx, colIdx));
- } // getString
-
- public int getInt(int rowIdx, String colName) {
- return getInt(rowIdx, getColumnIndex(colName));
- } // getString
-
- public String getItem(int rowIdx, int colIdx) {
- return getString(rowIdx, colIdx);
- } // getItem
-
- public String getItem(int rowIdx, String colName) {
- return getString(rowIdx, colName);
- } // getItem
-
- /** *********************************************************************** */
-
- private String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- private String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
-} // DataSet
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.util;
-
-
-import java.util.HashMap;
-
-import org.apache.poi.hssf.util.HSSFColor;
-
-public class ExcelColorDef {
-
- public static HashMap colors = new HashMap();
-
- public static void initializeExcelColorDef() {
- colors.put("#00FFFF",new Short(HSSFColor.AQUA.index));
- colors.put("#000000",new Short(HSSFColor.BLACK.index));
- colors.put("#0000FF",new Short(HSSFColor.BLUE.index));
- colors.put("#FF00FF",new Short(HSSFColor.PINK.index));
- colors.put("#808080",new Short(HSSFColor.GREY_40_PERCENT.index));
- colors.put("#008000",new Short(HSSFColor.BRIGHT_GREEN.index));
- colors.put("#00FF00",new Short(HSSFColor.LIME.index));
- colors.put("#800000",new Short(HSSFColor.MAROON.index));
- colors.put("#000080",new Short(HSSFColor.ROYAL_BLUE.index));
- colors.put("#808000",new Short(HSSFColor.OLIVE_GREEN.index));
- colors.put("#FF9900",new Short(HSSFColor.ORANGE.index));
- colors.put("#800080",new Short(HSSFColor.VIOLET.index));
- colors.put("#FF0000",new Short(HSSFColor.RED.index));
- colors.put("#C0C0C0",new Short(HSSFColor.CORAL.index));
- colors.put("#008080",new Short(HSSFColor.TEAL.index));
- colors.put("#FFFFFF",new Short(HSSFColor.WHITE.index));
- colors.put("#FFFF00",new Short(HSSFColor.YELLOW.index));
-
- }
-
- public static short getExcelColor( String color) {
- if ((colors != null) && (colors.containsKey(color))) {
- return ((Short) colors.get(color)).shortValue();
- }
-
- return new Short(HSSFColor.WHITE.index).shortValue();
- }
-
- public static void main(String[] args) {
- // TODO Auto-generated method stub
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.util;
-
-import java.io.*;
-
-import org.openecomp.portalsdk.analytics.RaptorObject;
-
-public class HtmlStripper extends RaptorObject// this function can be accessed publicly
-{
-
- String filename;
- final char TXT_END_TAG = '>';
- final char TXT_START_TAG = '<';
-
- public String stripSpecialCharacters (String s) {
- s = nvl(s);
- StringBuffer sbuf = new StringBuffer();
- int c;
- int prev_char = 0;
- boolean inText = true;
- for (int i = 0; i < s.length(); i++) {
- // while c is not last character
- c = s.charAt(i);
- //System.out.println("444 Character " + (char)c + " int " + c);
- if ((char) c == TXT_END_TAG) {
- // if char == '>' text following
- // it and not HTML tag
- inText = true;
- } else if ((char) c == TXT_START_TAG) {
- // if char == '<' tag is
- // following not text
- inText = false;
- } /*else if ((char)c == '\n') {
- System.out.println("new line " + (char)c + " int " + c);
- inText = false;
- }*/ /*else if ((char) c == '&') {
- // if char == '&' chars following
- // are not text
- inText = false;
- }*/
- else if (inText) {
- // if text write char to "text.txt"
- //System.out.println("444444 Adding " + (char)c + " int " + c);
- if (c >= 32 && c <= 122) {
- if(c==32 || (c>32 && c<=47) || ( c>=58 && c<=64 )) {
- if (c == 45) {
- prev_char = 0;
- sbuf.append((char) 45);
- }
- else if(prev_char != 95) {
- prev_char = 95;
- sbuf.append((char) 95);
- }
- }
- else {
- prev_char=0;
- sbuf.append((char) c);
- }
- }
- }
- }
- //System.out.println("\n\nFinished processing: " + s + "\n\n");
- //System.out.println("\n\nThe processed String : " + sbuf.toString() + "\n\n");
- return sbuf.toString();
- }
-
- public String stripHtml(String s) {
-
- //System.out.println("Starting to process: " + s + "\n\n"); // prints
- s = nvl(s);
- StringBuffer sbuf = new StringBuffer();
- int c;
- boolean inText = true;
- for (int i = 0; i < s.length(); i++) {
- // while c is not last character
- c = s.charAt(i);
- if ((char) c == TXT_END_TAG) {
- // if char == '>' text following
- // it and not HTML tag
- inText = true;
- } else if ((char) c == TXT_START_TAG) {
- // if char == '<' tag is
- // following not text
- inText = false;
- } /*else if ((char)c == '\n') {
- System.out.println("new line " + (char)c + " int " + c);
- inText = false;
- }*/ /*else if ((char) c == '&') {
- // if char == '&' chars following
- // are not text
- inText = false;
- }*/
- else if (inText) {
- // if text write char to "text.txt"
- if (c >= 32 && c <= 122) {
- sbuf.append((char) c);
- }
- }
- }
- //System.out.println("\n\nFinished processing: " + s + "\n\n");
- //System.out.println("\n\nThe processed String : " + sbuf.toString() + "\n\n");
- int pos = 0 ;
- while(sbuf.indexOf(" ")!=-1) {
- pos = sbuf.indexOf(" ");
- sbuf.replace(pos, pos+6, " ");
- }
-
- return sbuf.toString();
- }
-
-
- public String stripCSVHtml (String s) {
- String s1 = stripHtml(s);
- //s1 = Utils.replaceInString(s1, "\"", "\"\"");
- s1 = s1.replaceAll("\"", "\"\"");
- return s1;
- }
-
- public static void main(String[] args) {
-
- String st = " Import: report name hello $ # " ;
- System.out.println("hello " + new HtmlStripper().stripSpecialCharacters(st));
- StringBuffer strBuf = new StringBuffer("");
- strBuf.append("<table class=\"mTAB\" border=\"0\" width=\"60%\">\n<tr class=\"rowalt1\">\n");
- strBuf.append(" <td>Charge To Account</td> <td>ABBZ2</td>\n");
- strBuf.append("</tr>\n");
- strBuf.append("<tr class=\"rowalt2\">");
- strBuf.append("<td>dateMonth</td> <td> 04/30/2008 </td>");
- strBuf.append("</tr>");
- strBuf.append("<tr class=\"rowalt1\">");
- strBuf.append("<td>Generated Date/Time</td> <td> 05/30/2008 06:15:16 PM GMT </td>");
- strBuf.append("</tr>");
- strBuf.append("<tr class=\"rowalt2\">");
- strBuf.append("<td>Login Id:</td> <td> sundar </td>");
- strBuf.append("</tr>");
- strBuf.append("</table>");
- new HtmlStripper().stripHtml(strBuf.toString());
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.util;
-
-public class Log {
-
- public Log() {
- }
-
- public static void write(String info) {
- System.out.println(info);
- } // write
-
- public static void write(String info, int debugLevel) {
- if (debugLevel <= org.openecomp.portalsdk.analytics.system.Globals.getDebugLevel())
- write(info);
- } // write
-
- public static void writeError(String info) {
- System.err.println(info);
- } // writeError
-
-} // Log
+++ /dev/null
-/*-
- * ================================================================================
- * 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.util;
-
-import java.util.HashMap;
-
-import org.openecomp.portalsdk.analytics.system.DbUtils;
-import org.openecomp.portalsdk.analytics.system.Globals;
-
-public class RemDbInfo {
- private HashMap remDbMap = null;
- private HashMap remDbTypeMap = null;
-
- public RemDbInfo() throws Exception {
- if (remDbMap == null) {
- load();
- }
- }
-
- public void load() throws Exception {
- remDbMap = new HashMap();
- remDbTypeMap = new HashMap();
- try {
- //String query = " SELECT a.SCHEMA_ID, a.SCHEMA_DESC, DATASOURCE_TYPE, rownum id FROM SCHEMA_INFO a " +
- // " where schema_id = 'local' union " +
- // " SELECT a.SCHEMA_ID, a.SCHEMA_DESC, DATASOURCE_TYPE, (rownum+1) id FROM SCHEMA_INFO a " +
- // " where schema_id <> 'local' order by id ";
- String query = Globals.getRemoteDbSchemaSql();
- DataSet ds = null;
- Globals.getDbUtils();
- ds = DbUtils.executeQuery(query);
-
- String prefix = "", desc = "", dbType = "";
-
- if(ds.getRowCount() > 0) {
- for (int i = 0; i < ds.getRowCount(); i++) {
- prefix = ds.getItem(i, 0);
- desc = ds.getItem(i, 1);
- dbType = ds.getItem(i, 2);
-
- remDbMap.put(prefix, desc);
- remDbTypeMap.put(prefix, dbType);
- }
- } else {
- remDbMap.put("local", "local");
- remDbTypeMap.put("local", Globals.getDBType());
- }
- }
- catch (Exception e) {}
-
- }
-
- public String getDesc(String prefix) {
- if ((remDbMap != null) && (remDbMap.containsKey(prefix))) {
- return (String) remDbMap.get(prefix);
- }
-
- return "";
- }
-
- public String getDBType(String prefix) {
- if ((remDbTypeMap != null) && (remDbTypeMap.containsKey(prefix))) {
- return (String) remDbTypeMap.get(prefix);
- }
-
- return "";
- }
-
- public HashMap getDbHash() {
- return remDbMap;
- }
-
- public HashMap getDbTypeHash() {
- return remDbTypeMap;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.util;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
-public class SQLCorrector {
-
- static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SQLCorrector.class);
-
-
- public String fixSQL(StringBuffer sql) {
-
- int pos = 0;
- //int pos_f_select_from = 0;
- int pos_f_select_to = 0;
- int pos_s_select_from = 0;
- int pos_s_select_to = 0;
- int pos_dup_select = 0;
- int pos_dup_select1 = 0;
- int pos_f_format = 0;
- int pos_t_format = 0;
- int pos_alias_format = 0;
- int pos_alias = 0;
- String format = "";
- String alias = null;
- String sql2 = Utils.replaceInString(sql.toString(), "\n", " ");
- sql2 = Utils.replaceInString(sql2, "\t", " ");
- sql = new StringBuffer(sql2);
- if (sql.indexOf("FROM", 2) != -1) {
- pos = sql.indexOf("FROM", 2);
- pos_f_select_to = sql.indexOf("FROM", 2);
- if (sql.indexOf("SELECT", pos)!=-1) {
- pos = sql.indexOf("SELECT", pos);
- pos_s_select_from = pos;
- pos_dup_select1 = pos;
- //System.out.println(pos);
- if (sql.indexOf("FROM", pos)!=-1) {
- pos = sql.indexOf("FROM", pos);
- pos_dup_select = sql.lastIndexOf("SELECT",pos);
- while(pos_dup_select > pos_dup_select1) {
- pos_dup_select1 = pos_dup_select;
- pos = sql.indexOf("FROM", pos + 2);
- pos_dup_select = sql.lastIndexOf("SELECT",pos);
- }
- pos_s_select_to = pos;
-
- }
- }
- }
-
- String o_sql = sql.substring(0, pos_f_select_to-1);
- String i_sql = sql.substring(pos_s_select_from, pos_s_select_to-1);
- o_sql = o_sql.toUpperCase();
- i_sql = i_sql.toUpperCase();
- String outer_sql = o_sql.substring(o_sql.indexOf("SELECT")+7);
- String inner_sql = i_sql.substring(i_sql.indexOf("SELECT")+7);
- logger.debug(EELFLoggerDelegate.debugLogger, ("|"+inner_sql+"|"));
- String outer_cols[] = outer_sql.split(",");
- //inner_sql = inner_sql.replaceAll(", '", ",'");
-
- String inner_cols[] = inner_sql.split(", ");
- inner_cols = removeExtraSpace(inner_cols);
- logger.debug(EELFLoggerDelegate.debugLogger, ("*******OuterCols ********"));
- printArray(outer_cols);
- logger.debug(EELFLoggerDelegate.debugLogger, ("\n*******InnerCols********"));
- printArray(inner_cols);
- logger.debug(EELFLoggerDelegate.debugLogger, ("\n********Replacing Elements*****"));
- ArrayList elements = findSum(outer_cols);
- logger.debug(EELFLoggerDelegate.debugLogger, ("In Fix SQL " + elements.size()));
- printArrayList(elements);
- HashMap elementFormatMap = matchAndGetFormatInInnerCol(elements, inner_cols);
- ArrayList outerReplacedCols = replaceOuterCols(elementFormatMap, outer_cols);
- String finalSql = generateSQL(outerReplacedCols, sql.toString());
- return finalSql;
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
-
- SQLCorrector s = new SQLCorrector();
- StringBuffer strBuf = new StringBuffer();
- strBuf.append("SELECT NULL TOTAL_BILLMONTH, NULL TOTAL_ACCOUNTNUMBER, NULL TOTAL_SECTORCODE, NULL TOTAL_BUSINESS_UNIT_CODE, NULL TOTAL_BILLINGSITEID, NULL TOTAL_SITEADDRESS, NULL TOTAL_SITECITY, NULL TOTAL_SITESTATE, NULL TOTAL_VENDORNAME, NULL TOTAL_INVOICENUMBER, NULL TOTAL_INVOICEDATE, NULL TOTAL_SERVICEDESCRIPTION, SUM(INVOICEAMOUNT) TOTAL_INVOICEAMOUNT FROM (SELECT '2006/09/16 - 2006/10/15' BillMonth, account_number AccountNumber, (select distinct sector_code FROM billing_site where business_unit_code = BU) SectorCode, BU||' - '||(select distinct business_unit_name FROM billing_site where business_unit_code = BU) Business_Unit_Code, Site_ID BillingSiteID, site_address1 SiteAddress, site_city SiteCity, site_state SiteState, Vendor_Site_Name VendorName, invoice_number InvoiceNumber, to_char(invoice_date,'YYYY/MM/DD') InvoiceDate, billing_service_description ServiceDescription, to_char(payment_amount,'9,999,999.99') InvoiceAmount");
- strBuf.append(" FROM cis_gm_passthrough ");
- strBuf.append(" where ");
- strBuf.append(" BU = decode(upper('ALL'), 'ALL', BU, substr('ALL', 1, 3)) ");
- strBuf.append(" and BU in (SELECT distinct business_unit_code FROM billing_site where ");
- strBuf.append(" sector_code = decode('ALL', 'ALL', sector_code, 'ALL') ");
- strBuf.append(" and CHECK_USER_SECURITY(10, 'BUSINESS_UNIT_CODE', business_unit_code)='Y') ");
- strBuf.append(" and to_char(bill_cycle_start_date, 'YYYY/MM/DD') = substr('2006/09/16 - 2006/10/15', 1, 10) ");
- strBuf.append(" and to_char(bill_cycle_end_date, 'YYYY/MM/DD') = substr('2006/09/16 - 2006/10/15', 14, 10)");
- strBuf.append(" order by business_unit_code, sitecity, sitestate, invoicedate, servicedescription ) totalSQL ");
- String sql = strBuf.toString();
- String fix_sql = s.fixSQL(new StringBuffer(sql.toUpperCase()));
- logger.debug(EELFLoggerDelegate.debugLogger, (fix_sql));
- // TODO Auto-generated method stub
-
- }
-
- private String[] removeExtraSpace (String[] inner_cols) {
- String [] fixed_cols = new String[inner_cols.length];
- for (int i = 0; i < inner_cols.length; i++) {
- fixed_cols[i] = inner_cols[i].replaceAll(", '", ",'");
- }
- return fixed_cols;
- }
-
- private void printArray (String[] arr) {
- logger.debug(EELFLoggerDelegate.debugLogger, (""));
- for (int i = 0; i < arr.length; i++) {
- System.out.print(arr[i].trim());
- if(i<arr.length-1)
- logger.debug(EELFLoggerDelegate.debugLogger, (","));
- }
- }
-
- private void printArrayList (ArrayList arrList) {
- logger.debug(EELFLoggerDelegate.debugLogger, (" ArrayList "));
- for (int i = 0; i < arrList.size(); i++) {
- System.out.print(arrList.get(i));
- if(i<arrList.size()-1)
- logger.debug(EELFLoggerDelegate.debugLogger, (","));
- }
- }
-
- private ArrayList findSum (String[] arr ) {
- CharSequence inputString = null;
- Pattern pattern = null;
- Matcher matcher = null;
- ArrayList elements = new ArrayList();
- boolean b = false;
- for (int i = 0; i < arr.length; i++) {
- //System.out.print(arr[i].trim());
- inputString = arr[i].trim();
- //debugLogger.debug(inputString);
- //String keyPattern = "/SUM(|AVG|COUNT|STDDEV/";
- String keyPattern = "SUM\\(|AVG\\(|COUNT\\(|STDDEV\\(|VARIANCE\\(|SUM \\(|AVG \\(|COUNT \\(|STDDEV \\(|VARIANCE \\(";
- pattern = Pattern.compile(keyPattern);
- matcher = pattern.matcher(inputString);
- b = matcher.find();
- //debugLogger.debug(b);
- if(b) {
- elements.add(arr[i].trim());
- }
- }
- //debugLogger.debug("In Find Sum " + elements.size());
- return elements;
-
- }
-
-
- private HashMap matchAndGetFormatInInnerCol(ArrayList arrList, String[] inner_cols) {
- HashMap elementFormat = new HashMap();
- String totalElement = null;
- String extractedElement = null;
- String format = null;
- int pos = 0;
- //debugLogger.debug("arrList.size() " + arrList.size());
- for (int i = 0; i < arrList.size(); i++) {
- totalElement = (String) arrList.get(i);
- //debugLogger.debug("\nTotalElement " + totalElement);
- extractedElement = totalElement.substring(totalElement.indexOf("(")+1, totalElement.indexOf(")") );
- for (int j = 0; j < inner_cols.length; j++) {
- //debugLogger.debug("Format " + inner_cols[j] + " " + extractedElement);
- if(inner_cols[j].lastIndexOf(extractedElement)!=-1) {
- if(inner_cols[j].indexOf("999")!=-1 && inner_cols[j].indexOf("TO_CHAR")!=-1) {
- pos = inner_cols[j].indexOf("TO_CHAR");
- pos = inner_cols[j].lastIndexOf(",'");
- if(pos == -1)
- pos = inner_cols[j].lastIndexOf(", '");
- //debugLogger.debug("Format before " + inner_cols[j] + "\n*** " + pos+ " " + (inner_cols[j].substring(pos+2, inner_cols[j].indexOf("'", pos+2))));
- format = inner_cols[j].substring(pos+2, inner_cols[j].indexOf("'", pos+2));
- }
- }
- }
- if(format!=null) {
- //debugLogger.debug("Match and Get Format In Inner " + totalElement + " " + format);
- elementFormat.put(totalElement, format);
-
- }
- format = null;
- }
-
- return elementFormat;
- }
-
- private ArrayList replaceOuterCols (HashMap hashMap, String[] outer_cols) {
- Set mapSet = hashMap.entrySet();
- String element = "", value = "";
- ArrayList finalElements = new ArrayList();
- Map.Entry me;
- int flag=0;
- for (int i = 0; i < outer_cols.length; i++) {
- flag = 0;
- for (Iterator iter = mapSet.iterator(); iter.hasNext();) {
- me=(Map.Entry)iter.next();
- element = (String) me.getKey();
- value = (String) me.getValue();
- //debugLogger.debug("Replace Map entry " + element + " " + value);
- //debugLogger.debug("Replace " + outer_cols[i] + " " + element);
- if(outer_cols[i].trim().equals(element.trim())) {
- flag = 1;
- //debugLogger.debug("I am here " + element + " " + value );
- finalElements.add(addFormat(element,value));
- }
- }
- if(flag == 0)
- finalElements.add(outer_cols[i]);
- }
- return finalElements;
- }
-
- private String addFormat (String element, String value) {
- StringBuffer elementBuf = new StringBuffer (element);
- StringBuffer finalElement = new StringBuffer("");
- String extractedElement = elementBuf.substring(elementBuf.indexOf("(")+1,elementBuf.indexOf(")"));
- String alias = elementBuf.substring(elementBuf.lastIndexOf(" ")+1);
- String operation = elementBuf.substring(0,elementBuf.indexOf("("));
- //debugLogger.debug("Add Format " + alias + " "+ extractedElement);
- finalElement.append("TO_CHAR (")
- .append(operation)
- .append("(TO_NUMBER (")
- .append(extractedElement)
- .append(",'" + value +"'")
- .append(")),'"+value + "') ")
- .append(alias);
-/* elementBuf.insert(0, "TO_CHAR (");
- elementBuf.insert(elementBuf.lastIndexOf(")")+1,value+"')");
- debugLogger.debug("FORMAT " + element);
- debugLogger.debug("FORMAT BUF " + elementBuf.toString());
- debugLogger.debug("Format " + finalElement.toString());
-*/
- //debugLogger.debug("Final Element " + finalElement.toString());
- return finalElement.toString();
- }
-
- private String generateSQL( ArrayList outerSql, String sql) {
-
- StringBuffer finalSql = new StringBuffer("SELECT ") ;
-
- for (int i = 0; i < outerSql.size(); i++) {
- finalSql.append(outerSql.get(i));
- if ( i < outerSql.size()-1 )
- finalSql.append(",");
- }
- finalSql.append(" "+sql.substring(sql.indexOf("FROM")));
- logger.debug(EELFLoggerDelegate.debugLogger, (" ---" + finalSql.toString()));
- return finalSql.toString();
- }
-
-
-/* public String fixCrosstabSQL1(StringBuffer sql) {
- int pos = 0;
- int pos_f_format = 0;
- int pos_t_format = 0;
- int pos_alias = 0;
- String format = "";
- String alias = null;
- if(sql.indexOf("SELECT", 7)!= -1) {
- pos = sql.indexOf("SELECT", 7);
- if(sql.indexOf("TO_CHAR", pos)!= -1){
- pos = sql.indexOf("TO_CHAR", pos);
- debugLogger.debug("pos" + pos);
- if(sql.indexOf("999",pos)!= -1) {
- pos = sql.indexOf("999",pos);
- pos_f_format = sql.lastIndexOf(", '", pos);
- debugLogger.debug("pos_f_format" + pos_f_format);
- if(pos_f_format == -1 || (pos - pos_f_format > 10)) {
- pos_f_format = sql.lastIndexOf(",'", pos);
- pos_f_format -= 1;
- }
- pos = pos_f_format;
- if(sql.indexOf("')", pos)!= -1) {
- pos_t_format = sql.indexOf("')", pos);
- debugLogger.debug("pos_t - " + pos_t_format + " " + pos);
- if(pos_t_format == -1 || (pos_t_format - pos > 20)) {
- pos_t_format = sql.indexOf("' )", pos);
- pos_t_format += 3;
- }
- else if (pos_t_format != -1)
- pos_t_format += 2;
- format = sql.substring(pos_f_format+3, pos_t_format);
- //alias = sql.substring(pos_t_format+3, pos_t_format+6);
- pos_alias = sql.indexOf(" ", pos_t_format);
- alias = sql.substring(pos_alias+1, pos_alias+4);
- }
- }
- }
-
- if(sql.indexOf(alias)!=-1) {
- pos = sql.indexOf(alias);
- debugLogger.debug(pos + " " + alias.length()+1 + "\n" + sql);
- sql.delete(pos,pos+4);
- sql.insert(pos, "TO_NUMBER("+alias+", '"+format+"')),'"+ format + "')");
- pos = sql.lastIndexOf("SUM", pos);
- if(pos==-1)
- pos = sql.lastIndexOf("AVG", pos);
- else if (pos==-1)
- pos = sql.lastIndexOf("COUNT", pos);
- else if (pos == -1)
- pos = sql.lastIndexOf("STDDEV", pos);
- else if (pos == -1)
- pos = sql.lastIndexOf("VARIANCE", pos);
- sql.insert(pos, "TO_CHAR (");
- }
-
- }
-
- debugLogger.debug("Alias|" + alias + "| Format " + format);
- debugLogger.debug(sql.toString());
- return sql.toString();
- } // FixSQL
-*/
-
-
-}
-
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.util;
-
-import java.sql.SQLException;
-import java.util.*;
-
-import org.openecomp.portalsdk.analytics.error.ReportSQLException;
-import org.openecomp.portalsdk.analytics.scheduler.SendNotifications;
-import org.openecomp.portalsdk.analytics.system.*;
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class Scheduler extends TimerTask {
- private Timer timer = new Timer(true);
-
- private int timeInterval = 0;
-
- public Scheduler(int timeInterval) {
- super();
-
- this.timeInterval = timeInterval;
- start();
- } // Scheduler
-
- public void start() {
- if (timeInterval > 0)
- timer.schedule(this, 0, timeInterval * 1000);
- }
-
- public void stop() {
- timer.cancel();
- }
-
- public void run() {
-
- SendNotifications sendNotifications = null;
-
- try {
- Log.write("[Scheduler.run " + (new java.util.Date()).toString()
- + "] Sending notifications...", 4);
- //System.out.println("SMTP Server " + AppUtils.getSMTPServer());
- //System.out.println("System Name " + Globals.getSystemName());
- //System.out.println("DefaultEmailSender " + AppUtils.getDefaultEmailSender());
- //System.out.println("DirectAccessURL " + AppUtils.getDirectAccessURL());
- //System.out.println("timeInterval " + timeInterval);
- /*
- DbUtils.executeCall(
- "BEGIN cr_raptor.send_notifications(" +
- "'" + AppUtils.getSMTPServer() + "', " +
- "'" + AppUtils.getDefaultEmailSender() + "', " +
- "'" + Globals.getSystemName() + "', " +
- "'" + AppUtils.getDirectAccessURL() + "', " +
- timeInterval +
- "); END;", false);
- */
- sendNotifications = new SendNotifications();
- sendNotifications.send_notification(AppUtils.getSMTPServer(), AppUtils.getSMTPServer(), Globals.getSystemName() ,
- AppUtils.getDirectAccessURL(), timeInterval);
-
- } catch (Exception e) {
- Log.write("[SYSTEM ERROR Scheduler.run] Exception: " + e.getMessage());
- //e.printStackTrace();
- }
- finally {
-
- try {
- sendNotifications.deInit();
- } catch (SQLException e) {
- Log.write("[SYSTEM ERROR Scheduler.run] Could not close connection: " + e.getMessage());
- }
- }
- } // run
-
-} // Scheduler
+++ /dev/null
-/*-
- * ================================================================================
- * 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.util;
-
-import java.util.*;
-import java.util.regex.Pattern;
-import java.io.File;
-import java.text.*;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
-import org.openecomp.portalsdk.analytics.error.RaptorException;
-import org.openecomp.portalsdk.analytics.model.base.*;
-import org.openecomp.portalsdk.analytics.system.*;
-import org.openecomp.portalsdk.analytics.system.fusion.adapter.Item;
-
-
-public class Utils extends org.openecomp.portalsdk.analytics.RaptorObject {
-
- public Utils() {
- }
-
- public static String getCurrentDateTime() {
- return (new SimpleDateFormat(Globals.getJavaTimeFormat())).format(new Date());
- } // getCurrentDateTime
-
- public static String truncateDecimals(String value, int maxDecimals) {
- return (maxDecimals < 0 || value == null || value.indexOf('.') < 0
- || (value.indexOf('.') == value.length() - 1) || value.substring(
- value.indexOf('.')).length() - 1 <= maxDecimals) ? value : value.substring(0,
- value.indexOf('.') + maxDecimals + 1);
- } // truncateDecimals
-
- public static String truncateTotalDecimals(String value) {
- return truncateDecimals(value, Globals.getMaxDecimalsOnTotals());
- } // truncateTotalDecimals
-
- public static String replaceInString(String replaceInStr, String replaceStr,
- String replaceWithStr) {
- if (replaceStr.equals(replaceWithStr))
- return replaceInStr;
-
- while (replaceInStr!=null && replaceInStr.indexOf(replaceStr) >= 0) {
- int startIdx = replaceInStr.indexOf(replaceStr);
- int endIdx = startIdx + replaceStr.length();
-
- StringBuffer sb = new StringBuffer();
- if (startIdx > 0)
- sb.append(replaceInStr.substring(0, startIdx));
- sb.append(nvls(replaceWithStr));
- if (endIdx < replaceInStr.length())
- sb.append(replaceInStr.substring(endIdx));
- replaceInStr = sb.toString();
- } // while
-
- return replaceInStr;
- } // replaceInString
-
- public static String singleQuoteEncode(String value) {
- value = value!=null?value:"";
- value = Pattern.compile("[\']",Pattern.DOTALL).matcher(value).replaceAll("\\\\\\'");
- return value;
- }
-
- public static String htmlEncode(String value) {
- return replaceInString(replaceInString(value, "<", "<"), ">", ">");
- } // htmlEncode
-
- public static String excelEncode(String value) {
- String replaceStr = replaceInString(replaceInString(value, "<", "<"), ">", ">");
- String reg = "&(?!&#)";
- Pattern p = Pattern.compile(reg);
- String replaceStrAmpersand = p.matcher(replaceStr).replaceAll("&");
- return replaceStrAmpersand;
- } // htmlEncode
-
-
- public static String oracleSafe(String s) {
- if (s == null)
- return null;
-
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i);
- if (ch == '\''/* &&(i>=s.length()-1||s.charAt(i+1)!='\'') */)
- sb.append('\'');
- sb.append(ch);
- } // for
-
- return sb.toString();
- } // oracleSafe
-
-
- public static String javaSafe(String s) {
- if (s == null)
- return null;
-
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i);
- if (ch == '"')
- sb.append('\\');
- sb.append(ch);
- } // for
-
- return sb.toString();
- } // javaSafe
-
- public static Vector getUsersNotInList(List excludeValues, HttpServletRequest request)throws RaptorException {
- HttpSession session = request.getSession();
-// String[] whereConditionAndSess = Globals.getWhereConditionForUserRole().split(",");
-// String whereCondition = "";
-// String conditionalValue = "";
-// for (int i = 0; i < whereConditionAndSess.length; i++) {
-// whereCondition = whereConditionAndSess[0];
-// }
-// for (int i = 1; i < whereConditionAndSess.length; i++) {
-// conditionalValue = whereConditionAndSess[1];
-// }
-// whereCondition = " where "+ whereCondition + "'" + (String)session.getAttribute(conditionalValue) + "'";
-
-// Vector allUsers = AppUtils.getAllUsers(whereCondition);
- String query = Globals.getCustomizedScheduleQueryForUsers();
- session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
- String userId = AppUtils.getUserID(request);
- session.setAttribute("LOGGED_USERID", userId);
- 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 allUsers = AppUtils.getAllUsers(query,param, isAdmin);
- Vector result = new Vector(allUsers.size());
-
- for (Iterator iter = allUsers.iterator(); iter.hasNext();) {
- IdNameValue value = (IdNameValue) iter.next();
-
- boolean exclude = false;
- for (Iterator iterE = excludeValues.iterator(); iterE.hasNext();)
- if (((IdNameValue) iterE.next()).getId().equals(value.getId())) {
- exclude = true;
- break;
- } // if
-
- if (!exclude)
- result.add(value);
- } // for
-
- return result;
- } // getUsersNotInList
-
- public static Vector getRolesNotInList(List excludeValues, HttpServletRequest request) throws RaptorException {
- HttpSession session = request.getSession();
- String query = Globals.getCustomizedScheduleQueryForRoles();
- session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
- String userId = AppUtils.getUserID(request);
- session.setAttribute("LOGGED_USERID", userId);
- 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 result = new Vector(allRoles.size());
-
- for (Iterator iter = allRoles.iterator(); iter.hasNext();) {
- IdNameValue value = (IdNameValue) iter.next();
-
- boolean exclude = false;
- for (Iterator iterE = excludeValues.iterator(); iterE.hasNext();)
- if (((IdNameValue) iterE.next()).getId().equals(value.getId())) {
- exclude = true;
- break;
- } // if
-
- // Exclude the super role
- if (value.getId().equals(AppUtils.getSuperRoleID()))
- exclude = true;
-
- if (!exclude)
- result.add(value);
- } // for
-
- return result;
- } // getRolesNotInList
-
- public static List<Item> getUsersNotInListLatest(List excludeValues, HttpServletRequest request)throws RaptorException {
- HttpSession session = request.getSession();
- String query = Globals.getCustomizedScheduleQueryForUsers();
- session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
- String userId = AppUtils.getUserID(request);
- session.setAttribute("LOGGED_USERID", userId);
- String[] sessionParameters = Globals.getSessionParams().split(",");
- String param = "";
- for (int i = 0; i < sessionParameters.length; i++) {
- param = (String)session.getAttribute(sessionParameters[i]);
- 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 result = new Vector(allUsers.size());
-
- List<Item> resultLatest = new ArrayList<Item>();
-
- for (Iterator iter = allUsers.iterator(); iter.hasNext();) {
- IdNameValue value = (IdNameValue) iter.next();
-
- boolean exclude = false;
- for (Iterator iterE = excludeValues.iterator(); iterE.hasNext();)
- if (((IdNameValue) iterE.next()).getId().equals(value.getId())) {
- exclude = true;
- break;
- } // if
-
- if (!exclude)
- resultLatest.add(new Item(value.getId(), value.getName()));
- } // for
-
- return resultLatest;
- } // getUsersNotInListLatest
-
-
- public static List<Item> getRolesNotInListLatest(List excludeValues, HttpServletRequest request) throws RaptorException {
- HttpSession session = request.getSession();
- String query = Globals.getCustomizedScheduleQueryForRoles();
- session.setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
- String userId = AppUtils.getUserID(request);
- session.setAttribute("LOGGED_USERID", userId);
- String[] sessionParameters = Globals.getSessionParams().split(",");
- String param = "";
- for (int i = 0; i < sessionParameters.length; i++) {
- param = (String)session.getAttribute(sessionParameters[i]);
- 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 result = new Vector(allRoles.size());
-
- List<Item> resultLatest = new ArrayList<Item>();
-
- for (Iterator iter = allRoles.iterator(); iter.hasNext();) {
- IdNameValue value = (IdNameValue) iter.next();
-
- boolean exclude = false;
- for (Iterator iterE = excludeValues.iterator(); iterE.hasNext();)
- if (((IdNameValue) iterE.next()).getId().equals(value.getId())) {
- exclude = true;
- break;
- } // if
-
- // Exclude the super role
- if (value.getId().equals(AppUtils.getSuperRoleID()))
- exclude = true;
-
- if (!exclude)
- resultLatest.add(new Item(value.getId(), value.getName()));
- } // for
-
- return resultLatest;
- } // getRolesNotInList
- /*
- * public static String nvl(String s) { return (s==null)?"":s; } // nvl
- *
- * public static String nvl(String s, String sDefault) { return
- * nvl(s).equals("")?sDefault:s; } // nvl
- */
-
- public static void _assert(boolean condition, String errMsg) {
- if (org.openecomp.portalsdk.analytics.system.Globals.getDebugLevel() > 0)
- if (!condition)
- throw new RuntimeException(errMsg);
- } // _assert
-
- public static boolean isNull(String a) {
- if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null"))
- return true;
- else
- return false;
- }
-
-
- public static boolean isDownloadFileExists(String fileNamePrefix) {
- File f = new File (Globals.getShellScriptDir()+AppConstants.SHELL_DATA_DIR);
- String[] fileNames = f.list();
- //System.out.println("Util.boolean Prefix" + fileNamePrefix);
- if(fileNames!=null) {
- for (int i = 0; i < fileNames.length; i++) {
- //System.out.println("Util.boolean " + fileNames[i]);
- if(fileNames[i].startsWith(fileNamePrefix)) {
- return true;
- }
- }
- }
- return false;
-
- }
-
- public static String getLatestDownloadableFile(String fileNamePrefix) {
- File f = new File (Globals.getShellScriptDir()+AppConstants.SHELL_DATA_DIR);
- String[] fileNames = f.list();
- ArrayList matchingFiles = new ArrayList();
- //System.out.println("Util.download Prefix" + fileNamePrefix);
- for (int i = 0; i < fileNames.length; i++) {
- //System.out.println("Util.download " + fileNames[i]);
- if(fileNames[i].startsWith(fileNamePrefix)) {
- matchingFiles.add(fileNames[i]);
- }
- }
- //System.out.println("SIZE 1 " + matchingFiles.size());
- String tmpFileName = "";
- int numberOfTimesLooped = 0;
- boolean isSorted = false;
- SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
- Date date1 = null, date2 = null;
- Date currDate = new Date();
- Object[] matchingfileNamesArr = matchingFiles.toArray();
- //System.out.println("SIZE " + matchingFiles.size());
- String fileName1 = "", fileName2 ="";
- do {
- isSorted = true;
- for (int j = 1; j < matchingfileNamesArr.length - numberOfTimesLooped++; j++) {
- fileName1 = (String) matchingfileNamesArr[j];
- fileName2 = (String) matchingfileNamesArr[j-1];
- try{
- date1 = sdf.parse(fileName1.substring(fileName1.lastIndexOf("_")+1,fileName1.lastIndexOf(".")));
- date2 = sdf.parse(fileName2.substring(fileName2.lastIndexOf("_")+1,fileName2.lastIndexOf(".")));
- }
- catch(ParseException ex) {
- return null;
- }
-
- if ( (currDate.getTime()-date1.getTime()) < (currDate.getTime()-date2.getTime())) {
- tmpFileName = fileName1;
- matchingfileNamesArr[j] = fileName2;
- matchingfileNamesArr[j-1] = tmpFileName;
- isSorted = false;
- }
-
- }
- } while (!isSorted);
- if(matchingfileNamesArr.length>0)
- return (String)matchingfileNamesArr[0];
- else
- return null;
-
- }
-
-
-} // Utils
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.util;
-
- /**
- *
- * @author Sundar
- * This class is used to filter javascript tags to avoid XSS attacks.
- */
-public class XSSFilter {
-
- // private static String[] filterChars = { "<", ">", "<", ">", "\"", "\\", "0x" };
-// private static String[] replacementChars = { " ", " ", " ", " ", "'", "/", "0 x" };
-
-/* public static synchronized String filterRequest(String param) {
- String value = param;
-
- if (param != null) {
-
- for (int i = 0; i < filterChars.length; i++) {
- value = filterCharacters(filterChars[i], replacementChars[i],
- value);
- }
-
- }
-
- return value;
-
- }
-*/
-
- public static synchronized String filterRequestOnlyScript(String param) {
- String value = "";
- value = nvl(param);
- value = value.replaceAll("<[\\s]*[sS][\\s]*[cC][\\s]*[rR][\\s]*[iI][\\s]*[pP][\\s]*[tT][\\s]*>", "");
- value = value.replaceAll("</[\\s]*[sS][\\s]*[cC][\\s]*[rR][\\s]*[iI][\\s]*[pP][\\s]*[tT][\\s]*>", "");
- value = value.replaceAll("[\\s]*[jJ][\\s]*[aA][\\s]*[vV][\\s]*[aA][\\s]*[sS][\\s]*[cC][\\s]*[rR][\\s]*[iI][\\s]*[pP][\\s]*[tT][\\s]*", "");
- return value;
- }
- public static synchronized String filterRequest (String param) {
- String value = "";
- value = nvl(param);
- value = value.replaceAll("<[\\s]*[sS][\\s]*[cC][\\s]*[rR][\\s]*[iI][\\s]*[pP][\\s]*[tT][\\s]*>", "");
- value = value.replaceAll("</[\\s]*[sS][\\s]*[cC][\\s]*[rR][\\s]*[iI][\\s]*[pP][\\s]*[tT][\\s]*>", "");
- value = value.replaceAll("[\\s]*[jJ][\\s]*[aA][\\s]*[vV][\\s]*[aA][\\s]*[sS][\\s]*[cC][\\s]*[rR][\\s]*[iI][\\s]*[pP][\\s]*[tT][\\s]*", "");
- value = value.replaceAll("[\\s]*<", "");
- value = value.replaceAll("[\\s]*>", "");
-
- return value;
- }
-
-// private static synchronized String filterCharacters(String originalChar, String newChar,
-// String param) {
-// StringBuffer sb = new StringBuffer(param);
-//
-// for (int position = param.toLowerCase().indexOf(originalChar); position >= 0;) {
-// sb.replace(position, position + originalChar.length(), newChar);
-// param = sb.toString();
-// position = param.toLowerCase().indexOf(originalChar);
-// }
-//
-// return sb.toString();
-// }
-
- public static void main (String args[]) {
- String value = XSSFilter.filterRequest("<s\nC\nr\nI\np\nT\n>\na\nl\ne\nr\nt\n('sundar');</SCRIPT>javascript:alert('Sundar');");
- int i = Integer.parseInt("8989");
- System.out.println(value);
- }
-
- private static String nvl(String s) {
- return (s == null) ? "" : s;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.util.jar;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.Writer;
-import java.net.URL;
-import java.util.jar.JarEntry;
-import java.util.jar.JarInputStream;
-
-public class ExtractJar {
-
- public static int bufferSize = 8192;
- public static String JARFILE = "raptor_upgrade.jar";
-
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- if (args.length > 0 && args[0] != null && args[0].length() > 0)
- extractFilesFromJar(args[0]);
- else {
- System.out.println("Current Directory is taken as webapp path");
- String currentDir = new File(".").getAbsolutePath();
- extractFilesFromJar(currentDir);
- }
- }
-
- /**
- *
- * @param jarFile
- * @throws Exception
- */
- public static void readJar(File jarFile) throws Exception {
- JarInputStream in = new JarInputStream(new FileInputStream(jarFile));
- JarEntry je;
- while ((je = in.getNextJarEntry()) != null) {
- if (je.isDirectory() == false) {
- if (je.getName().startsWith("org/openecomp/portalsdk/analytics/config/")) {
- System.out.println(je.getName() + " " + je.getTime());
-
- }
- }
- }
- in.close();
- }
-
- /**
- *
- * @param directory
- * @throws IOException
- */
- public static void extractFilesFromJar(String directory) throws IOException {
- Class clazz = ExtractJar.class;
- URL jarUrl = clazz.getProtectionDomain().getCodeSource().getLocation();
-
- JarInputStream entryStream = new JarInputStream(jarUrl.openStream());
- JarEntry entry;
-
- while (true) {
- entry = entryStream.getNextJarEntry();
- if (entry == null)
- break;
- if (entry.getName().indexOf("jarutil") < 0) {
- System.out.println(entry.getName());
- File file = new File(directory, entry.getName());
- if (entry.isDirectory()) {
- if (!file.exists())
- file.mkdirs();
- } else {
- File dir = new File(file.getParent());
- if (!dir.exists())
- dir.mkdirs();
- if (file.exists())
- file.delete();
- FileOutputStream fout = new FileOutputStream(file);
- copy(entryStream, fout);
- fout.close();
-
- if (entry.getTime() >= 0)
- file.setLastModified(entry.getTime());
- }
-
- }
- entryStream.closeEntry();
- }
- entryStream.close();
- System.out.println("/WEB-INF/classes/org/openecomp/portalsdk/analytics");
- System.out.println("Delete .... ");
-
- File file1 = new File(directory, "/WEB-INF/classes/org/openecomp/portalsdk/analytics");
-
- deleteDir(file1);
- System.out.println("Deleted ....");
-
- System.out.println("raptor_upgrade_setup.jar");
- file1 = new File(directory, "/raptor_upgrade_setup.jar");
-
- deleteDir(file1);
- System.out.println("Deleted ....");
-
- System.out.println("/org");
- System.out.println("Delete .... ");
-
- file1 = new File(directory, "/org");
- System.out.println(" ********************************* ");
- deleteDir(file1);
- System.out.println("Deleted ....");
- System.out.println("org");
- System.out.println("Delete .... ");
-
- System.out.println("************************************************");
- System.out.println("* *");
- System.out.println("* *");
- System.out.println("* RAPTOR SETUP COMPLETE. *");
- System.out.println("* *");
- System.out.println("* Thank you for upgrading. *");
- System.out.println("* *");
- System.out.println("************************************************");
- }
-
- /**
- *
- * @param in
- * @param out
- * @param byteCount
- * @throws IOException
- */
- public static void copy(InputStream in, OutputStream out, long byteCount) throws IOException {
- byte buffer[] = new byte[bufferSize];
- int len = bufferSize;
- if (byteCount >= 0) {
- while (byteCount > 0) {
- if (byteCount < bufferSize)
- len = in.read(buffer, 0, (int) byteCount);
- else
- len = in.read(buffer, 0, bufferSize);
- if (len == -1)
- break;
-
- byteCount -= len;
- out.write(buffer, 0, len);
- }
- } else {
- while (true) {
- len = in.read(buffer, 0, bufferSize);
- if (len < 0)
- break;
- out.write(buffer, 0, len);
- }
- }
- }
-
- /**
- * Copy Reader to Writer for byteCount bytes or until EOF or exception.
- *
- * @param in
- * @param out
- * @param byteCount
- * @throws IOException
- */
- public static void copy(Reader in, Writer out, long byteCount) throws IOException {
- char buffer[] = new char[bufferSize];
- int len = bufferSize;
- if (byteCount >= 0) {
- while (byteCount > 0) {
- if (byteCount < bufferSize)
- len = in.read(buffer, 0, (int) byteCount);
- else
- len = in.read(buffer, 0, bufferSize);
-
- if (len == -1)
- break;
- byteCount -= len;
- out.write(buffer, 0, len);
- }
- } else {
- while (true) {
- len = in.read(buffer, 0, bufferSize);
- if (len == -1)
- break;
- out.write(buffer, 0, len);
- }
- }
- }
-
- /**
- * Copy Stream in to Stream out until EOF or exception.
- *
- * @param in
- * @param out
- * @throws IOException
- */
- public static void copy(InputStream in, OutputStream out) throws IOException {
- copy(in, out, -1);
- }
-
- public static boolean deleteDir(File dir) {
- System.out.println("Name: " + dir.getName() + " " + dir.isDirectory());
- if (dir.isDirectory()) {
- String[] children = dir.list();
- System.out.println(children);
- for (int i = 0; i < children.length; i++) {
- boolean success = deleteDir(new File(dir, children[i]));
- if (!success) {
- return false;
- }
- }
- }
-
- return dir.delete();
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.util.upgrade;
-
-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.*;
-import org.openecomp.portalsdk.analytics.model.*;
-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.*;
-import org.openecomp.portalsdk.analytics.view.*;
-import org.openecomp.portalsdk.analytics.xmlobj.*;
-
-public class SystemUpgrade extends org.openecomp.portalsdk.analytics.RaptorObject {
- private static final String upgradeFromVersion = "1.x";
- private static final String upgradeToVersion = "2.0";
-
-/* This script upgrades the Raptor database to a newer version
- Make sure you execute the "upgrade_v0_to_v1_0_before_java.sql" before running this
- and "upgrade_v0_to_v1_0_after_java.sql" afterwards
-
- URL example: http://localhost:8082/databank/dispatcher?action=raptor&r_action=system_upgrade
-*/
- public static String upgradeDB(HttpServletRequest request) {
- request.setAttribute("system_message", "System upgrade disabled");
- return "raptor/blank.jsp";
-
-/* try {
- if(upgradeFromVersion.equals("1.x")&&upgradeToVersion.equals("2.0"))
- upgrateFromV1ToV2_0(request);
- else
- throw new RuntimeException("Invalid version");
-
- return "raptor/blank.jsp";
- } catch(Exception e) {
- return (new ErrorHandler()).processFatalError(request, e);
- }*/
- } // upgradeDB
-
- private static void upgrateFromV1ToV2_0(HttpServletRequest request) throws Exception {
- StringBuffer log = new StringBuffer();
- log.append("Starting upgrade...<br>\n");
-
- DataSet ds = DbUtils.executeQuery("SELECT cr.rep_id, cr.sched_mailto_user_ids FROM cr_report cr");
- for(int i=0; i<ds.getRowCount(); i++) {
- String repId = ds.getString(i, 0);
- log.append("<li>Processing report ["+repId+"]: ");
-
- Connection connection = DbUtils.startTransaction();
- String emailIds = nvls(ds.getString(i, 1));
- if(emailIds.length()>0)
- try {
- log.append("Converting emails ");
- StringTokenizer st = new StringTokenizer(emailIds, ",");
- while(st.hasMoreTokens()) {
- String userId = nvls(st.nextToken());
- log.append(userId);
- if(userId.length()>0)
- DbUtils.executeUpdate(connection, "INSERT INTO cr_report_schedule_users (rep_id, user_id) VALUES ("+repId+", "+userId+")");
- log.append("-success, ");
- } // while
- log.append(" <font color=green>COMPLETED</font>; ");
- } catch(Exception e) {
- log.append("-<font color=red>FAILED</font>; ");
- }
-
- String reportXML = ReportLoader.loadCustomReportXML(repId);
- ReportDefinition rdef = ReportDefinition.unmarshal(reportXML, repId, request);
- ReportWrapper rw = new ReportWrapper(rdef.cloneCustomReport(), repId, null, null, null, null, null, null, false);
-
- for(Iterator iter=rw.getAllColumns().iterator(); iter.hasNext(); ) {
- DataColumnType col = (DataColumnType) iter.next();
- String drillDownURL = nvls(col.getDrillDownURL());
- if(drillDownURL.startsWith("dispatcher?action=custrep.run&c_master=")) {
- drillDownURL = AppUtils.getReportExecuteActionURL()+drillDownURL.substring("dispatcher?action=custrep.run&c_master=".length());
- log.append("Drill-down processed; ");
- col.setDrillDownURL(drillDownURL);
- }
- } // for
-
- reportXML = rw.marshal();
-
- /*PrintWriter xmlOut = new PrintWriter(new BufferedWriter(new FileWriter(new File(AppUtils.getTempFolderPath()+AppUtils.getUserID(request)))));
- xmlOut.println(reportXML);
- xmlOut.close();*/
-
- try {
- ReportLoader.updateCustomReportRec(connection, rw, reportXML);
- DbUtils.commitTransaction(connection);
- log.append("<font color=green>REPORT UPDATED</font></li>\n");
- } catch(Exception e) {
- log.append("<font color=red>REPORT UPDATE FAILED</font></li>\n");
- DbUtils.rollbackTransaction(connection);
- } finally {
- DbUtils.clearConnection(connection);
- }
- } // for
-
- log.append("<br>\nSystem upgrade successfully completed...<br>\n");
- request.setAttribute("system_message", log.toString());
- } // upgrateFromV1ToV2_0
-
-} // SystemUpgrade
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class ColumnHeader extends org.openecomp.portalsdk.analytics.RaptorObject {
- private String columnTitle = "";
-
- private String columnWidth = "";
-
- private String alignment = "center";
-
- private int rowSpan = 1;
-
- private int actualColSpan = 1;
-
- private int visibleColSpan = 1;
-
- private String linkColId = null;
-
- private int columnSort = 0;
-
- private String colId = "";
-
- private int groupLevel =0;
-
- private int startGroup = 0;
-
- private int colSpanGroup = 0;
-
- private boolean sortable = false;
-
-
- public ColumnHeader() {
- super();
- }
-
- public ColumnHeader(String columnTitle) {
- this();
- setColumnTitle(columnTitle);
- } // ColumnHeader
-
- public ColumnHeader(String columnTitle, Integer columnSort) {
- this();
- setColumnTitle(columnTitle);
- setColumnSort(columnSort.intValue());
- } // ColumnHeader
-
- public ColumnHeader(String columnTitle, String columnWidth) {
- this(columnTitle);
- setColumnWidth(columnWidth);
- } // ColumnHeader
-
- public ColumnHeader(String columnTitle, String columnWidth, int colSpan) {
- this(columnTitle, columnWidth);
- setColSpan(colSpan);
- } // ColumnHeader
-
- //public ColumnHeader(String columnTitle, String columnWidth, int colSpan, String linkColId) {
- //this(columnTitle, columnWidth, colSpan);
- //setLinkColId(linkColId);
- //} // ColumnHeader
-
- public ColumnHeader(String columnTitle, String columnWidth, String alignment, int colSpan, String linkColId) {
- this(columnTitle, columnWidth, colSpan);
- setAlignment(alignment);
- setLinkColId(linkColId);
- } // ColumnHeader
-
- public ColumnHeader(String columnTitle, String columnWidth, int colSpan, int rowSpan) {
- this(columnTitle, columnWidth, colSpan);
- setRowSpan(rowSpan);
- } // ColumnHeader
-
- public String getColumnTitle() {
- return columnTitle;
- }
-
- public String getColumnWidth() {
- return columnWidth;
- }
-
- public int getRowSpan() {
- return rowSpan;
- }
-
- public int getColSpan() {
- return actualColSpan;
- }
-
- public boolean isVisible() {
- return (visibleColSpan > 0) && (rowSpan > 0);
- }
-
- public String getLinkColId() {
- return linkColId;
- }
-
- public void setColumnTitle(String columnTitle) {
- this.columnTitle = nvl(columnTitle);
- }
-
- public void setColumnWidth(String columnWidth) {
- this.columnWidth = columnWidth;
- }
-
- public void setLinkColId(String linkColId) {
- this.linkColId = linkColId;
- }
-
- public void setRowSpan(int rowSpan) {
- this.rowSpan = rowSpan;
- }
-
- public void setColSpan(int colSpan) {
- this.visibleColSpan = colSpan;
- this.actualColSpan = colSpan;
- }
-
- public void setVisible(boolean visible) {
- if (visible) {
- if (visibleColSpan < actualColSpan)
- visibleColSpan++;
- } else {
- if (visibleColSpan > 0)
- visibleColSpan--;
- }
- } // setVisible
-
- public String getColumnWidthHtml() {
- return (columnWidth.length() == 0) ? "" : (" width=" + columnWidth);
- }
-
- public String getRowSpanHtml() {
- return (rowSpan == 1) ? "" : (" rowspan=" + rowSpan);
- }
-
- public String getColSpanHtml() {
- return (visibleColSpan == 1) ? "" : (" colspan=" + visibleColSpan);
- }
-
- public String getColumnTitleHtml() {
- if (linkColId == null)
- return (columnTitle.length() == 0) ? " " : columnTitle;
- else
- return "<a href=\"javascript:performSortBy('" + linkColId
- + "')\" title=\"Sort by column " + columnTitle + "\" class=rcolheader>"
- + ((columnTitle.length() == 0) ? "[NULL]" : columnTitle) + "</a>";
- } // getColumnTitleHtml
-
- /**
- * @return the columnSort
- */
- public int getColumnSort() {
- return columnSort;
- }
-
- /**
- * @param columnSort the columnSort to set
- */
- public void setColumnSort(int columnSort) {
- this.columnSort = columnSort;
- }
-
- /**
- * @return the colId
- */
- public String getColId() {
- return colId;
- }
-
- /**
- * @param colId the colId to set
- */
- public void setColId(String colId) {
- this.colId = colId;
- }
-
- public String getAlignment() {
- return alignment;
- }
-
- public void setAlignment(String alignment) {
- if(nvl(alignment).length()>0)
- this.alignment = alignment;
- }
-
- public int getGroupLevel() {
- return groupLevel;
- }
-
- public void setGroupLevel(int groupLevel) {
- this.groupLevel = groupLevel;
- }
-
- public int getStartGroup() {
- return startGroup;
- }
-
- public void setStartGroup(int startGroup) {
- this.startGroup = startGroup;
- }
-
- public int getColSpanGroup() {
- return colSpanGroup;
- }
-
- public void setColSpanGroup(int colSpanGroup) {
- this.colSpanGroup = colSpanGroup;
- }
-
- public boolean isSortable() {
- return sortable;
- }
-
- public void setSortable(boolean sortable) {
- this.sortable = sortable;
- }
-
-
-
-} // ColumnHeader
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import java.util.*;
-
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class ColumnHeaderRow extends Vector {
- private String rowHeight = "";
-
- private String displayWidth = "";
-
- private String alignment = "center";
-
- 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 ColumnHeader getNext() {
- return hasNext() ? getColumnHeader(nextElemIdx++) : null;
- } // getNext
-
- public ColumnHeader getColumnHeader(int idx) {
- return (ColumnHeader) get(idx);
- } // getColumnHeader
-
- public void addColumnHeader(ColumnHeader columnHeader) {
- add(columnHeader);
- } // addColumnHeader
-
- public void addColumnHeader(int idx, ColumnHeader columnHeader) {
- add(idx, columnHeader);
- } // addColumnHeader
-
- public String getRowHeightHtml() {
- return (rowHeight.length() == 0) ? "" : (" height=" + rowHeight);
- }
-
- public String getRowHeight() {
- return rowHeight;
- }
-
- public void setRowHeight(String rowHeight) {
- this.rowHeight = nvl(rowHeight);
- }
-
- public void setDisplayWidth(String displayWidth) {
- this.displayWidth = nvl(displayWidth);
- }
-
- public String getDisplayWidth() {
- return this.displayWidth;
- }
- /** ************************************************************************************************* */
-
- private String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- private String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
- public String getAlignment() {
- return alignment;
- }
-
- public void setAlignment(String alignment) {
- if(nvl(alignment).length()>0)
- this.alignment = alignment;
- }
-
-} // ColumnHeaderRow
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import org.openecomp.portalsdk.analytics.RaptorObject;
-
-public class ColumnVisual extends RaptorObject {
- private String colId = null;
-
- private String colDisplay = null;
-
- private boolean visible = true;
-
- private String sortType = null;
-
- public ColumnVisual(String colId, String colDisplay, boolean visible, String sortType) {
- super();
-
- setColId(colId);
- setColDisplay(colDisplay);
- setVisible(visible);
- setSortType(sortType);
- } // ColumnVisual
-
- public String getColId() {
- return colId;
- }
-
- public String getColDisplay() {
- return colDisplay;
- }
-
- public boolean isVisible() {
- return visible;
- }
-
- public String getSortType() {
- return sortType;
- }
-
- public void setColId(String colId) {
- this.colId = colId;
- }
-
- public void setColDisplay(String colDisplay) {
- this.colDisplay = colDisplay;
- }
-
- public void setVisible(boolean visible) {
- this.visible = visible;
- }
-
- public void setSortType(String sortType) {
- this.sortType = sortType;
- }
-
-} // ColumnVisual
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import java.util.*;
-
-import org.openecomp.portalsdk.analytics.error.*;
-import org.openecomp.portalsdk.analytics.system.*;
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class CrossTabColumnValues extends org.openecomp.portalsdk.analytics.RaptorObject {
- private String colId = null;
-
- private Vector columnValues = null;
-
- public CrossTabColumnValues(String colId, String loadValuesSQL, String dbInfo)
- throws RaptorException {
- this.colId = colId;
- DataSet ds = ConnectionUtils.getDataSet(loadValuesSQL, dbInfo);
- // DataSet ds = DbUtils.executeQuery(loadValuesSQL);
- columnValues = new Vector(ds.getRowCount());
- for (int i = 0; i < ds.getRowCount(); i++)
- columnValues.add(ds.getString(i, 0));
- } // CrossTabColumnValues
-
- public String getColId() {
- return colId;
- }
-
- public Vector getColumnValues() {
- return columnValues;
- }
-
- public int getValuesCount() {
- return columnValues.size();
- }
-
- public String getValueAt(int idx) {
- return (String) columnValues.get(idx);
- }
-
- public int getIndexOf(String value) {
- for (int i = 0; i < getValuesCount(); i++)
- if (value.equals(getValueAt(i)))
- return i;
-
- return -1;
- } // getIndexOf
-
- public int getIndexOf(int value) {
- for (int i = 0; i < getValuesCount(); i++)
- if (value == new Integer(getValueAt(i)).intValue())
- return i;
-
- return -1;
- } // getIndexOf
-
-} // CrossTabColumnValues
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import java.util.*;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.analytics.RaptorObject;
-import org.openecomp.portalsdk.analytics.error.*;
-import org.openecomp.portalsdk.analytics.model.runtime.*;
-import org.openecomp.portalsdk.analytics.system.*;
-import org.openecomp.portalsdk.analytics.util.*;
-import org.openecomp.portalsdk.analytics.xmlobj.*;
-
-public class CrossTabOrderManager extends RaptorObject {
- private Vector colHeaderValues = null;
-
- private Vector rowHeaderValues = null;
-
-
- public CrossTabOrderManager(ReportRuntime rr, String userId,HttpServletRequest request) throws RaptorException {
- colHeaderValues = new Vector();
- rowHeaderValues = new Vector();
-
- for (Iterator iter = rr.getAllColumns().iterator(); iter.hasNext();) {
- DataColumnType dct = (DataColumnType) iter.next();
- if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_COLUMN)) {
- if(rr.getColumnById(dct.getColId()+"_sort")!=null) {
- dct = rr.getColumnById(dct.getColId()+"_sort");
- colHeaderValues.add(new CrossTabColumnValues(dct.getColId(), rr
- .generateDistinctValuesSQL(dct, userId,request), rr.getDbInfo()));
- } else
- colHeaderValues.add(new CrossTabColumnValues(dct.getColId(), rr
- .generateDistinctValuesSQL(dct, userId,request), rr.getDbInfo()));
- }
- else if (nvl(dct.getCrossTabValue()).equals(AppConstants.CV_ROW))
- rowHeaderValues.add(new CrossTabColumnValues(dct.getColId(), rr
- .generateDistinctValuesSQL(dct, userId,request), rr.getDbInfo()));
- else if (nvl(dct.getCrossTabValue()).trim().length()<=0)
- rowHeaderValues.add(new CrossTabColumnValues(dct.getColId(), rr
- .generateDistinctValuesSQL(dct, userId,request), rr.getDbInfo()));
- } // for
- } // CrossTabOrderManager
-
- public int getIndexOfColHeaderValue(int colIdx, String value) {
- return ((CrossTabColumnValues) colHeaderValues.get(colIdx)).getIndexOf(value);
- } // getIndexOfColHeaderValue
-
- public int getIndexOfColHeaderValue(int colIdx, int value) {
- return ((CrossTabColumnValues) colHeaderValues.get(colIdx)).getIndexOf(value);
- } // getIndexOfColHeaderValue
-
- public boolean isAfterColHeaderValue(int colIdx, String curValue, String newValue) {
- return (getIndexOfColHeaderValue(colIdx, curValue) > getIndexOfColHeaderValue(colIdx,
- newValue));
- } // isBeforeColHeaderValue
-
- public boolean isAfterColHeaderValue(int colIdx, int curValue, Integer newValue) {
- return (getIndexOfColHeaderValue(colIdx, curValue) > getIndexOfColHeaderValue(colIdx,
- newValue.intValue()));
- } // isBeforeColHeaderValue
-
- public int getIndexOfRowHeaderValue(int rowIdx, String value) {
- return ((CrossTabColumnValues) rowHeaderValues.get(rowIdx)).getIndexOf(value);
- } // getIndexOfRowHeaderValue
-
- public boolean isAfterRowHeaderValue(int rowIdx, String curValue, String newValue) {
- return (getIndexOfRowHeaderValue(rowIdx, curValue) > getIndexOfRowHeaderValue(rowIdx,
- newValue));
- } // isBeforeRowHeaderValue
-
- public Vector getRowHeaderValues() {
- return rowHeaderValues;
- }
-
- public void setRowHeaderValues(Vector rowHeaderValues) {
- this.rowHeaderValues = rowHeaderValues;
- }
-
-} // CrossTabOrderManager
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import java.util.*;
-
-public class CrossTabTotalValue extends org.openecomp.portalsdk.analytics.RaptorObject {
- private Vector headerValues = null;
-
- private String totalValue = null;
-
- public CrossTabTotalValue() {
- super();
- }
-
- public CrossTabTotalValue(Vector headerValues, String totalValue) {
- this();
-
- setHeaderValues(headerValues);
- setTotalValue(totalValue);
- } // CrossTabTotalValue
-
- public Vector getHeaderValues() {
- return headerValues;
- }
-
- public String getTotalValue() {
- return totalValue;
- }
-
- public void setHeaderValues(Vector headerValues) {
- this.headerValues = headerValues;
- }
-
- public void setTotalValue(String totalValue) {
- this.totalValue = totalValue;
- }
-
-} // CrossTabTotalValue
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import java.util.*;
-
-public class DataRow/* extends Vector*/ {
-
- private ArrayList dataValueList = new ArrayList();
- private HtmlFormatter rowFormatter = null;
-
- private int nextElemIdx = 0;
-
- private boolean rowFormat = false;
-
- private String formatId = null;
-
- private int rowNum = -1;
-
- private Vector<DataValue> rowValues;
-
- /**
- * @return the rowNum
- */
- public int getRowNum() {
- return rowNum;
- }
-
-
- /**
- * @param rowNum the rowNum to set
- * Used for crosstab
- */
- public void setRowNum(int rowNum) {
- this.rowNum = rowNum;
- }
-
-
- public String getFormatId() {
- return formatId;
- }
-
-
- public void setFormatId(String formatId) {
- this.formatId = formatId;
- }
-
-
- public void resetNext() {
- resetNext(0);
- } // resetNext
-
- public void resetNext(int toPos) {
- nextElemIdx = toPos;
- } // resetNext
-
- public boolean hasNext() {
- return (nextElemIdx < dataValueList.size());
- } // hasNext
-
- public DataValue getNext() {
- return hasNext() ? getDataValue(nextElemIdx++) : null;
- } // getNext
-
- public DataValue getDataValue(int idx) {
- return (DataValue) dataValueList.get(idx);
- } // getRowHeader
-
- public void addDataValue(DataValue dataValue) {
- if (rowFormatter != null)
- dataValue.setRowFormatter(rowFormatter);
- dataValueList.add(dataValue);
- } // addDataValue
-
- public void addDataValue(int idx, DataValue dataValue) {
- if (rowFormatter != null)
- dataValue.setRowFormatter(rowFormatter);
- dataValueList.add(idx, dataValue);
- } // addDataValue
-
- public void setDataValue(int idx, DataValue dataValue) {
- if (rowFormatter != null)
- dataValue.setRowFormatter(rowFormatter);
- dataValueList.set(idx, dataValue);
- } // addDataValue
-
- public HtmlFormatter getRowFormatter() {
- return rowFormatter;
- }
-
- public void setRowFormat(boolean b) {
- rowFormat = b;
- }
- public boolean isRowFormat() {
- return rowFormat;
- }
-
- public void setRowFormatter(HtmlFormatter rowFormatter) {
- this.rowFormatter = rowFormatter;
-
- for (int i = 0; i < dataValueList.size(); i++)
- ((DataValue) dataValueList.get(i)).setRowFormatter(rowFormatter);
- } // setRowFormatter
-
- public String getBgColorHtml() {
- if (rowFormatter != null && rowFormatter.getBgColor().length() > 0)
- return " bgcolor=" + rowFormatter.getBgColor();
- else
- return "";
- } // getBgColorHtml
-
- public String getDataValue(String colId) {
- String v_ColId = "";
- for (int i = 0; i < dataValueList.size(); i++) {
- v_ColId = ((DataValue) dataValueList.get(i)).getColId();
- if(v_ColId.equals(colId)) {
- return ((DataValue) dataValueList.get(i)).getDisplayValue();
- }
- }
- return null;
-
- }
-
-
- /**
- * @return the dataValueList
- */
- public ArrayList getDataValueList() {
- return dataValueList;
- }
-
-
- /**
- * @param dataValueList the dataValueList to set
- */
- public void setDataValueList(ArrayList dataValueList) {
- this.dataValueList = dataValueList;
- }
-
-
- public Vector<DataValue> getRowValues() {
- return rowValues;
- }
-
-
- public void setRowValues(Vector<DataValue> rowValues) {
- this.rowValues = rowValues;
- }
-
-} // DataRow
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class DataValue extends org.openecomp.portalsdk.analytics.RaptorObject {
- private String displayValue = "";
-
- private String displayCalculatedValue = "";
-
- private String drillDownURL = null;
-
- private boolean drillDowninPoPUp = false;
-
- private String indentation = "";
-
- private String alignment = "Left";
-
- private boolean visible = true;
-
- private boolean hidden = false;
-
- private boolean bold = false;
-
- private HtmlFormatter cellFormatter = null;
-
- private HtmlFormatter rowFormatter = null;
-
- private String formatId = null;
-
- private boolean cellFormat = false;
-
- private String colId = null;
-
- private String displayTotal = null;
-
- private String colName = null;
-
- private String displayName = null;
-
- private String nowrap = "False";
-
- private String hyperlinkURL = "";
-
- private String displayType = "";
-
- private String actionImg = "";
-
-
- public String getColName() {
-
- return colName;
- }
-
-
- public void setColName(String colName) {
-
- this.colName = colName;
- }
-
- public DataValue() {
- super();
- }
-
- public String getFormatId() {
- return formatId;
- }
-
-
- public void setFormatId(String formatId) {
- this.formatId = formatId;
- }
-
- public void setCellFormat(boolean b) {
- cellFormat = b;
- }
- public boolean isCellFormat() {
- return cellFormat;
- }
-
- public String getDisplayValue() {
- return displayValue;
- }
-
- public String getDrillDownURL() {
- return drillDownURL;
- }
-
- public String getAlignment() {
- return alignment;
- }
-
- public boolean isVisible() {
- return visible;
- }
-
- public boolean isBold() {
- return bold;
- }
-
- public HtmlFormatter getCellFormatter() {
- return cellFormatter;
- }
-
- public HtmlFormatter getRowFormatter() {
- return rowFormatter;
- }
-
- public void setDisplayValue(String displayValue) {
- this.displayValue = nvl(displayValue);
- }
-
- public void setDrillDownURL(String drillDownURL) {
- this.drillDownURL = drillDownURL;
- }
-
- public void setAlignment(String alignment) {
- this.alignment = alignment;
- }
-
- public void setVisible(boolean visible) {
- this.visible = visible;
- }
-
- public void setBold(boolean bold) {
- this.bold = bold;
- }
-
- public void setCellFormatter(HtmlFormatter cellFormatter) {
- this.cellFormatter = cellFormatter;
- }
-
- public void setRowFormatter(HtmlFormatter rowFormatter) {
- this.rowFormatter = rowFormatter;
- }
-
- private String getFormattedValue(String value) {
- value = nvl(value.trim()).length()<=0 ? " ":value;
- if (cellFormatter != null)
- return cellFormatter.formatValue(value);
- else if (rowFormatter != null)
- return rowFormatter.formatValue(value);
- else
- return value;
- } // getFormattedValue
-
- private String getFormattedLink(String value) {
- if (cellFormatter != null)
- return cellFormatter.formatLink(value, drillDownURL, isDrillDowninPoPUp());
- else if (rowFormatter != null)
- return rowFormatter.formatLink(value, drillDownURL, isDrillDowninPoPUp());
- else {
- if(!isDrillDowninPoPUp()) {
- return "<a href=\"" + drillDownURL + "\">" + value + "</a>";
- } else {
- return "<a href=\"#\" onClick=\"showDrillDownInPopup('" + drillDownURL + "&noFormFields=Y&isEmbedded=Y&show_back_btn=N"+ "')\">" + value + "</a>";
- }
-
- }
- } // getFormattedValue
-
- private String getValueHtml() {
- return (nvl(displayValue).trim().length() == 0) ? " " : displayValue;
- }
-
- public String getDisplayValueHtml() {
- return getFormattedValue(getValueHtml());
- }
-
- public String getDisplayValueLinkHtml() {
- if (nvl(drillDownURL).length() == 0)
- return getDisplayValueHtml();
- else
- return getFormattedLink(getValueHtml());
- // return getFormattedValue("<a
- // href=\""+drillDownURL+"\">"+getValueHtml()+"</a>");
- } // getDisplayValueLinkHtml
-
- public String getAlignmentHtml() {
- if (cellFormatter != null && cellFormatter.getAlignment().length() > 0)
- return " align=" + cellFormatter.getAlignment();
- else if (rowFormatter != null && rowFormatter.getAlignment().length() > 0)
- return " align=" + rowFormatter.getAlignment();
- else
- return (alignment.length() == 0) ? "" : (" align=" + alignment);
- } // getAlignmentHtml
-
- public String getBgColorHtml() {
- if (cellFormatter != null && cellFormatter.getBgColor().length() > 0)
- return " bgcolor=" + cellFormatter.getBgColor();
- else if (rowFormatter != null && rowFormatter.getBgColor().length() > 0)
- return " bgcolor=" + rowFormatter.getBgColor();
- else
- return "";
- } // getBgColorHtml
-
-
- public String getColId() {
-
- return colId;
- }
-
-
- public void setColId(String colId) {
-
- this.colId = colId;
- }
-
-
- public String getDisplayTotal() {
-
- return displayTotal;
- }
-
-
- public void setDisplayTotal(String displayTotal) {
-
- this.displayTotal = displayTotal;
- }
-
-
-
- public String getDisplayName() {
-
- return displayName;
- }
-
-
-
- public void setDisplayName(String displayName) {
-
- this.displayName = displayName;
- }
-
-
- public boolean isHidden() {
- return hidden;
- }
-
-
- public void setHidden(boolean hidden) {
- this.hidden = hidden;
- }
-
- public String getNowrap() {
- return nowrap;
- }
-
-
- public void setNowrap(String nowrap) {
- this.nowrap = nowrap;
- }
-
- public boolean isDrillDowninPoPUp() {
- return drillDowninPoPUp;
- }
-
-
- public void setDrillDowninPoPUp(boolean drillDowninPoPUp) {
- this.drillDowninPoPUp = drillDowninPoPUp;
- }
-
-
- /**
- * @return the displayCalculatedValue
- */
- public String getDisplayCalculatedValue() {
- return displayCalculatedValue;
- }
-
-
- /**
- * @param displayCalculatedValue the displayCalculatedValue to set
- */
- public void setDisplayCalculatedValue(String displayCalculatedValue) {
- this.displayCalculatedValue = displayCalculatedValue;
- }
-
-
- /**
- * @return the indentation
- */
- public String getIndentation() {
- return indentation;
- }
-
-
- /**
- * @param indentation the indentation to set
- */
- public void setIndentation(String indentation) {
- this.indentation = indentation;
- }
-
-
- /**
- * @return the hyperlinkURL
- */
- public String getHyperlinkURL() {
- return hyperlinkURL;
- }
-
-
- /**
- * @param hyperlinkURL the hyperlinkURL to set
- */
- public void setHyperlinkURL(String hyperlinkURL) {
- this.hyperlinkURL = hyperlinkURL;
- }
-
-
- /**
- * @return the displayType
- */
- public String getDisplayType() {
- return displayType;
- }
-
-
- /**
- * @param displayType the displayType to set
- */
- public void setDisplayType(String displayType) {
- this.displayType = displayType;
- }
-
-
- /**
- * @return the actionImg
- */
- public String getActionImg() {
- return actionImg;
- }
-
-
- /**
- * @param actionImg the actionImg to set
- */
- public void setActionImg(String actionImg) {
- this.actionImg = actionImg;
- }
-
-} // DataValue
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import org.openecomp.portalsdk.analytics.RaptorObject;
-
-public class HtmlFormatter extends RaptorObject {
- private boolean bold = false;
-
- private boolean italic = false;
-
- private boolean underline = false;
-
- private String bgColor = "";
-
- private String fontColor = "";
-
- private String fontFace = "";
-
- private String fontSize = "";
-
- private String alignment = "";
-
- private String formatId = "";
-
- public HtmlFormatter() {
- super();
- }
-
- public HtmlFormatter(boolean bold, boolean italic, boolean underline, String bgColor,
- String fontColor, String fontFace, String fontSize) {
- this();
-
- setBold(bold);
- setItalic(italic);
- setUnderline(underline);
- setBgColor(bgColor);
- setFontColor(fontColor);
- setFontFace(fontFace);
- setFontSize(fontSize);
- } // HtmlFormatter
-
- public HtmlFormatter(boolean bold, boolean italic, boolean underline, String bgColor,
- String fontColor, String fontFace, String fontSize, String alignment) {
- this(bold, italic, underline, bgColor, fontColor, fontFace, fontSize);
- setAlignment(alignment);
- } // HtmlFormatter
-
- public boolean isBold() {
- return bold;
- }
-
- public boolean isItalic() {
- return italic;
- }
-
- public boolean isUnderline() {
- return underline;
- }
-
- public String getBgColor() {
- return bgColor;
- }
-
- public String getFontColor() {
- return fontColor;
- }
-
- public String getFontFace() {
- return fontFace;
- }
-
- public String getFontSize() {
- return fontSize;
- }
-
- public String getAlignment() {
- return alignment;
- }
-
- public void setBold(boolean bold) {
- this.bold = bold;
- }
-
- public void setItalic(boolean italic) {
- this.italic = italic;
- }
-
- public void setUnderline(boolean underline) {
- this.underline = underline;
- }
-
- public void setBgColor(String bgColor) {
- this.bgColor = nvl(bgColor);
- }
-
- public void setFontColor(String fontColor) {
- this.fontColor = nvl(fontColor);
- }
-
- public void setFontFace(String fontFace) {
- this.fontFace = nvl(fontFace);
- }
-
- public void setFontSize(String fontSize) {
- this.fontSize = nvl(fontSize);
- }
-
- public void setAlignment(String alignment) {
- this.alignment = nvl(alignment);
- }
-
- private String generateStyleHtml() {
- StringBuffer sb = new StringBuffer();
-
- if (isBold())
- sb.append("font-weight:bold;");
- if (isItalic())
- sb.append("font-style:italic;");
- if (isUnderline())
- sb.append("text-decoration:underline;");
- // if(getBgColor().length()>0)
- // sb.append("background-color:"+getBgColor()+";");
- if (getFontColor().length() > 0)
- sb.append("color:" + getFontColor() + ";");
- if (getFontFace().length() > 0)
- sb.append("font-family:" + getFontFace() + ";");
- if (getFontSize().length() > 0)
- sb.append("font-size:" + getFontSize() + "px;");
- if (getAlignment().length() > 0)
- sb.append("text-align:" + getAlignment() + ";");
-
- if (sb.length() > 0) {
- sb.insert(0, " style=\"");
- sb.append("\"");
- } // if
-
- return sb.toString();
- } // generateStyleHtml
-
- public String generateStyleForZK() {
- StringBuffer sb = new StringBuffer();
-
- if (isBold())
- sb.append("font-weight:bold;");
- if (isItalic())
- sb.append("font-style:italic;");
- if (isUnderline())
- sb.append("text-decoration:underline;");
- // if(getBgColor().length()>0)
- // sb.append("background-color:"+getBgColor()+";");
- if (getFontColor().length() > 0)
- sb.append("color:" + getFontColor() + ";");
- if (getFontFace().length() > 0)
- sb.append("font-family:" + getFontFace() + ";");
- if (getFontSize().length() > 0)
- sb.append("font-size:" + getFontSize() + "px;");
- if (getAlignment().length() > 0)
- sb.append("text-align:" + getAlignment() + ";");
-
- return sb.toString();
- } // generateStyleHtml
-
- public String formatValue(String value) {
- String style = generateStyleHtml();
- if (style.length() > 0)
- return "<font" + style + ">" + value + "</font>";
- else
- return value;
- } // formatValue
-
- public String formatLink(String value, String url, boolean drillDowninPoPUp) {
- if(!drillDowninPoPUp) {
- return "<a href=\"" + url + "\"" + generateStyleHtml() + ">" + value + "</a>";
- } else {
- return "<a href=\"#\" onClick=\"showDrillDownInPopup('" + url + "&noFormFields=Y&isEmbedded=Y&show_back_btn=N"+ "')\"" + generateStyleHtml() + ">" + value + "</a>";
- }
- } // formatLink
-
- public String getFormatId() {
- return formatId;
- }
-
- public void setFormatId(String formatId) {
- this.formatId = formatId;
- }
-
-} // HtmlFormatter
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import java.util.*;
-
-public class ReportColumnHeaderRows extends Vector {
- 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 ColumnHeaderRow getNext() {
- return hasNext() ? getColumnHeaderRow(nextElemIdx++) : null;
- } // getNext
-
- public ColumnHeader getColumnHeader(int rowIdx, int colIdx) {
- return getColumnHeaderRow(rowIdx).getColumnHeader(colIdx);
- } // getColumnHeader
-
- public ColumnHeaderRow getColumnHeaderRow(int idx) {
- return (ColumnHeaderRow) get(idx);
- } // getColumnHeaderRow
-
- public void addColumnHeaderRow(ColumnHeaderRow columnHeaderRow) {
- add(columnHeaderRow);
- } // addColumnHeaderRow
-
- public void addColumnHeaderRow(int idx, ColumnHeaderRow columnHeaderRow) {
- add(idx, columnHeaderRow);
- } // addColumnHeaderRow
-
- public int getRowCount() {
- return size();
- } // getRowCount
-
- public int getColumnCount() {
- int cSize = 0;
- if (getRowCount() > 0)
- cSize = getColumnHeaderRow(getRowCount() - 1).size();
-
- return cSize;
- } // getColumnCount
-
-} // ReportColumnHeaderRows
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import java.io.Serializable;
-import java.util.*;
-
-import org.openecomp.portalsdk.analytics.model.runtime.*;
-import org.openecomp.portalsdk.analytics.system.*;
-import org.openecomp.portalsdk.analytics.util.*;
-import org.openecomp.portalsdk.analytics.xmlobj.*;
-
-public class ReportData extends org.openecomp.portalsdk.analytics.RaptorObject implements Serializable {
- // private static final boolean sortData = true; // sort cross-tab data by
- // row/col name while being added
- private static final int MAX_NUM_COLS = 150; // -1 => no restriction
-
- private int pageNo = -1;
-
- private int pageSetNo = -1;
-
- public ReportColumnHeaderRows reportColumnHeaderRows = null;
-
- public ReportRowHeaderCols reportRowHeaderCols = null;
-
- public ReportDataRows reportDataRows = null;
-
- public ReportDataRows reportDataTotalRow = null;
-
- public ReportRowHeaderCols reportTotalRowHeaderCols = null;
-
- public List reportDataList = null;
-
- private boolean canSortAtRuntime = false;
-
- private Vector columnVisuals = null; // Contains actual column Ids for
- // linear or last header col values
- // for cross-tab
-
- public ReportData(int pageNo, boolean canSortAtRuntime) {
- super();
-
- this.pageNo = pageNo;
- this.canSortAtRuntime = canSortAtRuntime;
-
- reportColumnHeaderRows = new ReportColumnHeaderRows();
- reportRowHeaderCols = new ReportRowHeaderCols();
- reportDataRows = new ReportDataRows();
-
- columnVisuals = new Vector();
- } // ReportData
-
- public int getPageNo() {
- return pageNo;
- } // pageNo
-
- public int getPageSetNo() {
- return pageSetNo;
- } // pageSetNo
-
- public int getHeaderRowCount() {
- return reportColumnHeaderRows.getRowCount();
- } // getHeaderRowCount
-
- public int getDataRowCount() {
- if(reportDataRows!=null && reportDataRows.getRowCount()>0)
- return reportDataRows.getRowCount();
- else if(getReportDataList()!=null)
- return getReportDataList().size();
- else
- return 0;
- } // getDataRowCount
-
- public int getTotalRowCount() {
- return getHeaderRowCount() + getDataRowCount();
- } // getTotalRowCount
-
- public int getHeaderColumnCount() {
- return reportRowHeaderCols.getColumnCount();
- } // getHeaderColumnCount
-
- public int getDataColumnCount() {
- int cCount = reportDataRows.getColumnCount();
- if (cCount == 0)
- cCount = reportColumnHeaderRows.getColumnCount();
-
- return cCount;
- } // getDataColumnCount
-
- public int getTotalColumnCount() {
- return getHeaderColumnCount() + getDataColumnCount();
- } // getTotalColumnCount
-
- // Cross-tab data section
- private void insertColumn(int colIdx, Vector colNameValues, Vector colNameSortValues, List dataList, String alignment) {
- int r = 0;
- for (reportColumnHeaderRows.resetNext(); reportColumnHeaderRows.hasNext();) {
- ColumnHeaderRow chr = reportColumnHeaderRows.getNext();
- if(colNameSortValues!=null) {
- ColumnHeader ch = new ColumnHeader(((DataValue) colNameValues.get(r)).getDisplayValue(), Integer.valueOf(((DataValue)colNameSortValues.get(r)).getDisplayValue()) );
- ch.setColumnWidth(chr.getDisplayWidth());
- ch.setAlignment(alignment);
- chr.addColumnHeader(colIdx, ch);
- }
- else {
- ColumnHeader ch = new ColumnHeader(((DataValue) colNameValues.get(r)).getDisplayValue());
- ch.setColumnWidth(chr.getDisplayWidth());
- ch.setAlignment(alignment);
- chr.addColumnHeader(colIdx, ch);
- }
- r++;
- } // for
-
-/* for (reportDataRows.resetNext(); reportDataRows.hasNext();) {
- DataRow dr = reportDataRows.getNext();
- dr.addDataValue(colIdx, new DataValue());
- } // for
- */
- for(int j = 0; j < dataList.size(); j++) {
- DataRow dr = (DataRow) dataList.get(j);
- dr.addDataValue(colIdx, new DataValue());
- }
- } // insertColumn
-
- private boolean prevColNamesChanged(int colIdx, Vector prevColNames) {
- for (int k = 0; k < prevColNames.size(); k++)
- if (!nvl((String) prevColNames.get(k)).equals(
- reportColumnHeaderRows.getColumnHeader(k, colIdx).getColumnTitle()))
- return true;
-
- return false;
- } // prevColNamesChanged
-
- private int findColumnIdx(Vector colNameValues, Vector colNameSortValues, CrossTabOrderManager crossTabOrderManager,
- boolean createIfMissing, List dataList) {
- int colIdx = 0;
- try {
-
- boolean nameFound = false;
- // String prevColName = null;
- Vector prevColNames = new Vector();
- int columnSort = -1;
- for (int r = 0; r < colNameValues.size(); r++) {
- //String colName = (String) colNameValues.get(r);
- String colName = ((DataValue) colNameValues.get(r)).getDisplayValue();
- Integer colSortName = null;
- if(colNameSortValues!=null)
- colSortName = Integer.valueOf(((DataValue)colNameSortValues.get(r)).getDisplayValue());
- ColumnHeaderRow chr = reportColumnHeaderRows.getColumnHeaderRow(r);
-
- chr.resetNext(colIdx);
- nameFound = false;
- boolean posFound = false;
- while ((!nameFound) && (!posFound) && chr.hasNext()) {
- ColumnHeader ch = chr.getNext();
- columnSort = ch.getColumnSort();
- if (colName.equals(ch.getColumnTitle())) {
- if (prevColNamesChanged(colIdx, prevColNames))
- posFound = true;
- else
- nameFound = true;
- } else if (crossTabOrderManager != null) {
- if( colNameSortValues!=null && crossTabOrderManager.isAfterColHeaderValue(r, columnSort,
- colSortName))
- posFound = true;
- else if (colNameSortValues == null && crossTabOrderManager.isAfterColHeaderValue(r, ch.getColumnTitle(),
- colName)) {
- posFound = true;
- }
- }
- else if (crossTabOrderManager == null) {
- if( colNameSortValues!=null && colSortName.compareTo(ch.getColumnSort()) < 0)
- posFound = true;
- else if (colNameSortValues==null && colName.compareTo(ch.getColumnTitle()) < 0)
- posFound = true;
- }
- else // if(prevColName!=null&&(!
- // prevColName.equals(reportColumnHeaderRows.getColumnHeader(r-1,
- // colIdx).getColumnTitle())))
- if (prevColNamesChanged(colIdx, prevColNames))
- posFound = true;
-
- if ((!nameFound) && (!posFound))
- colIdx++;
- } // while
-
- if (!nameFound)
- if (createIfMissing && (MAX_NUM_COLS >= 0) && (colIdx <= MAX_NUM_COLS)) {
- insertColumn(colIdx, colNameValues, colNameSortValues, dataList, chr.getAlignment());
- return colIdx;
- } else
- return -1;
-
- prevColNames.add(r, colName);
- } // for
- if (!nameFound)
- if (createIfMissing && (MAX_NUM_COLS >= 0) && (colIdx <= MAX_NUM_COLS))
- insertColumn(colIdx, colNameValues, colNameSortValues, dataList, "center");
- else
- return -1;
- } catch (Exception ex) {ex.printStackTrace();}
-
- return colIdx;
- } // findColumnIdx
-
- private void insertRow(int rowIdx, Vector rowNameValues, List dataList, CrossTabOrderManager crossTabOrderManager) {
- int c = 0;
- DataRow dr = new DataRow();
- int dataRowIdx = 0;
- for (reportRowHeaderCols.resetNext(); reportRowHeaderCols.hasNext();) {
- if((c+1)==reportRowHeaderCols.size()) {
- dataRowIdx = crossTabOrderManager.getIndexOfRowHeaderValue(c, ((DataValue) rowNameValues.get(c)).getDisplayValue());
- }
- RowHeaderCol rhc = reportRowHeaderCols.getNext();
- rhc.addRowHeader(rowIdx, new RowHeader(((DataValue) rowNameValues.get(c)).getDisplayValue()));
- c++;
- } // for
-
- dr.setRowNum(dataRowIdx);
- for (c = 0; c < getDataColumnCount(); c++) {
- dr.addDataValue(new DataValue());
- }
-
- //reportDataRows.addDataRow(rowIdx, dr);
- //dr.setRowNum(dataList.size()==0?1:dataList.size());
- dataList.add(rowIdx, dr);
-
- } // insertRow
-
- private boolean prevRowNamesChanged(int rowIdx, Vector prevRowNames) {
- for (int k = 0; k < prevRowNames.size(); k++)
- if (!nvl((String) prevRowNames.get(k)).equals(
- reportRowHeaderCols.getRowHeader(k, rowIdx).getRowTitle()))
- return true;
-
- return false;
- } // prevRowNamesChanged
-
- private int findRowIdx(Vector rowNameValues, CrossTabOrderManager crossTabOrderManager,
- boolean createIfMissing, List dataList) {
- int rowIdx = 0;
- boolean nameFound = false;
- Vector prevRowNames = new Vector();
- for (int c = 0; c < rowNameValues.size(); c++) {
- //String rowName = (String) rowNameValues.get(c);
- String rowName = ((DataValue) rowNameValues.get(c)).getDisplayValue();
-
- RowHeaderCol rhc = reportRowHeaderCols.getRowHeaderCol(c);
-
- rhc.resetNext(rowIdx);
- nameFound = false;
- boolean posFound = false;
- while ((!nameFound) && (!posFound) && rhc.hasNext()) {
- RowHeader rh = rhc.getNext();
- if (rowName.equals(rh.getRowTitle())) {
- if (prevRowNamesChanged(rowIdx, prevRowNames))
- posFound = true;
- else
- nameFound = true;
- } else if (crossTabOrderManager != null
- && crossTabOrderManager.isAfterRowHeaderValue(c, rh.getRowTitle(),
- rowName))
- posFound = true;
- else if (crossTabOrderManager == null
- && rowName.compareTo(rh.getRowTitle()) < 0)
- posFound = true;
- else if (prevRowNamesChanged(rowIdx, prevRowNames))
- posFound = true;
-
- if ((!nameFound) && (!posFound))
- rowIdx++;
- } // while
-
- if (!nameFound)
- if (createIfMissing) {
- insertRow(rowIdx, rowNameValues, dataList, crossTabOrderManager);
- return rowIdx;
- } else
- return -1;
-
- prevRowNames.add(c, rowName);
- } // for
- if (!nameFound)
- if (createIfMissing)
- insertRow(rowIdx, rowNameValues, dataList, crossTabOrderManager);
- else
- return -1;
-
- return rowIdx;
- } // findRowIdx
-
- public void setDataValue(Vector rowNameValues, Vector colNameValues, Vector colNameSortValues, DataValue value,
- FormatProcessor formatProcessor, CrossTabOrderManager crossTabOrderManager, List dataList) {
- int rowIdx = findRowIdx(rowNameValues, crossTabOrderManager, true, dataList);
- int colIdx = findColumnIdx(colNameValues, colNameSortValues, crossTabOrderManager, true, dataList);
-
- if ((rowIdx >= 0) && (colIdx >= 0)) {
- //DataRow dr = reportDataRows.getDataRow(rowIdx);
- DataRow dr = (DataRow)dataList.get(rowIdx);
- dr.setRowValues(rowNameValues);
- dr.setDataValue(colIdx, value);
- formatProcessor.setHtmlFormatters(value, dr, false);
- } // if
- } // setDataValue
-
- public void consolidateColumnHeaders(VisualManager visualManager) {
- // Setting column visuals
- for (int i = 0; i < reportColumnHeaderRows.getColumnHeaderRow(
- reportColumnHeaderRows.getRowCount() - 1).size(); i++) {
- StringBuffer sb = new StringBuffer();
-
- for (int ir = 0; ir < reportColumnHeaderRows.getRowCount(); ir++) {
- ColumnHeader ch = reportColumnHeaderRows.getColumnHeaderRow(ir)
- .getColumnHeader(i);
- if (sb.length() > 0)
- sb.append('|');
- sb.append(Utils.replaceInString(ch.getColumnTitle(), "|", " "));
- } // for
-
- String colValue = sb.toString();
- columnVisuals.add(new ColumnVisual(colValue, colValue, visualManager
- .isColumnVisible(colValue), /* visualManager.getSortByColId().equals(colValue)?visualManager.getSortByAscDesc(): */
- null));
- } // for
-
- // Consolidating column headers
- for (int r = reportColumnHeaderRows.getRowCount() - 1; r >= 0; r--) {
- ColumnHeaderRow chr = reportColumnHeaderRows.getColumnHeaderRow(r);
-
- if (chr.size() > 0) {
- ColumnHeader baseCH = chr.getColumnHeader(0);
- int c = 1;
- int c_shift = 0;
- while (c < chr.size()) {
- ColumnHeader ch = chr.getColumnHeader(c);
-
- boolean performMerge = true;
- for (int ir = r; ir >= 0; ir--) {
- ColumnHeaderRow ichr = reportColumnHeaderRows.getColumnHeaderRow(ir);
- ColumnHeader ch0 = ichr.getColumnHeader(c + ((ir == r) ? 0 : c_shift));
- ColumnHeader ch1 = ichr.getColumnHeader(c + ((ir == r) ? 0 : c_shift)
- - 1);
- if (!ch0.getColumnTitle().equals(ch1.getColumnTitle()))
- performMerge = false;
- } // for
-
- if (performMerge) {
- c_shift++;
- baseCH.setColSpan(baseCH.getColSpan() + 1);
- chr.remove(c);
- } else {
- baseCH = ch;
- c++;
- }
- } // while
- } // if
- } // for
- } // consolidateColumnHeaders
-
- public void consolidateRowHeaders() {
- for (int c = reportRowHeaderCols.getColumnCount() - 1; c >= 0; c--) {
- RowHeaderCol rhc = reportRowHeaderCols.getRowHeaderCol(c);
-
- if (rhc.size() > 0) {
- RowHeader baseRH = rhc.getRowHeader(0);
- int r = 1;
- while (r < rhc.size()) {
- RowHeader rh = rhc.getRowHeader(r);
-
- boolean performMerge = rh.getRowTitle().equals(baseRH.getRowTitle());
- for (int ic = c - 1; ic >= 0; ic--) {
- RowHeaderCol irhc = reportRowHeaderCols.getRowHeaderCol(ic);
- RowHeader rh0 = irhc.getRowHeader(r);
- RowHeader rh1 = irhc.getRowHeader(r - 1);
- if (!rh0.getRowTitle().equals(rh1.getRowTitle()))
- performMerge = false;
- } // for
-
- if (performMerge)
- rh.setRowTitle(null);
- else
- baseRH = rh;
-
- r++;
- } // while
- } // if
- } // for
- } // consolidateRowHeaders
-
- public void addRowNumbers(int pageNo, List dataList) {
- pageNo = 0;
- //int startRowNum = ((pageNo < 0) ? 0 : pageNo) * pageSize + 1;
- int startRowNum = 0;
- RowHeaderCol rhc = new RowHeaderCol();
- reportRowHeaderCols.addRowHeaderCol(0, rhc);
- //rhc.setColumnWidth("5%");
- for (int r = 0; r < dataList.size(); r++) {
- rhc.add(new RowHeader(startRowNum + r+""));
- ((DataRow)dataList.get(r)).setRowNum(r);
- }
- } // addRowNumbers
-
- private void removeRow(int rowIdx) {
- for (reportRowHeaderCols.resetNext(); reportRowHeaderCols.hasNext();) {
- RowHeaderCol rhc = reportRowHeaderCols.getNext();
- rhc.remove(rowIdx);
- } // for
-
- reportDataRows.remove(rowIdx);
- } // removeRow
-
- public void truncateData(int startRow, int endRow) {
- if( endRow != -1){
- for (int r = getDataRowCount() - 1; r > endRow; r--)
- removeRow(r);
- }
-
- for (int r = startRow - 1; r >= 0; r--)
- removeRow(r);
- } // truncateData
-
- /** *********************************************************************************** */
-
- public void createColumn(String colId, String displayName, String displayWidthInPxls, String alignment,
- boolean currentlyVisible, String currentSort, boolean isRuntimeColSortDisabled, int level, int start, int colspan, boolean sortable) {
- ColumnHeaderRow chr = null;
- if (getHeaderRowCount() > 0)
- chr = reportColumnHeaderRows.getColumnHeaderRow(0);
- else {
- chr = new ColumnHeaderRow();
- reportColumnHeaderRows.addColumnHeaderRow(chr);
- chr.setRowHeight("30");
- } // if
- /*ColumnHeader ch = new ColumnHeader(displayName, (displayWidth > 100) ? "10%" : (""
- + displayWidth + "%"), alignment, 1, isRuntimeColSortDisabled ? null : colId);
- */
- ColumnHeader ch = new ColumnHeader(displayName, displayWidthInPxls, alignment, 1, isRuntimeColSortDisabled ? null : colId);
- ch.setGroupLevel(level);
- ch.setStartGroup(start);
- ch.setColSpanGroup(colspan);
- ch.setColId(colId);
- ch.setSortable(sortable);
- //chr.addColumnHeader(new ColumnHeader(displayName, (displayWidth > 100) ? "10%" : (""
- // + displayWidth + "%"), 1, isRuntimeColSortDisabled ? null : colId));
-
- if (displayName != "Hidden") {
-
- chr.addColumnHeader(ch);
- columnVisuals.add(new ColumnVisual(colId, displayName, currentlyVisible, currentSort));
- }
- } // createColumn
-
- public void columnVisualShowHide(String colId, boolean newVisible) {
- for (int i = 0; i < columnVisuals.size(); i++) {
- ColumnVisual col = (ColumnVisual) columnVisuals.get(i);
- if (col.getColId().equals(colId)) {
- col.setVisible(newVisible);
- applyColumnVisibility(i, newVisible);
- break;
- } // if
- } // for
- } // columnVisualShowHide
-
- private void applyColumnVisibility(int colIdx, boolean newVisible) {
- boolean isLast = true;
- for (int r = reportColumnHeaderRows.getRowCount() - 1; r >= 0; r--) {
- ColumnHeaderRow chr = reportColumnHeaderRows.getColumnHeaderRow(r);
-
- if (isLast) {
- chr.getColumnHeader(colIdx).setVisible(newVisible);
- isLast = false;
- } else {
- int curStartIdx = 0;
- for (chr.resetNext(); chr.hasNext();) {
- ColumnHeader ch = chr.getNext();
- if (colIdx >= curStartIdx && colIdx <= curStartIdx + ch.getColSpan() - 1) {
- ch.setVisible(newVisible);
- break;
- } else
- curStartIdx += ch.getColSpan();
- } // for
- } // else
- } // for
- int row = 0;
- for (reportDataRows.resetNext(); reportDataRows.hasNext();) {
- //reportDataRows.getNext().getDataValue(colIdx).setVisible(newVisible);
- DataRow dr = reportDataRows.getNext();
- if(colIdx < dr.getDataValueList().size()) {
- DataValue dv = dr.getDataValue(colIdx);
- dr.getDataValueList().remove(colIdx);
- if(!dv.isHidden())
- dv.setVisible(newVisible);
- else
- dv.setVisible(false);
- dr.addDataValue(colIdx, dv);
- }
- reportDataRows.removeElementAt(row);
- reportDataRows.addDataRow(row, dr);
- row++;
- }
- } // applyColumnVisibility
-
- public void applyVisibility() {
- for (int i = 0; i < columnVisuals.size(); i++)
- applyColumnVisibility(i, ((ColumnVisual) columnVisuals.get(i)).isVisible());
- } // applyVisibility
-
- public void resetVisualSettings() {
- // No need to reset sort - if sort exists, the report data is reloaded
- for (int i = 0; i < columnVisuals.size(); i++)
- ((ColumnVisual) columnVisuals.get(i)).setVisible(true);
-
- applyVisibility();
- } // resetVisualSettings
-
- /** *********************************************************************************** */
-
- private int nextVisualIdx = 0;
-
- public void resetNextVisual() {
- resetNextVisual(0);
- } // resetNext
-
- public void resetNextVisual(int toPos) {
- nextVisualIdx = toPos;
- } // resetNext
-
- public boolean hasNextVisual() {
- return (nextVisualIdx < columnVisuals.size());
- } // hasNext
-
- public String getNextHiddenColLinks(int toPos) {
- resetNextVisual(toPos);
- return getNextHiddenColLinks();
- } // getNextHiddenColLinks
-
- public String getNextHiddenColLinks() {
- if (!hasNextVisual())
- return "";
-
- StringBuffer sb = new StringBuffer();
- ColumnVisual col = (ColumnVisual) columnVisuals.get(nextVisualIdx);
-
- while (!col.isVisible()) {
- if(!col.getColDisplay().equals(AppConstants.HIDDEN)) {
- sb.append("<input type=image border=0 src='");
- sb.append(AppUtils.getImgFolderURL());
- sb.append("plus.gif' alt=\"Show column ");
- sb.append(col.getColDisplay());
- sb.append("\" width=11 height=11 onClick=\"document.formd.");
- sb.append(AppConstants.RI_VISUAL_ACTION);
- sb.append(".value='");
- sb.append(AppConstants.VA_SHOW);
- sb.append("';document.formd.");
- sb.append(AppConstants.RI_DETAIL_ID);
- sb.append(".value='");
- sb.append(col.getColId());
- sb.append("';document.formd.submit();\">");
- }
-
- if (!(nextVisualIdx + 1 < columnVisuals.size()))
- break;
- col = (ColumnVisual) columnVisuals.get(++nextVisualIdx);
- } // while
-
- return sb.toString();
- } // getNextHiddenColLinks
-
- public String getNextVisual() {
- if (!hasNextVisual())
- return null;
-
- ColumnVisual col = (ColumnVisual) columnVisuals.get(nextVisualIdx++);
-
- StringBuffer sb = new StringBuffer();
-
- if (!col.isVisible() || col.getColDisplay().equals(AppConstants.HIDDEN))
- return null;
-
- sb.append("\n\t\t\t<table width=100% border=0 cellspacing=0 cellpadding=0><tr>\n");
- sb
- .append("\t\t\t\t<td style=\"background:#ffffff;\" align=left valign=middle nowrap><input type=image border=0 src='");
- sb.append(AppUtils.getImgFolderURL());
- sb.append("minus.gif' alt=\"Hide column ");
- sb.append(col.getColDisplay());
- sb.append("\" width=11 height=11 onClick=\"document.formd.");
- sb.append(AppConstants.RI_VISUAL_ACTION);
- sb.append(".value='");
- sb.append(AppConstants.VA_HIDE);
- sb.append("';document.formd.");
- sb.append(AppConstants.RI_DETAIL_ID);
- sb.append(".value='");
- sb.append(col.getColId());
- sb.append("';document.formd.submit();");
- sb.append("\"></td>\n");
- sb.append("\t\t\t\t<td style=\"background:#ffffff;\" align=center valign=middle width=95% nowrap>");
- if (col.getSortType() != null) {
- sb.append("<img border=0 src='");
- sb.append(AppUtils.getImgFolderURL());
- if (col.getSortType().equals(AppConstants.SO_ASC))
- sb.append("grnarrowdn.gif");
- else
- sb.append("grnarrowup.gif");
- sb.append("' alt=\"Sorted by column ");
- sb.append(col.getColDisplay());
- if (col.getSortType().equals(AppConstants.SO_ASC))
- sb.append(" ascending");
- else
- sb.append(" descending");
- sb.append("\" width=13 height=11>");
- }
- sb.append("</td>\n");
- sb.append("\t\t\t\t<td style=\"background:#ffffff;\" align=right valign=middle nowrap>");
- sb.append(getNextHiddenColLinks());
- sb.append("</td>\n");
- sb.append("\t\t\t</tr></table>\n\t\t");
-
- return sb.toString();
- } // getNext
-
- /** *********************************************************************************** */
-
- public void setColumnDataTotalsLinear(DataRow colDataTotals, String colTotalLabel) {
- //commented so that we could differentiate data rows with total rows
- //reportDataRows.addDataRow(colDataTotals);
- RowHeader rh = new RowHeader(colTotalLabel, "45", 1, reportRowHeaderCols.getColumnCount(),true);
- if(reportRowHeaderCols.size()>0)
- reportRowHeaderCols.getRowHeaderCol(0).add(rh);
-
- reportDataTotalRow = new ReportDataRows();
- reportDataTotalRow.addDataRow(colDataTotals);
- RowHeaderCol rhc = new RowHeaderCol();
- rhc.add(rh);
- reportTotalRowHeaderCols = new ReportRowHeaderCols();
- reportTotalRowHeaderCols.addRowHeaderCol(0, rhc);
- } // setColumnDataTotalsLinear
-
- public void setCrossTabColumnTotalLabel(String colTotalLabel) {
- reportRowHeaderCols.getRowHeaderCol(0).getRowHeader(getDataRowCount() - 1)
- .setRowTitle("");
- reportRowHeaderCols.getRowHeaderCol(0).getRowHeader(getDataRowCount() - 1).setColSpan(
- 0);
- reportRowHeaderCols.getRowHeaderCol(1).set(
- getDataRowCount() - 1,
- new RowHeader(colTotalLabel, "45", 1, reportRowHeaderCols.getColumnCount(),
- true));
- } // setCrossTabColumnTotalLabel
-
- public void setCrossTabColumnTotalLabel(int reportDataSize, String colTotalLabel) {
-
- reportRowHeaderCols.getRowHeaderCol(0).getRowHeader(getDataRowCount() - 1)
- .setRowTitle("");
- reportRowHeaderCols.getRowHeaderCol(0).getRowHeader(getDataRowCount() - 1).setColSpan(
- 0);
- reportRowHeaderCols.getRowHeaderCol(1).set(
- getDataRowCount() - 1,
- new RowHeader(colTotalLabel, "45", 1, reportRowHeaderCols.getColumnCount(),
- true));
- } // setCrossTabColumnTotalLabel
-
- public void setColumnDataTotalsCrossTab(Vector colDataTotals, String totalsAlignment,
- String colDisplayTotal, CrossTabOrderManager crossTabOrderManager, List dataList) {
- DataRow totalsDataRow = new DataRow();
- for (int c = 0; c < getDataColumnCount(); c++)
- totalsDataRow.addDataValue(new DataValue());
-
- for (Iterator iter = colDataTotals.iterator(); iter.hasNext();) {
- CrossTabTotalValue tVal = (CrossTabTotalValue) iter.next();
-
- int colIdx = findColumnIdx(tVal.getHeaderValues(), null, crossTabOrderManager, false, dataList);
- if (colIdx >= 0) {
- DataValue dataValue = new DataValue();
-
- String totalValue = tVal.getTotalValue();
- // if(colDisplayTotal.length()>0&&(!
- // colDisplayTotal.equals(AppConstants.TOTAL_SUM_ID)))
- // totalValue =
- // nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(colDisplayTotal))+":
- // "+totalValue;
- dataValue.setDisplayValue(totalValue);
- //added below statement for displaying in excel as number
- dataValue.setDisplayTotal("SUM(");
- dataValue.setAlignment(totalsAlignment);
- dataValue.setBold(true);
- totalsDataRow.setDataValue(colIdx, dataValue);
-
- //totalsDataRow.addDataValue(dataValue);
-
- } // if
- } // for
-
- //reportDataRows.addDataRow(totalsDataRow);
- //dr.setRowValues(rowNameValues);
- Vector rowNameValues = new Vector();
- for (int i=0; i < reportRowHeaderCols.size(); i++) {
- if(i==0) {
- DataValue dataValue = new DataValue();
- dataValue.setBold(true);
- dataValue.setAlignment("center");
- dataValue.setDisplayValue("Total");
- rowNameValues.add(dataValue);
- //rowNameValues.add("Total");
- } else {
- //rowNameValues.add("");
- DataValue dataValue = new DataValue();
- dataValue.setDisplayValue("");
- rowNameValues.add(dataValue);
-
- }
- }
- totalsDataRow.setRowValues(rowNameValues);
- totalsDataRow.setRowNum(dataList.size());
- dataList.add(totalsDataRow);
- //reportRowHeaderCols.getNext().addRowHeader(new RowHeader("", "30", 1, 0));
- } // setColumnDataTotalsCrossTab
-
- public void setRowDataTotalsCrossTab(Vector rowDataTotals, String totalsAlignment,
- String rowDisplayTotal, CrossTabOrderManager crossTabOrderManager, List dataList) {
- int colIdx = getDataColumnCount();
-
- boolean isFirst = true;
- for (reportColumnHeaderRows.resetNext(); reportColumnHeaderRows.hasNext();) {
- ColumnHeaderRow chr = reportColumnHeaderRows.getNext();
- if (isFirst) {
- String totalLabel = "Total";
- if (rowDisplayTotal.length() > 0
- && (!rowDisplayTotal.equals(AppConstants.TOTAL_SUM_ID)))
- totalLabel = nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(rowDisplayTotal));
- chr.addColumnHeader(colIdx, new ColumnHeader(totalLabel, "", 1,
- reportColumnHeaderRows.getRowCount()));
- isFirst = false;
- } else
- chr.addColumnHeader(colIdx, new ColumnHeader("", "", 1, 0));
- } // for
-
- for (reportDataRows.resetNext(); reportDataRows.hasNext();) {
- DataRow dr = reportDataRows.getNext();
- dr.addDataValue(colIdx, new DataValue());
- } // for
-
- for (Iterator iter = rowDataTotals.iterator(); iter.hasNext();) {
- CrossTabTotalValue tVal = (CrossTabTotalValue) iter.next();
-
- int rowIdx = findRowIdx(tVal.getHeaderValues(), crossTabOrderManager, false, dataList);
- if (rowIdx >= 0) {
- DataValue dataValue = new DataValue();
-
- String totalValue = tVal.getTotalValue();
- // if(rowDisplayTotal.length()>0&&(!
- // rowDisplayTotal.equals(AppConstants.TOTAL_SUM_ID)))
- // totalValue =
- // nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(rowDisplayTotal))+":
- // "+totalValue;
- dataValue.setDisplayValue(totalValue);
- //added below statement for displaying in excel as number
- dataValue.setDisplayTotal("SUM(");
- dataValue.setAlignment(totalsAlignment);
- dataValue.setBold(true);
-
- //reportDataRows.getDataRow(rowIdx).getDataValueList().add(colIdx, dataValue);
- ((DataRow)dataList.get(rowIdx)).addDataValue(colIdx, dataValue);
- } // if
- } // for
- } // setRowDataTotalsCrossTab
-
- public void setGrandTotalCrossTab(String totalValue, String totalAlignment,
- String displayTotal, List dataList) {
- DataValue dataValue = new DataValue();
-
- // if(displayTotal.length()>0&&(!
- // displayTotal.equals(AppConstants.TOTAL_SUM_ID)))
- // totalValue =
- // nvl(AppConstants.TOTAL_FUNCTIONS.getNameById(displayTotal))+":
- // "+totalValue;
- dataValue.setDisplayValue(totalValue);
- //added below statement for displaying in excel as number
- dataValue.setDisplayTotal("SUM(");
- dataValue.setAlignment(totalAlignment);
- dataValue.setBold(true);
-
- //int colIdx = getDataColumnCount() - 1;
- int rowIdx = getDataRowCount() - 1;
- //reportDataRows.getDataRow(rowIdx).getDataValueList().add(colIdx, dataValue);
- DataRow dr = (DataRow)dataList.get(rowIdx);
- dr.addDataValue(dr.getDataValueList().size(), dataValue);
- } // setGrandTotalCrossTab
-
- public List getReportDataList() {
- return reportDataList;
- }
-
- public void setReportDataList(List reportDataList) {
- this.reportDataList = reportDataList;
- }
-
-} // ReportData
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import java.util.*;
-
-public class ReportDataRows extends Vector {
- 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 DataRow getNext() {
- return hasNext() ? getDataRow(nextElemIdx++) : null;
- } // getNext
-
- public DataValue getDataValue(int rowIdx, int colIdx) {
- return getDataRow(rowIdx).getDataValue(colIdx);
- } // getDataValue
-
- public DataRow getDataRow(int idx) {
- return (DataRow) get(idx);
- } // getDataRow
-
- public void addDataRow(DataRow dataRow) {
- add(dataRow);
- } // addDataRow
-
- public void addDataRow(int idx, DataRow dataRow) {
- add(idx, dataRow);
- } // addDataRow
-
- public int getRowCount() {
- return size();
- } // getRowCount
-
- public int getColumnCount() {
- int cSize = 0;
- if (getRowCount() > 0)
- cSize = getDataRow(0).getDataValueList().size();
-
- return cSize;
- } // getColumnCount
-
-} // ReportDataRows
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import java.util.*;
-
-public class ReportRowHeaderCols extends Vector {
- 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 RowHeaderCol getNext() {
- return hasNext() ? getRowHeaderCol(nextElemIdx++) : null;
- } // getNext
-
- public RowHeader getRowHeader(int colIdx, int rowIdx) {
- return getRowHeaderCol(colIdx).getRowHeader(rowIdx);
- } // getRowHeader
-
- public RowHeaderCol getRowHeaderCol(int idx) {
- return (RowHeaderCol) get(idx);
- } // getRowHeaderCol
-
- public void addRowHeaderCol(RowHeaderCol rowHeaderCol) {
- add(rowHeaderCol);
- } // addRowHeaderCol
-
- public void addRowHeaderCol(int idx, RowHeaderCol rowHeaderCol) {
- add(idx, rowHeaderCol);
- } // addRowHeaderCol
-
- public int getRowCount() {
- int cSize = 0;
- if (getColumnCount() > 0)
- cSize = getRowHeaderCol(0).size();
-
- return cSize;
- } // getRowCount
-
- public int getColumnCount() {
- return size();
- } // getColumnCount
-
-} // ReportRowHeaderCols
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class RowHeader extends org.openecomp.portalsdk.analytics.RaptorObject {
- private String rowTitle = "";
-
- private String rowHeight = "";
-
- private int rowSpan = 1;
-
- private int colSpan = 1;
-
- private boolean bold = false;
-
- public RowHeader() {
- super();
- }
-
- public RowHeader(String rowTitle) {
- this();
- setRowTitle(rowTitle);
- } // RowHeader
-
- public RowHeader(String rowTitle, String rowHeight) {
- this(rowTitle);
- setRowHeight(rowHeight);
- } // RowHeader
-
- public RowHeader(String rowTitle, String rowHeight, int rowSpan) {
- this(rowTitle, rowHeight);
- setRowSpan(rowSpan);
- } // RowHeader
-
- public RowHeader(String rowTitle, String rowHeight, int rowSpan, int colSpan) {
- this(rowTitle, rowHeight, rowSpan);
- setColSpan(colSpan);
- } // RowHeader
-
- public RowHeader(String rowTitle, String rowHeight, int rowSpan, int colSpan, boolean bold) {
- this(rowTitle, rowHeight, rowSpan, colSpan);
- setBold(bold);
- } // RowHeader
-
- public String getRowTitle() {
- return rowTitle;
- }
-
- public String getRowHeight() {
- return rowHeight;
- }
-
- public int getRowSpan() {
- return rowSpan;
- }
-
- public int getColSpan() {
- return colSpan;
- }
-
- public boolean isBold() {
- return bold;
- }
-
- public void setRowTitle(String rowTitle) {
- this.rowTitle = nvl(rowTitle);
- }
-
- public void setRowHeight(String rowHeight) {
- this.rowHeight = rowHeight;
- }
-
- public void setRowSpan(int rowSpan) {
- this.rowSpan = rowSpan;
- }
-
- public void setColSpan(int colSpan) {
- this.colSpan = colSpan;
- }
-
- public void setBold(boolean bold) {
- this.bold = bold;
- }
-
- public String getRowTitleHtml() {
- return (rowTitle.length() == 0) ? " " : rowTitle;
- }
-
- public String getRowHeightHtml() {
- return (rowHeight.length() == 0) ? "" : (" height=" + rowHeight);
- }
-
- public String getRowSpanHtml() {
- return (rowSpan == 1) ? "" : (" rowspan=" + rowSpan);
- }
-
- public String getColSpanHtml() {
- return (colSpan == 1) ? "" : (" colspan=" + colSpan);
- }
-
-} // RowHeader
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.view;
-
-import java.util.*;
-
-import org.openecomp.portalsdk.analytics.util.*;
-
-public class RowHeaderCol extends Vector {
- private String columnWidth = "";
-
- private String columnTitle = "";
-
- private String alignment = "";
-
- private String displayHeaderAlignment = "";
-
- private int nextElemIdx = 0;
-
- private boolean visible = true;
-
- private String colId = "";
-
- private String nowrap = "False";
-
- public void resetNext() {
- resetNext(0);
- } // resetNext
-
- public void resetNext(int toPos) {
- nextElemIdx = toPos;
- } // resetNext
-
- public boolean hasNext() {
- return (nextElemIdx < size());
- } // hasNext
-
- public RowHeader getNext() {
- return hasNext() ? getRowHeader(nextElemIdx++) : null;
- } // getNext
-
- public RowHeader getRowHeader(int idx) {
- return (RowHeader) get(idx);
- } // getRowHeader
-
- public void addRowHeader(RowHeader rowHeader) {
- add(rowHeader);
- } // addRowHeader
-
- public void addRowHeader(int idx, RowHeader rowHeader) {
- add(idx, rowHeader);
- } // addRowHeader
-
- public String getColumnTitle() {
- return columnTitle;
- }
-
- public String getColumnWidth() {
- return columnWidth;
- }
-
- public String getAlignment() {
- return alignment;
- }
-
- public void setColumnTitle(String columnTitle) {
- this.columnTitle = nvl(columnTitle);
- }
-
- public void setColumnWidth(String columnWidth) {
- this.columnWidth = nvl(columnWidth);
- }
-
- public void setAlignment(String alignment) {
- this.alignment = alignment;
- }
-
- public String getColumnTitleHtml() {
- return (columnTitle.length() == 0) ? " " : columnTitle;
- }
-
- public String getColumnWidthHtml() {
- return (columnWidth.length() == 0) ? "" : (" width=" + columnWidth);
- }
-
- public String getAlignmentHtml() {
- return " align=" + nvl(alignment, "center");
- }
-
- /** ************************************************************************************************* */
-
- private String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- private String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
- public String getNowrap() {
- return nowrap;
- }
-
- public void setNowrap(String nowrap) {
- this.nowrap = nowrap;
- }
-
- public boolean isVisible() {
- return visible;
- }
-
- public void setVisible(boolean visible) {
- this.visible = visible;
- }
-
- /**
- * @return the colId
- */
- public String getColId() {
- return colId;
- }
-
- /**
- * @param colId the colId to set
- */
- public void setColId(String colId) {
- this.colId = colId;
- }
-
- public String getDisplayHeaderAlignment() {
- return displayHeaderAlignment;
- }
-
- public void setDisplayHeaderAlignment(String displayHeaderAlignment) {
- this.displayHeaderAlignment = displayHeaderAlignment;
- }
-
-
-
-} // RowHeaderCol
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for ChartAdditionalOptions complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="ChartAdditionalOptions">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="chartMultiplePieOrder" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartMultiplePieLabelDisplay" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartOrientation" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="secondaryChartRenderer" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartDisplay" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="hideToolTips" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="hidechartLegend" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="legendPosition" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="labelAngle" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="intervalFromdate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="intervalTodate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="intervalLabel" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="lastSeriesALineChart" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="lastSeriesABarChart" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="maxLabelsInDomainAxis" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="linearRegression" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="linearRegressionColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="exponentialRegressionColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="maxRegression" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="rangeAxisUpperLimit" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="rangeAxisLowerLimit" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="overlayItemValueOnStackBar" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="animate" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="animateAnimatedChart" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="keepDomainAxisValueAsString" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="stacked" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="barControls" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="xAxisDateType" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="lessXaxisTickers" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="timeAxis" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="timeSeriesRender" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="multiSeries" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="showXAxisLabel" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="addXAxisTickers" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="zoomIn" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="timeAxisType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="logScale" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="topMargin" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="bottomMargin" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="rightMargin" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="leftMargin" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "ChartAdditionalOptions", propOrder = {
- "chartMultiplePieOrder",
- "chartMultiplePieLabelDisplay",
- "chartOrientation",
- "secondaryChartRenderer",
- "chartDisplay",
- "hideToolTips",
- "hidechartLegend",
- "legendPosition",
- "labelAngle",
- "intervalFromdate",
- "intervalTodate",
- "intervalLabel",
- "lastSeriesALineChart",
- "lastSeriesABarChart",
- "maxLabelsInDomainAxis",
- "linearRegression",
- "linearRegressionColor",
- "exponentialRegressionColor",
- "maxRegression",
- "rangeAxisUpperLimit",
- "rangeAxisLowerLimit",
- "overlayItemValueOnStackBar",
- "animate",
- "animateAnimatedChart",
- "keepDomainAxisValueAsString",
- "stacked",
- "barControls",
- "xAxisDateType",
- "lessXaxisTickers",
- "timeAxis",
- "timeSeriesRender",
- "multiSeries",
- "showXAxisLabel",
- "addXAxisTickers",
- "zoomIn",
- "timeAxisType",
- "logScale",
- "topMargin",
- "bottomMargin",
- "rightMargin",
- "leftMargin"
-})
-public class ChartAdditionalOptions {
-
- protected String chartMultiplePieOrder;
- protected String chartMultiplePieLabelDisplay;
- protected String chartOrientation;
- protected String secondaryChartRenderer;
- protected String chartDisplay;
- protected String hideToolTips;
- protected String hidechartLegend;
- protected String legendPosition;
- protected String labelAngle;
- protected String intervalFromdate;
- protected String intervalTodate;
- protected String intervalLabel;
- protected String lastSeriesALineChart;
- protected String lastSeriesABarChart;
- protected String maxLabelsInDomainAxis;
- protected String linearRegression;
- protected String linearRegressionColor;
- protected String exponentialRegressionColor;
- protected String maxRegression;
- protected String rangeAxisUpperLimit;
- protected String rangeAxisLowerLimit;
- protected String overlayItemValueOnStackBar;
- @XmlElement(defaultValue = "false")
- protected Boolean animate;
- @XmlElement(defaultValue = "true")
- protected Boolean animateAnimatedChart;
- protected String keepDomainAxisValueAsString;
- @XmlElement(defaultValue = "false")
- protected Boolean stacked;
- @XmlElement(defaultValue = "false")
- protected Boolean barControls;
- @XmlElement(defaultValue = "false")
- protected Boolean xAxisDateType;
- @XmlElement(defaultValue = "false")
- protected Boolean lessXaxisTickers;
- @XmlElement(defaultValue = "true")
- protected Boolean timeAxis;
- protected String timeSeriesRender;
- @XmlElement(defaultValue = "false")
- protected Boolean multiSeries;
- @XmlElement(defaultValue = "false")
- protected Boolean showXAxisLabel;
- @XmlElement(defaultValue = "false")
- protected Boolean addXAxisTickers;
- protected Integer zoomIn;
- protected String timeAxisType;
- @XmlElement(defaultValue = "false")
- protected Boolean logScale;
- protected Integer topMargin;
- protected Integer bottomMargin;
- protected Integer rightMargin;
- protected Integer leftMargin;
-
- /**
- * Gets the value of the chartMultiplePieOrder property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartMultiplePieOrder() {
- return chartMultiplePieOrder;
- }
-
- /**
- * Sets the value of the chartMultiplePieOrder property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartMultiplePieOrder(String value) {
- this.chartMultiplePieOrder = value;
- }
-
- /**
- * Gets the value of the chartMultiplePieLabelDisplay property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartMultiplePieLabelDisplay() {
- return chartMultiplePieLabelDisplay;
- }
-
- /**
- * Sets the value of the chartMultiplePieLabelDisplay property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartMultiplePieLabelDisplay(String value) {
- this.chartMultiplePieLabelDisplay = value;
- }
-
- /**
- * Gets the value of the chartOrientation property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartOrientation() {
- return chartOrientation;
- }
-
- /**
- * Sets the value of the chartOrientation property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartOrientation(String value) {
- this.chartOrientation = value;
- }
-
- /**
- * Gets the value of the secondaryChartRenderer property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getSecondaryChartRenderer() {
- return secondaryChartRenderer;
- }
-
- /**
- * Sets the value of the secondaryChartRenderer property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setSecondaryChartRenderer(String value) {
- this.secondaryChartRenderer = value;
- }
-
- /**
- * Gets the value of the chartDisplay property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartDisplay() {
- return chartDisplay;
- }
-
- /**
- * Sets the value of the chartDisplay property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartDisplay(String value) {
- this.chartDisplay = value;
- }
-
- /**
- * Gets the value of the hideToolTips property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getHideToolTips() {
- return hideToolTips;
- }
-
- /**
- * Sets the value of the hideToolTips property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setHideToolTips(String value) {
- this.hideToolTips = value;
- }
-
- /**
- * Gets the value of the hidechartLegend property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getHidechartLegend() {
- return hidechartLegend;
- }
-
- /**
- * Sets the value of the hidechartLegend property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setHidechartLegend(String value) {
- this.hidechartLegend = value;
- }
-
- /**
- * Gets the value of the legendPosition property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getLegendPosition() {
- return legendPosition;
- }
-
- /**
- * Sets the value of the legendPosition property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setLegendPosition(String value) {
- this.legendPosition = value;
- }
-
- /**
- * Gets the value of the labelAngle property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getLabelAngle() {
- return labelAngle;
- }
-
- /**
- * Sets the value of the labelAngle property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setLabelAngle(String value) {
- this.labelAngle = value;
- }
-
- /**
- * Gets the value of the intervalFromdate property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getIntervalFromdate() {
- return intervalFromdate;
- }
-
- /**
- * Sets the value of the intervalFromdate property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setIntervalFromdate(String value) {
- this.intervalFromdate = value;
- }
-
- /**
- * Gets the value of the intervalTodate property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getIntervalTodate() {
- return intervalTodate;
- }
-
- /**
- * Sets the value of the intervalTodate property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setIntervalTodate(String value) {
- this.intervalTodate = value;
- }
-
- /**
- * Gets the value of the intervalLabel property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getIntervalLabel() {
- return intervalLabel;
- }
-
- /**
- * Sets the value of the intervalLabel property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setIntervalLabel(String value) {
- this.intervalLabel = value;
- }
-
- /**
- * Gets the value of the lastSeriesALineChart property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getLastSeriesALineChart() {
- return lastSeriesALineChart;
- }
-
- /**
- * Sets the value of the lastSeriesALineChart property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setLastSeriesALineChart(String value) {
- this.lastSeriesALineChart = value;
- }
-
- /**
- * Gets the value of the lastSeriesABarChart property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getLastSeriesABarChart() {
- return lastSeriesABarChart;
- }
-
- /**
- * Sets the value of the lastSeriesABarChart property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setLastSeriesABarChart(String value) {
- this.lastSeriesABarChart = value;
- }
-
- /**
- * Gets the value of the maxLabelsInDomainAxis property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getMaxLabelsInDomainAxis() {
- return maxLabelsInDomainAxis;
- }
-
- /**
- * Sets the value of the maxLabelsInDomainAxis property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setMaxLabelsInDomainAxis(String value) {
- this.maxLabelsInDomainAxis = value;
- }
-
- /**
- * Gets the value of the linearRegression property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getLinearRegression() {
- return linearRegression;
- }
-
- /**
- * Sets the value of the linearRegression property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setLinearRegression(String value) {
- this.linearRegression = value;
- }
-
- /**
- * Gets the value of the linearRegressionColor property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getLinearRegressionColor() {
- return linearRegressionColor;
- }
-
- /**
- * Sets the value of the linearRegressionColor property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setLinearRegressionColor(String value) {
- this.linearRegressionColor = value;
- }
-
- /**
- * Gets the value of the exponentialRegressionColor property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getExponentialRegressionColor() {
- return exponentialRegressionColor;
- }
-
- /**
- * Sets the value of the exponentialRegressionColor property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setExponentialRegressionColor(String value) {
- this.exponentialRegressionColor = value;
- }
-
- /**
- * Gets the value of the maxRegression property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getMaxRegression() {
- return maxRegression;
- }
-
- /**
- * Sets the value of the maxRegression property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setMaxRegression(String value) {
- this.maxRegression = value;
- }
-
- /**
- * Gets the value of the rangeAxisUpperLimit property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getRangeAxisUpperLimit() {
- return rangeAxisUpperLimit;
- }
-
- /**
- * Sets the value of the rangeAxisUpperLimit property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setRangeAxisUpperLimit(String value) {
- this.rangeAxisUpperLimit = value;
- }
-
- /**
- * Gets the value of the rangeAxisLowerLimit property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getRangeAxisLowerLimit() {
- return rangeAxisLowerLimit;
- }
-
- /**
- * Sets the value of the rangeAxisLowerLimit property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setRangeAxisLowerLimit(String value) {
- this.rangeAxisLowerLimit = value;
- }
-
- /**
- * Gets the value of the overlayItemValueOnStackBar property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getOverlayItemValueOnStackBar() {
- return overlayItemValueOnStackBar;
- }
-
- /**
- * Sets the value of the overlayItemValueOnStackBar property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setOverlayItemValueOnStackBar(String value) {
- this.overlayItemValueOnStackBar = value;
- }
-
- /**
- * Gets the value of the animate property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isAnimate() {
- return animate;
- }
-
- /**
- * Sets the value of the animate property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setAnimate(Boolean value) {
- this.animate = value;
- }
-
- /**
- * Gets the value of the animateAnimatedChart property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isAnimateAnimatedChart() {
- return animateAnimatedChart;
- }
-
- /**
- * Sets the value of the animateAnimatedChart property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setAnimateAnimatedChart(Boolean value) {
- this.animateAnimatedChart = value;
- }
-
- /**
- * Gets the value of the keepDomainAxisValueAsString property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getKeepDomainAxisValueAsString() {
- return keepDomainAxisValueAsString;
- }
-
- /**
- * Sets the value of the keepDomainAxisValueAsString property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setKeepDomainAxisValueAsString(String value) {
- this.keepDomainAxisValueAsString = value;
- }
-
- /**
- * Gets the value of the stacked property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isStacked() {
- return stacked;
- }
-
- /**
- * Sets the value of the stacked property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setStacked(Boolean value) {
- this.stacked = value;
- }
-
- /**
- * Gets the value of the barControls property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isBarControls() {
- return barControls;
- }
-
- /**
- * Sets the value of the barControls property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setBarControls(Boolean value) {
- this.barControls = value;
- }
-
- /**
- * Gets the value of the xAxisDateType property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isXAxisDateType() {
- return xAxisDateType;
- }
-
- /**
- * Sets the value of the xAxisDateType property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setXAxisDateType(Boolean value) {
- this.xAxisDateType = value;
- }
-
- /**
- * Gets the value of the lessXaxisTickers property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isLessXaxisTickers() {
- return lessXaxisTickers;
- }
-
- /**
- * Sets the value of the lessXaxisTickers property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setLessXaxisTickers(Boolean value) {
- this.lessXaxisTickers = value;
- }
-
- /**
- * Gets the value of the timeAxis property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isTimeAxis() {
- return timeAxis;
- }
-
- /**
- * Sets the value of the timeAxis property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setTimeAxis(Boolean value) {
- this.timeAxis = value;
- }
-
- /**
- * Gets the value of the timeSeriesRender property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTimeSeriesRender() {
- return timeSeriesRender;
- }
-
- /**
- * Sets the value of the timeSeriesRender property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTimeSeriesRender(String value) {
- this.timeSeriesRender = value;
- }
-
- /**
- * Gets the value of the multiSeries property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isMultiSeries() {
- return multiSeries;
- }
-
- /**
- * Sets the value of the multiSeries property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setMultiSeries(Boolean value) {
- this.multiSeries = value;
- }
-
- /**
- * Gets the value of the showXAxisLabel property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isShowXAxisLabel() {
- return showXAxisLabel;
- }
-
- /**
- * Sets the value of the showXAxisLabel property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setShowXAxisLabel(Boolean value) {
- this.showXAxisLabel = value;
- }
-
- /**
- * Gets the value of the addXAxisTickers property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isAddXAxisTickers() {
- return addXAxisTickers;
- }
-
- /**
- * Sets the value of the addXAxisTickers property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setAddXAxisTickers(Boolean value) {
- this.addXAxisTickers = value;
- }
-
- /**
- * Gets the value of the zoomIn property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getZoomIn() {
- return zoomIn;
- }
-
- /**
- * Sets the value of the zoomIn property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setZoomIn(Integer value) {
- this.zoomIn = value;
- }
-
- /**
- * Gets the value of the timeAxisType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTimeAxisType() {
- return timeAxisType;
- }
-
- /**
- * Sets the value of the timeAxisType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTimeAxisType(String value) {
- this.timeAxisType = value;
- }
-
- /**
- * Gets the value of the logScale property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isLogScale() {
- return logScale;
- }
-
- /**
- * Sets the value of the logScale property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setLogScale(Boolean value) {
- this.logScale = value;
- }
-
- /**
- * Gets the value of the topMargin property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getTopMargin() {
- return topMargin;
- }
-
- /**
- * Sets the value of the topMargin property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setTopMargin(Integer value) {
- this.topMargin = value;
- }
-
- /**
- * Gets the value of the bottomMargin property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getBottomMargin() {
- return bottomMargin;
- }
-
- /**
- * Sets the value of the bottomMargin property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setBottomMargin(Integer value) {
- this.bottomMargin = value;
- }
-
- /**
- * Gets the value of the rightMargin property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getRightMargin() {
- return rightMargin;
- }
-
- /**
- * Sets the value of the rightMargin property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setRightMargin(Integer value) {
- this.rightMargin = value;
- }
-
- /**
- * Gets the value of the leftMargin property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getLeftMargin() {
- return leftMargin;
- }
-
- /**
- * Sets the value of the leftMargin property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setLeftMargin(Integer value) {
- this.leftMargin = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for ChartDrillFormfield complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="ChartDrillFormfield">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="formfield" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "ChartDrillFormfield", propOrder = {
- "formfield"
-})
-public class ChartDrillFormfield {
-
- protected String formfield;
-
- /**
- * Gets the value of the formfield property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getFormfield() {
- return formfield;
- }
-
- /**
- * Sets the value of the formfield property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setFormfield(String value) {
- this.formfield = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for ChartDrillOptions complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="ChartDrillOptions">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="drill_reportId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="drill_xAxis_FormField" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="drill_yAxis_FormField" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="drill_series_FormField" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="targetFormfield" type="{}ChartDrillFormfield" maxOccurs="unbounded" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "ChartDrillOptions", propOrder = {
- "drillReportId",
- "drillXAxisFormField",
- "drillYAxisFormField",
- "drillSeriesFormField",
- "targetFormfield"
-})
-public class ChartDrillOptions {
-
- @XmlElement(name = "drill_reportId")
- protected String drillReportId;
- @XmlElement(name = "drill_xAxis_FormField")
- protected String drillXAxisFormField;
- @XmlElement(name = "drill_yAxis_FormField")
- protected String drillYAxisFormField;
- @XmlElement(name = "drill_series_FormField")
- protected String drillSeriesFormField;
- protected List<ChartDrillFormfield> targetFormfield;
-
- /**
- * Gets the value of the drillReportId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDrillReportId() {
- return drillReportId;
- }
-
- /**
- * Sets the value of the drillReportId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDrillReportId(String value) {
- this.drillReportId = value;
- }
-
- /**
- * Gets the value of the drillXAxisFormField property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDrillXAxisFormField() {
- return drillXAxisFormField;
- }
-
- /**
- * Sets the value of the drillXAxisFormField property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDrillXAxisFormField(String value) {
- this.drillXAxisFormField = value;
- }
-
- /**
- * Gets the value of the drillYAxisFormField property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDrillYAxisFormField() {
- return drillYAxisFormField;
- }
-
- /**
- * Sets the value of the drillYAxisFormField property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDrillYAxisFormField(String value) {
- this.drillYAxisFormField = value;
- }
-
- /**
- * Gets the value of the drillSeriesFormField property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDrillSeriesFormField() {
- return drillSeriesFormField;
- }
-
- /**
- * Sets the value of the drillSeriesFormField property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDrillSeriesFormField(String value) {
- this.drillSeriesFormField = value;
- }
-
- /**
- * Gets the value of the targetFormfield property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the targetFormfield property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getTargetFormfield().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link ChartDrillFormfield }
- *
- *
- */
- public List<ChartDrillFormfield> getTargetFormfield() {
- if (targetFormfield == null) {
- targetFormfield = new ArrayList<ChartDrillFormfield>();
- }
- return this.targetFormfield;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for ColFilterList complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="ColFilterList">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="colFilter" type="{}ColFilterType" maxOccurs="unbounded" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "ColFilterList", propOrder = {
- "colFilter"
-})
-public class ColFilterList {
-
- protected List<ColFilterType> colFilter;
-
- /**
- * Gets the value of the colFilter property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the colFilter property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getColFilter().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link ColFilterType }
- *
- *
- */
- public List<ColFilterType> getColFilter() {
- if (colFilter == null) {
- colFilter = new ArrayList<ColFilterType>();
- }
- return this.colFilter;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for ColFilterType complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="ColFilterType">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="colId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="filterSeq" type="{http://www.w3.org/2001/XMLSchema}int"/>
- * <element name="joinCondition" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="openBrackets" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="expression" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="argType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="argValue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="closeBrackets" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element ref="{}comment" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "ColFilterType", propOrder = {
- "colId",
- "filterSeq",
- "joinCondition",
- "openBrackets",
- "expression",
- "argType",
- "argValue",
- "closeBrackets",
- "comment"
-})
-public class ColFilterType {
-
- @XmlElement(required = true)
- protected String colId;
- protected int filterSeq;
- @XmlElement(required = true)
- protected String joinCondition;
- protected String openBrackets;
- @XmlElement(required = true)
- protected String expression;
- protected String argType;
- protected String argValue;
- protected String closeBrackets;
- protected String comment;
-
- /**
- * Gets the value of the colId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getColId() {
- return colId;
- }
-
- /**
- * Sets the value of the colId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setColId(String value) {
- this.colId = value;
- }
-
- /**
- * Gets the value of the filterSeq property.
- *
- */
- public int getFilterSeq() {
- return filterSeq;
- }
-
- /**
- * Sets the value of the filterSeq property.
- *
- */
- public void setFilterSeq(int value) {
- this.filterSeq = value;
- }
-
- /**
- * Gets the value of the joinCondition property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getJoinCondition() {
- return joinCondition;
- }
-
- /**
- * Sets the value of the joinCondition property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setJoinCondition(String value) {
- this.joinCondition = value;
- }
-
- /**
- * Gets the value of the openBrackets property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getOpenBrackets() {
- return openBrackets;
- }
-
- /**
- * Sets the value of the openBrackets property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setOpenBrackets(String value) {
- this.openBrackets = value;
- }
-
- /**
- * Gets the value of the expression property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getExpression() {
- return expression;
- }
-
- /**
- * Sets the value of the expression property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setExpression(String value) {
- this.expression = value;
- }
-
- /**
- * Gets the value of the argType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getArgType() {
- return argType;
- }
-
- /**
- * Sets the value of the argType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setArgType(String value) {
- this.argType = value;
- }
-
- /**
- * Gets the value of the argValue property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getArgValue() {
- return argValue;
- }
-
- /**
- * Sets the value of the argValue property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setArgValue(String value) {
- this.argValue = value;
- }
-
- /**
- * Gets the value of the closeBrackets property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getCloseBrackets() {
- return closeBrackets;
- }
-
- /**
- * Sets the value of the closeBrackets property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setCloseBrackets(String value) {
- this.closeBrackets = value;
- }
-
- /**
- * Gets the value of the comment property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getComment() {
- return comment;
- }
-
- /**
- * Sets the value of the comment property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setComment(String value) {
- this.comment = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlSchemaType;
-import javax.xml.bind.annotation.XmlType;
-import javax.xml.datatype.XMLGregorianCalendar;
-
-
-/**
- * <p>Java class for CustomReportType complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="CustomReportType">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="reportName" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="reportDescr" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="numDashCols" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="dashboardLayoutHTML" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="dbInfo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="dbType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartType" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="chartTypeFixed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartMultiSeries" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartLeftAxisLabel" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartRightAxisLabel" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartWidth" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartHeight" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="showChartTitle" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
- * <element name="public" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
- * <element name="hideFormFieldAfterRun" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="createId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="createDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
- * <element name="reportSQL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="reportTitle" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="reportSubTitle" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="reportHeader" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="frozenColumns" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="pdfImgLogo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="emptyMessage" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="widthNoColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="dataGridAlign" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="reportFooter" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="numFormCols" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="displayOptions" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="jumpTo" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="searchPageSize" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="navPosition" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="toggleLayout" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="pageNav" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="showPageSize" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="showNavPos" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="showGotoOption" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="dataContainerHeight" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="dataContainerWidth" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="allowSchedule" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="multiGroupColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="topDown" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="sizedByContent" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element ref="{}comment" minOccurs="0"/>
- * <element name="dataSourceList" type="{}DataSourceList" minOccurs="0"/>
- * <element name="formFieldList" type="{}FormFieldList" minOccurs="0"/>
- * <element name="javascriptList" type="{}JavascriptList" minOccurs="0"/>
- * <element name="semaphoreList" type="{}SemaphoreList" minOccurs="0"/>
- * <element name="dashboardOptions" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="dashboardType" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="reportInNewWindow" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="displayFolderTree" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="maxRowsInExcelDownload" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="dashBoardReports" type="{}DashboardReports" minOccurs="0"/>
- * <element name="dashBoardReportsNew" type="{}DashboardReportsNew" minOccurs="0"/>
- * <element name="chartAdditionalOptions" type="{}ChartAdditionalOptions" minOccurs="0"/>
- * <element name="pdfAdditionalOptions" type="{}PDFAdditionalOptions" minOccurs="0"/>
- * <element name="chartDrillOptions" type="{}ChartDrillOptions" minOccurs="0"/>
- * <element name="dataminingOptions" type="{}DataminingOptions" minOccurs="0"/>
- * <element name="javascriptElement" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="folderId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="drillURLInPoPUpPresent" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="isOneTimeScheduleAllowed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="isHourlyScheduleAllowed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="isDailyScheduleAllowed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="isDailyMFScheduleAllowed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="isWeeklyScheduleAllowed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="isMonthlyScheduleAllowed" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="reportMap" type="{}ReportMap" minOccurs="0"/>
- * </sequence>
- * <attribute name="pageSize" type="{http://www.w3.org/2001/XMLSchema}int" />
- * <attribute name="reportType" type="{http://www.w3.org/2001/XMLSchema}string" />
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "CustomReportType", propOrder = {
- "reportName",
- "reportDescr",
- "numDashCols",
- "dashboardLayoutHTML",
- "dbInfo",
- "dbType",
- "chartType",
- "chartTypeFixed",
- "chartMultiSeries",
- "chartLeftAxisLabel",
- "chartRightAxisLabel",
- "chartWidth",
- "chartHeight",
- "showChartTitle",
- "_public",
- "hideFormFieldAfterRun",
- "createId",
- "createDate",
- "reportSQL",
- "reportTitle",
- "reportSubTitle",
- "reportHeader",
- "frozenColumns",
- "pdfImgLogo",
- "emptyMessage",
- "widthNoColumn",
- "dataGridAlign",
- "reportFooter",
- "numFormCols",
- "displayOptions",
- "jumpTo",
- "searchPageSize",
- "navPosition",
- "toggleLayout",
- "pageNav",
- "showPageSize",
- "showNavPos",
- "showGotoOption",
- "dataContainerHeight",
- "dataContainerWidth",
- "allowSchedule",
- "multiGroupColumn",
- "topDown",
- "sizedByContent",
- "comment",
- "dataSourceList",
- "formFieldList",
- "javascriptList",
- "semaphoreList",
- "dashboardOptions",
- "dashboardType",
- "reportInNewWindow",
- "displayFolderTree",
- "maxRowsInExcelDownload",
- "dashBoardReports",
- "dashBoardReportsNew",
- "chartAdditionalOptions",
- "pdfAdditionalOptions",
- "chartDrillOptions",
- "dataminingOptions",
- "javascriptElement",
- "folderId",
- "drillURLInPoPUpPresent",
- "isOneTimeScheduleAllowed",
- "isHourlyScheduleAllowed",
- "isDailyScheduleAllowed",
- "isDailyMFScheduleAllowed",
- "isWeeklyScheduleAllowed",
- "isMonthlyScheduleAllowed",
- "reportMap"
-})
-public class CustomReportType {
-
- @XmlElement(required = true)
- protected String reportName;
- @XmlElement(required = true)
- protected String reportDescr;
- protected String numDashCols;
- protected String dashboardLayoutHTML;
- protected String dbInfo;
- protected String dbType;
- @XmlElement(required = true)
- protected String chartType;
- protected String chartTypeFixed;
- protected String chartMultiSeries;
- protected String chartLeftAxisLabel;
- protected String chartRightAxisLabel;
- protected String chartWidth;
- protected String chartHeight;
- @XmlElement(defaultValue = "false")
- protected boolean showChartTitle;
- @XmlElement(name = "public", defaultValue = "false")
- protected boolean _public;
- @XmlElement(defaultValue = "false")
- protected Boolean hideFormFieldAfterRun;
- @XmlElement(required = true)
- protected String createId;
- @XmlElement(required = true)
- @XmlSchemaType(name = "date")
- protected XMLGregorianCalendar createDate;
- protected String reportSQL;
- protected String reportTitle;
- protected String reportSubTitle;
- protected String reportHeader;
- @XmlElement(defaultValue = "0")
- protected Integer frozenColumns;
- protected String pdfImgLogo;
- protected String emptyMessage;
- protected String widthNoColumn;
- protected String dataGridAlign;
- protected String reportFooter;
- protected String numFormCols;
- protected String displayOptions;
- protected Integer jumpTo;
- protected Integer searchPageSize;
- protected String navPosition;
- @XmlElement(defaultValue = "true")
- protected Boolean toggleLayout;
- @XmlElement(defaultValue = "true")
- protected Boolean pageNav;
- @XmlElement(defaultValue = "true")
- protected Boolean showPageSize;
- @XmlElement(defaultValue = "true")
- protected Boolean showNavPos;
- @XmlElement(defaultValue = "true")
- protected Boolean showGotoOption;
- protected String dataContainerHeight;
- protected String dataContainerWidth;
- protected String allowSchedule;
- protected String multiGroupColumn;
- protected String topDown;
- protected String sizedByContent;
- protected String comment;
- protected DataSourceList dataSourceList;
- protected FormFieldList formFieldList;
- protected JavascriptList javascriptList;
- protected SemaphoreList semaphoreList;
- protected String dashboardOptions;
- @XmlElement(defaultValue = "false")
- protected Boolean dashboardType;
- @XmlElement(defaultValue = "false")
- protected Boolean reportInNewWindow;
- @XmlElement(defaultValue = "false")
- protected Boolean displayFolderTree;
- protected Integer maxRowsInExcelDownload;
- protected DashboardReports dashBoardReports;
- protected DashboardReportsNew dashBoardReportsNew;
- protected ChartAdditionalOptions chartAdditionalOptions;
- protected PDFAdditionalOptions pdfAdditionalOptions;
- protected ChartDrillOptions chartDrillOptions;
- protected DataminingOptions dataminingOptions;
- protected String javascriptElement;
- @XmlElement(defaultValue = "0")
- protected String folderId;
- @XmlElement(defaultValue = "false")
- protected Boolean drillURLInPoPUpPresent;
- protected String isOneTimeScheduleAllowed;
- protected String isHourlyScheduleAllowed;
- protected String isDailyScheduleAllowed;
- protected String isDailyMFScheduleAllowed;
- protected String isWeeklyScheduleAllowed;
- protected String isMonthlyScheduleAllowed;
- protected ReportMap reportMap;
- @XmlAttribute(name = "pageSize")
- protected Integer pageSize;
- @XmlAttribute(name = "reportType")
- protected String reportType;
-
- /**
- * Gets the value of the reportName property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getReportName() {
- return reportName;
- }
-
- /**
- * Sets the value of the reportName property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setReportName(String value) {
- this.reportName = value;
- }
-
- /**
- * Gets the value of the reportDescr property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getReportDescr() {
- return reportDescr;
- }
-
- /**
- * Sets the value of the reportDescr property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setReportDescr(String value) {
- this.reportDescr = value;
- }
-
- /**
- * Gets the value of the numDashCols property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getNumDashCols() {
- return numDashCols;
- }
-
- /**
- * Sets the value of the numDashCols property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setNumDashCols(String value) {
- this.numDashCols = value;
- }
-
- /**
- * Gets the value of the dashboardLayoutHTML property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDashboardLayoutHTML() {
- return dashboardLayoutHTML;
- }
-
- /**
- * Sets the value of the dashboardLayoutHTML property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDashboardLayoutHTML(String value) {
- this.dashboardLayoutHTML = value;
- }
-
- /**
- * Gets the value of the dbInfo property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDbInfo() {
- return dbInfo;
- }
-
- /**
- * Sets the value of the dbInfo property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDbInfo(String value) {
- this.dbInfo = value;
- }
-
- /**
- * Gets the value of the dbType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDbType() {
- return dbType;
- }
-
- /**
- * Sets the value of the dbType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDbType(String value) {
- this.dbType = value;
- }
-
- /**
- * Gets the value of the chartType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartType() {
- return chartType;
- }
-
- /**
- * Sets the value of the chartType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartType(String value) {
- this.chartType = value;
- }
-
- /**
- * Gets the value of the chartTypeFixed property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartTypeFixed() {
- return chartTypeFixed;
- }
-
- /**
- * Sets the value of the chartTypeFixed property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartTypeFixed(String value) {
- this.chartTypeFixed = value;
- }
-
- /**
- * Gets the value of the chartMultiSeries property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartMultiSeries() {
- return chartMultiSeries;
- }
-
- /**
- * Sets the value of the chartMultiSeries property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartMultiSeries(String value) {
- this.chartMultiSeries = value;
- }
-
- /**
- * Gets the value of the chartLeftAxisLabel property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartLeftAxisLabel() {
- return chartLeftAxisLabel;
- }
-
- /**
- * Sets the value of the chartLeftAxisLabel property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartLeftAxisLabel(String value) {
- this.chartLeftAxisLabel = value;
- }
-
- /**
- * Gets the value of the chartRightAxisLabel property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartRightAxisLabel() {
- return chartRightAxisLabel;
- }
-
- /**
- * Sets the value of the chartRightAxisLabel property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartRightAxisLabel(String value) {
- this.chartRightAxisLabel = value;
- }
-
- /**
- * Gets the value of the chartWidth property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartWidth() {
- return chartWidth;
- }
-
- /**
- * Sets the value of the chartWidth property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartWidth(String value) {
- this.chartWidth = value;
- }
-
- /**
- * Gets the value of the chartHeight property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartHeight() {
- return chartHeight;
- }
-
- /**
- * Sets the value of the chartHeight property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartHeight(String value) {
- this.chartHeight = value;
- }
-
- /**
- * Gets the value of the showChartTitle property.
- *
- */
- public boolean isShowChartTitle() {
- return showChartTitle;
- }
-
- /**
- * Sets the value of the showChartTitle property.
- *
- */
- public void setShowChartTitle(boolean value) {
- this.showChartTitle = value;
- }
-
- /**
- * Gets the value of the public property.
- *
- */
- public boolean isPublic() {
- return _public;
- }
-
- /**
- * Sets the value of the public property.
- *
- */
- public void setPublic(boolean value) {
- this._public = value;
- }
-
- /**
- * Gets the value of the hideFormFieldAfterRun property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isHideFormFieldAfterRun() {
- return hideFormFieldAfterRun;
- }
-
- /**
- * Sets the value of the hideFormFieldAfterRun property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setHideFormFieldAfterRun(Boolean value) {
- this.hideFormFieldAfterRun = value;
- }
-
- /**
- * Gets the value of the createId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getCreateId() {
- return createId;
- }
-
- /**
- * Sets the value of the createId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setCreateId(String value) {
- this.createId = value;
- }
-
- /**
- * Gets the value of the createDate property.
- *
- * @return
- * possible object is
- * {@link XMLGregorianCalendar }
- *
- */
- public XMLGregorianCalendar getCreateDate() {
- return createDate;
- }
-
- /**
- * Sets the value of the createDate property.
- *
- * @param value
- * allowed object is
- * {@link XMLGregorianCalendar }
- *
- */
- public void setCreateDate(XMLGregorianCalendar value) {
- this.createDate = value;
- }
-
- /**
- * Gets the value of the reportSQL property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getReportSQL() {
- return reportSQL;
- }
-
- /**
- * Sets the value of the reportSQL property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setReportSQL(String value) {
- this.reportSQL = value;
- }
-
- /**
- * Gets the value of the reportTitle property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getReportTitle() {
- return reportTitle;
- }
-
- /**
- * Sets the value of the reportTitle property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setReportTitle(String value) {
- this.reportTitle = value;
- }
-
- /**
- * Gets the value of the reportSubTitle property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getReportSubTitle() {
- return reportSubTitle;
- }
-
- /**
- * Sets the value of the reportSubTitle property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setReportSubTitle(String value) {
- this.reportSubTitle = value;
- }
-
- /**
- * Gets the value of the reportHeader property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getReportHeader() {
- return reportHeader;
- }
-
- /**
- * Sets the value of the reportHeader property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setReportHeader(String value) {
- this.reportHeader = value;
- }
-
- /**
- * Gets the value of the frozenColumns property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getFrozenColumns() {
- return frozenColumns;
- }
-
- /**
- * Sets the value of the frozenColumns property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setFrozenColumns(Integer value) {
- this.frozenColumns = value;
- }
-
- /**
- * Gets the value of the pdfImgLogo property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getPdfImgLogo() {
- return pdfImgLogo;
- }
-
- /**
- * Sets the value of the pdfImgLogo property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setPdfImgLogo(String value) {
- this.pdfImgLogo = value;
- }
-
- /**
- * Gets the value of the emptyMessage property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getEmptyMessage() {
- return emptyMessage;
- }
-
- /**
- * Sets the value of the emptyMessage property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setEmptyMessage(String value) {
- this.emptyMessage = value;
- }
-
- /**
- * Gets the value of the widthNoColumn property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getWidthNoColumn() {
- return widthNoColumn;
- }
-
- /**
- * Sets the value of the widthNoColumn property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setWidthNoColumn(String value) {
- this.widthNoColumn = value;
- }
-
- /**
- * Gets the value of the dataGridAlign property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDataGridAlign() {
- return dataGridAlign;
- }
-
- /**
- * Sets the value of the dataGridAlign property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDataGridAlign(String value) {
- this.dataGridAlign = value;
- }
-
- /**
- * Gets the value of the reportFooter property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getReportFooter() {
- return reportFooter;
- }
-
- /**
- * Sets the value of the reportFooter property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setReportFooter(String value) {
- this.reportFooter = value;
- }
-
- /**
- * Gets the value of the numFormCols property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getNumFormCols() {
- return numFormCols;
- }
-
- /**
- * Sets the value of the numFormCols property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setNumFormCols(String value) {
- this.numFormCols = value;
- }
-
- /**
- * Gets the value of the displayOptions property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDisplayOptions() {
- return displayOptions;
- }
-
- /**
- * Sets the value of the displayOptions property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDisplayOptions(String value) {
- this.displayOptions = value;
- }
-
- /**
- * Gets the value of the jumpTo property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getJumpTo() {
- return jumpTo;
- }
-
- /**
- * Sets the value of the jumpTo property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setJumpTo(Integer value) {
- this.jumpTo = value;
- }
-
- /**
- * Gets the value of the searchPageSize property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getSearchPageSize() {
- return searchPageSize;
- }
-
- /**
- * Sets the value of the searchPageSize property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setSearchPageSize(Integer value) {
- this.searchPageSize = value;
- }
-
- /**
- * Gets the value of the navPosition property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getNavPosition() {
- return navPosition;
- }
-
- /**
- * Sets the value of the navPosition property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setNavPosition(String value) {
- this.navPosition = value;
- }
-
- /**
- * Gets the value of the toggleLayout property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isToggleLayout() {
- return toggleLayout;
- }
-
- /**
- * Sets the value of the toggleLayout property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setToggleLayout(Boolean value) {
- this.toggleLayout = value;
- }
-
- /**
- * Gets the value of the pageNav property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isPageNav() {
- return pageNav;
- }
-
- /**
- * Sets the value of the pageNav property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setPageNav(Boolean value) {
- this.pageNav = value;
- }
-
- /**
- * Gets the value of the showPageSize property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isShowPageSize() {
- return showPageSize;
- }
-
- /**
- * Sets the value of the showPageSize property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setShowPageSize(Boolean value) {
- this.showPageSize = value;
- }
-
- /**
- * Gets the value of the showNavPos property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isShowNavPos() {
- return showNavPos;
- }
-
- /**
- * Sets the value of the showNavPos property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setShowNavPos(Boolean value) {
- this.showNavPos = value;
- }
-
- /**
- * Gets the value of the showGotoOption property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isShowGotoOption() {
- return showGotoOption;
- }
-
- /**
- * Sets the value of the showGotoOption property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setShowGotoOption(Boolean value) {
- this.showGotoOption = value;
- }
-
- /**
- * Gets the value of the dataContainerHeight property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDataContainerHeight() {
- return dataContainerHeight;
- }
-
- /**
- * Sets the value of the dataContainerHeight property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDataContainerHeight(String value) {
- this.dataContainerHeight = value;
- }
-
- /**
- * Gets the value of the dataContainerWidth property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDataContainerWidth() {
- return dataContainerWidth;
- }
-
- /**
- * Sets the value of the dataContainerWidth property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDataContainerWidth(String value) {
- this.dataContainerWidth = value;
- }
-
- /**
- * Gets the value of the allowSchedule property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getAllowSchedule() {
- return allowSchedule;
- }
-
- /**
- * Sets the value of the allowSchedule property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setAllowSchedule(String value) {
- this.allowSchedule = value;
- }
-
- /**
- * Gets the value of the multiGroupColumn property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getMultiGroupColumn() {
- return multiGroupColumn;
- }
-
- /**
- * Sets the value of the multiGroupColumn property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setMultiGroupColumn(String value) {
- this.multiGroupColumn = value;
- }
-
- /**
- * Gets the value of the topDown property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTopDown() {
- return topDown;
- }
-
- /**
- * Sets the value of the topDown property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTopDown(String value) {
- this.topDown = value;
- }
-
- /**
- * Gets the value of the sizedByContent property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getSizedByContent() {
- return sizedByContent;
- }
-
- /**
- * Sets the value of the sizedByContent property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setSizedByContent(String value) {
- this.sizedByContent = value;
- }
-
- /**
- * Gets the value of the comment property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getComment() {
- return comment;
- }
-
- /**
- * Sets the value of the comment property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setComment(String value) {
- this.comment = value;
- }
-
- /**
- * Gets the value of the dataSourceList property.
- *
- * @return
- * possible object is
- * {@link DataSourceList }
- *
- */
- public DataSourceList getDataSourceList() {
- return dataSourceList;
- }
-
- /**
- * Sets the value of the dataSourceList property.
- *
- * @param value
- * allowed object is
- * {@link DataSourceList }
- *
- */
- public void setDataSourceList(DataSourceList value) {
- this.dataSourceList = value;
- }
-
- /**
- * Gets the value of the formFieldList property.
- *
- * @return
- * possible object is
- * {@link FormFieldList }
- *
- */
- public FormFieldList getFormFieldList() {
- return formFieldList;
- }
-
- /**
- * Sets the value of the formFieldList property.
- *
- * @param value
- * allowed object is
- * {@link FormFieldList }
- *
- */
- public void setFormFieldList(FormFieldList value) {
- this.formFieldList = value;
- }
-
- /**
- * Gets the value of the javascriptList property.
- *
- * @return
- * possible object is
- * {@link JavascriptList }
- *
- */
- public JavascriptList getJavascriptList() {
- return javascriptList;
- }
-
- /**
- * Sets the value of the javascriptList property.
- *
- * @param value
- * allowed object is
- * {@link JavascriptList }
- *
- */
- public void setJavascriptList(JavascriptList value) {
- this.javascriptList = value;
- }
-
- /**
- * Gets the value of the semaphoreList property.
- *
- * @return
- * possible object is
- * {@link SemaphoreList }
- *
- */
- public SemaphoreList getSemaphoreList() {
- return semaphoreList;
- }
-
- /**
- * Sets the value of the semaphoreList property.
- *
- * @param value
- * allowed object is
- * {@link SemaphoreList }
- *
- */
- public void setSemaphoreList(SemaphoreList value) {
- this.semaphoreList = value;
- }
-
- /**
- * Gets the value of the dashboardOptions property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDashboardOptions() {
- return dashboardOptions;
- }
-
- /**
- * Sets the value of the dashboardOptions property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDashboardOptions(String value) {
- this.dashboardOptions = value;
- }
-
- /**
- * Gets the value of the dashboardType property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isDashboardType() {
- return dashboardType;
- }
-
- /**
- * Sets the value of the dashboardType property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setDashboardType(Boolean value) {
- this.dashboardType = value;
- }
-
- /**
- * Gets the value of the reportInNewWindow property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isReportInNewWindow() {
- return reportInNewWindow;
- }
-
- /**
- * Sets the value of the reportInNewWindow property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setReportInNewWindow(Boolean value) {
- this.reportInNewWindow = value;
- }
-
- /**
- * Gets the value of the displayFolderTree property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isDisplayFolderTree() {
- return displayFolderTree;
- }
-
- /**
- * Sets the value of the displayFolderTree property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setDisplayFolderTree(Boolean value) {
- this.displayFolderTree = value;
- }
-
- /**
- * Gets the value of the maxRowsInExcelDownload property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getMaxRowsInExcelDownload() {
- return maxRowsInExcelDownload;
- }
-
- /**
- * Sets the value of the maxRowsInExcelDownload property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setMaxRowsInExcelDownload(Integer value) {
- this.maxRowsInExcelDownload = value;
- }
-
- /**
- * Gets the value of the dashBoardReports property.
- *
- * @return
- * possible object is
- * {@link DashboardReports }
- *
- */
- public DashboardReports getDashBoardReports() {
- return dashBoardReports;
- }
-
- /**
- * Sets the value of the dashBoardReports property.
- *
- * @param value
- * allowed object is
- * {@link DashboardReports }
- *
- */
- public void setDashBoardReports(DashboardReports value) {
- this.dashBoardReports = value;
- }
-
- /**
- * Gets the value of the dashBoardReportsNew property.
- *
- * @return
- * possible object is
- * {@link DashboardReportsNew }
- *
- */
- public DashboardReportsNew getDashBoardReportsNew() {
- return dashBoardReportsNew;
- }
-
- /**
- * Sets the value of the dashBoardReportsNew property.
- *
- * @param value
- * allowed object is
- * {@link DashboardReportsNew }
- *
- */
- public void setDashBoardReportsNew(DashboardReportsNew value) {
- this.dashBoardReportsNew = value;
- }
-
- /**
- * Gets the value of the chartAdditionalOptions property.
- *
- * @return
- * possible object is
- * {@link ChartAdditionalOptions }
- *
- */
- public ChartAdditionalOptions getChartAdditionalOptions() {
- return chartAdditionalOptions;
- }
-
- /**
- * Sets the value of the chartAdditionalOptions property.
- *
- * @param value
- * allowed object is
- * {@link ChartAdditionalOptions }
- *
- */
- public void setChartAdditionalOptions(ChartAdditionalOptions value) {
- this.chartAdditionalOptions = value;
- }
-
- /**
- * Gets the value of the pdfAdditionalOptions property.
- *
- * @return
- * possible object is
- * {@link PDFAdditionalOptions }
- *
- */
- public PDFAdditionalOptions getPdfAdditionalOptions() {
- return pdfAdditionalOptions;
- }
-
- /**
- * Sets the value of the pdfAdditionalOptions property.
- *
- * @param value
- * allowed object is
- * {@link PDFAdditionalOptions }
- *
- */
- public void setPdfAdditionalOptions(PDFAdditionalOptions value) {
- this.pdfAdditionalOptions = value;
- }
-
- /**
- * Gets the value of the chartDrillOptions property.
- *
- * @return
- * possible object is
- * {@link ChartDrillOptions }
- *
- */
- public ChartDrillOptions getChartDrillOptions() {
- return chartDrillOptions;
- }
-
- /**
- * Sets the value of the chartDrillOptions property.
- *
- * @param value
- * allowed object is
- * {@link ChartDrillOptions }
- *
- */
- public void setChartDrillOptions(ChartDrillOptions value) {
- this.chartDrillOptions = value;
- }
-
- /**
- * Gets the value of the dataminingOptions property.
- *
- * @return
- * possible object is
- * {@link DataminingOptions }
- *
- */
- public DataminingOptions getDataminingOptions() {
- return dataminingOptions;
- }
-
- /**
- * Sets the value of the dataminingOptions property.
- *
- * @param value
- * allowed object is
- * {@link DataminingOptions }
- *
- */
- public void setDataminingOptions(DataminingOptions value) {
- this.dataminingOptions = value;
- }
-
- /**
- * Gets the value of the javascriptElement property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getJavascriptElement() {
- return javascriptElement;
- }
-
- /**
- * Sets the value of the javascriptElement property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setJavascriptElement(String value) {
- this.javascriptElement = value;
- }
-
- /**
- * Gets the value of the folderId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getFolderId() {
- return folderId;
- }
-
- /**
- * Sets the value of the folderId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setFolderId(String value) {
- this.folderId = value;
- }
-
- /**
- * Gets the value of the drillURLInPoPUpPresent property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isDrillURLInPoPUpPresent() {
- return drillURLInPoPUpPresent;
- }
-
- /**
- * Sets the value of the drillURLInPoPUpPresent property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setDrillURLInPoPUpPresent(Boolean value) {
- this.drillURLInPoPUpPresent = value;
- }
-
- /**
- * Gets the value of the isOneTimeScheduleAllowed property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getIsOneTimeScheduleAllowed() {
- return isOneTimeScheduleAllowed;
- }
-
- /**
- * Sets the value of the isOneTimeScheduleAllowed property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setIsOneTimeScheduleAllowed(String value) {
- this.isOneTimeScheduleAllowed = value;
- }
-
- /**
- * Gets the value of the isHourlyScheduleAllowed property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getIsHourlyScheduleAllowed() {
- return isHourlyScheduleAllowed;
- }
-
- /**
- * Sets the value of the isHourlyScheduleAllowed property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setIsHourlyScheduleAllowed(String value) {
- this.isHourlyScheduleAllowed = value;
- }
-
- /**
- * Gets the value of the isDailyScheduleAllowed property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getIsDailyScheduleAllowed() {
- return isDailyScheduleAllowed;
- }
-
- /**
- * Sets the value of the isDailyScheduleAllowed property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setIsDailyScheduleAllowed(String value) {
- this.isDailyScheduleAllowed = value;
- }
-
- /**
- * Gets the value of the isDailyMFScheduleAllowed property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getIsDailyMFScheduleAllowed() {
- return isDailyMFScheduleAllowed;
- }
-
- /**
- * Sets the value of the isDailyMFScheduleAllowed property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setIsDailyMFScheduleAllowed(String value) {
- this.isDailyMFScheduleAllowed = value;
- }
-
- /**
- * Gets the value of the isWeeklyScheduleAllowed property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getIsWeeklyScheduleAllowed() {
- return isWeeklyScheduleAllowed;
- }
-
- /**
- * Sets the value of the isWeeklyScheduleAllowed property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setIsWeeklyScheduleAllowed(String value) {
- this.isWeeklyScheduleAllowed = value;
- }
-
- /**
- * Gets the value of the isMonthlyScheduleAllowed property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getIsMonthlyScheduleAllowed() {
- return isMonthlyScheduleAllowed;
- }
-
- /**
- * Sets the value of the isMonthlyScheduleAllowed property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setIsMonthlyScheduleAllowed(String value) {
- this.isMonthlyScheduleAllowed = value;
- }
-
- /**
- * Gets the value of the reportMap property.
- *
- * @return
- * possible object is
- * {@link ReportMap }
- *
- */
- public ReportMap getReportMap() {
- return reportMap;
- }
-
- /**
- * Sets the value of the reportMap property.
- *
- * @param value
- * allowed object is
- * {@link ReportMap }
- *
- */
- public void setReportMap(ReportMap value) {
- this.reportMap = value;
- }
-
- /**
- * Gets the value of the pageSize property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getPageSize() {
- return pageSize;
- }
-
- /**
- * Sets the value of the pageSize property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setPageSize(Integer value) {
- this.pageSize = value;
- }
-
- /**
- * Gets the value of the reportType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getReportType() {
- return reportType;
- }
-
- /**
- * Sets the value of the reportType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setReportType(String value) {
- this.reportType = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for DashboardEditorList complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="DashboardEditorList">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="editorList" type="{}DashboardEditorReport" maxOccurs="unbounded" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "DashboardEditorList", propOrder = {
- "editorList"
-})
-public class DashboardEditorList {
-
- protected List<DashboardEditorReport> editorList;
-
- /**
- * Gets the value of the editorList property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the editorList property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getEditorList().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link DashboardEditorReport }
- *
- *
- */
- public List<DashboardEditorReport> getEditorList() {
- if (editorList == null) {
- editorList = new ArrayList<DashboardEditorReport>();
- }
- return this.editorList;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for DashboardEditorReport complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="DashboardEditorReport">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="reportId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="reportName" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="dataType" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="position" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "DashboardEditorReport", propOrder = {
- "reportId",
- "reportName",
- "dataType",
- "position"
-})
-public class DashboardEditorReport {
-
- @XmlElement(required = true)
- protected String reportId;
- @XmlElement(required = true)
- protected String reportName;
- @XmlElement(required = true)
- protected String dataType;
- @XmlElement(required = true)
- protected String position;
-
- /**
- * Gets the value of the reportId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getReportId() {
- return reportId;
- }
-
- /**
- * Sets the value of the reportId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setReportId(String value) {
- this.reportId = value;
- }
-
- /**
- * Gets the value of the reportName property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getReportName() {
- return reportName;
- }
-
- /**
- * Sets the value of the reportName property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setReportName(String value) {
- this.reportName = value;
- }
-
- /**
- * Gets the value of the dataType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDataType() {
- return dataType;
- }
-
- /**
- * Sets the value of the dataType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDataType(String value) {
- this.dataType = value;
- }
-
- /**
- * Gets the value of the position property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getPosition() {
- return position;
- }
-
- /**
- * Sets the value of the position property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setPosition(String value) {
- this.position = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for DashboardReports complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="DashboardReports">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="reportsList" type="{}Reports" maxOccurs="unbounded" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "DashboardReports", propOrder = {
- "reportsList"
-})
-public class DashboardReports {
-
- protected List<Reports> reportsList;
-
- /**
- * Gets the value of the reportsList property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the reportsList property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getReportsList().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link Reports }
- *
- *
- */
- public List<Reports> getReportsList() {
- if (reportsList == null) {
- reportsList = new ArrayList<Reports>();
- }
- return this.reportsList;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for DashboardReportsNew complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="DashboardReportsNew">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="reportsList" type="{}Reports" maxOccurs="unbounded" minOccurs="0"/>
- * <element name="dashboardEditor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="dashboardEditorList" type="{}DashboardEditorList" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "DashboardReportsNew", propOrder = {
- "reportsList",
- "dashboardEditor",
- "dashboardEditorList"
-})
-public class DashboardReportsNew {
-
- protected List<Reports> reportsList;
- protected String dashboardEditor;
- protected DashboardEditorList dashboardEditorList;
-
- /**
- * Gets the value of the reportsList property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the reportsList property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getReportsList().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link Reports }
- *
- *
- */
- public List<Reports> getReportsList() {
- if (reportsList == null) {
- reportsList = new ArrayList<Reports>();
- }
- return this.reportsList;
- }
-
- /**
- * Gets the value of the dashboardEditor property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDashboardEditor() {
- return dashboardEditor;
- }
-
- /**
- * Sets the value of the dashboardEditor property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDashboardEditor(String value) {
- this.dashboardEditor = value;
- }
-
- /**
- * Gets the value of the dashboardEditorList property.
- *
- * @return
- * possible object is
- * {@link DashboardEditorList }
- *
- */
- public DashboardEditorList getDashboardEditorList() {
- return dashboardEditorList;
- }
-
- /**
- * Sets the value of the dashboardEditorList property.
- *
- * @param value
- * allowed object is
- * {@link DashboardEditorList }
- *
- */
- public void setDashboardEditorList(DashboardEditorList value) {
- this.dashboardEditorList = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for DataColumnList complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="DataColumnList">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="dataColumn" type="{}DataColumnType" maxOccurs="unbounded"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "DataColumnList", propOrder = {
- "dataColumn"
-})
-public class DataColumnList {
-
- @XmlElement(required = true)
- protected List<DataColumnType> dataColumn;
-
- /**
- * Gets the value of the dataColumn property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the dataColumn property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getDataColumn().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link DataColumnType }
- *
- *
- */
- public List<DataColumnType> getDataColumn() {
- if (dataColumn == null) {
- dataColumn = new ArrayList<DataColumnType>();
- }
- return this.dataColumn;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for DataColumnType complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="DataColumnType">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="tableId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="dbColName" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="crossTabValue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="colName" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="displayName" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="displayWidth" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="displayWidthInPxls" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="pdfDisplayWidthInPxls" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="displayAlignment" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="displayHeaderAlignment" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="orderSeq" type="{http://www.w3.org/2001/XMLSchema}int"/>
- * <element name="visible" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
- * <element name="calculated" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
- * <element name="colType" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="hyperlinkURL" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="hyperlinkType" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="actionImg" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="groupByPos" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="subTotalCustomText" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="hideRepeatedKey" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="colFormat" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="groupBreak" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
- * <element name="orderBySeq" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="orderByAscDesc" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="displayTotal" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="colOnChart" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartSeq" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="chartColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartLineType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartSeries" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="isRangeAxisFilled" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="isSortable" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="createInNewChart" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="drillDownType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="drillinPoPUp" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="drillDownURL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="drillDownParams" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element ref="{}comment" minOccurs="0"/>
- * <element name="colFilterList" type="{}ColFilterList" minOccurs="0"/>
- * <element name="semaphoreId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="dbColType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="chartGroup" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="yAxis" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="dependsOnFormField" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="nowrap" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="indentation" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="enhancedPagination" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="level" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="start" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="colspan" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="dataMiningCol" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * </sequence>
- * <attribute name="colId" type="{http://www.w3.org/2001/XMLSchema}string" />
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "DataColumnType", propOrder = {
- "tableId",
- "dbColName",
- "crossTabValue",
- "colName",
- "displayName",
- "displayWidth",
- "displayWidthInPxls",
- "pdfDisplayWidthInPxls",
- "displayAlignment",
- "displayHeaderAlignment",
- "orderSeq",
- "visible",
- "calculated",
- "colType",
- "hyperlinkURL",
- "hyperlinkType",
- "actionImg",
- "groupByPos",
- "subTotalCustomText",
- "hideRepeatedKey",
- "colFormat",
- "groupBreak",
- "orderBySeq",
- "orderByAscDesc",
- "displayTotal",
- "colOnChart",
- "chartSeq",
- "chartColor",
- "chartLineType",
- "chartSeries",
- "isRangeAxisFilled",
- "isSortable",
- "createInNewChart",
- "drillDownType",
- "drillinPoPUp",
- "drillDownURL",
- "drillDownParams",
- "comment",
- "colFilterList",
- "semaphoreId",
- "dbColType",
- "chartGroup",
- "yAxis",
- "dependsOnFormField",
- "nowrap",
- "indentation",
- "enhancedPagination",
- "level",
- "start",
- "colspan",
- "dataMiningCol"
-})
-public class DataColumnType {
-
- @XmlElement(required = true)
- protected String tableId;
- @XmlElement(required = true)
- protected String dbColName;
- protected String crossTabValue;
- @XmlElement(required = true)
- protected String colName;
- @XmlElement(required = true)
- protected String displayName;
- protected Integer displayWidth;
- protected String displayWidthInPxls;
- protected String pdfDisplayWidthInPxls;
- protected String displayAlignment;
- protected String displayHeaderAlignment;
- protected int orderSeq;
- @XmlElement(defaultValue = "true")
- protected boolean visible;
- @XmlElement(defaultValue = "false")
- protected boolean calculated;
- @XmlElement(required = true)
- protected String colType;
- @XmlElement(required = true)
- protected String hyperlinkURL;
- @XmlElement(required = true)
- protected String hyperlinkType;
- @XmlElement(required = true)
- protected String actionImg;
- protected Integer groupByPos;
- protected String subTotalCustomText;
- @XmlElement(defaultValue = "false")
- protected Boolean hideRepeatedKey;
- protected String colFormat;
- @XmlElement(defaultValue = "false")
- protected boolean groupBreak;
- protected Integer orderBySeq;
- protected String orderByAscDesc;
- protected String displayTotal;
- protected String colOnChart;
- protected Integer chartSeq;
- protected String chartColor;
- protected String chartLineType;
- @XmlElement(defaultValue = "false")
- protected Boolean chartSeries;
- @XmlElement(defaultValue = "false")
- protected Boolean isRangeAxisFilled;
- @XmlElement(defaultValue = "false")
- protected Boolean isSortable;
- @XmlElement(defaultValue = "false")
- protected Boolean createInNewChart;
- protected String drillDownType;
- @XmlElement(defaultValue = "false")
- protected Boolean drillinPoPUp;
- protected String drillDownURL;
- protected String drillDownParams;
- protected String comment;
- protected ColFilterList colFilterList;
- protected String semaphoreId;
- protected String dbColType;
- protected String chartGroup;
- protected String yAxis;
- protected String dependsOnFormField;
- protected String nowrap;
- @XmlElement(defaultValue = "0")
- protected Integer indentation;
- @XmlElement(defaultValue = "false")
- protected Boolean enhancedPagination;
- @XmlElement(defaultValue = "0")
- protected Integer level;
- @XmlElement(defaultValue = "0")
- protected Integer start;
- @XmlElement(defaultValue = "0")
- protected Integer colspan;
- protected String dataMiningCol;
- @XmlAttribute(name = "colId")
- protected String colId;
-
- /**
- * Gets the value of the tableId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTableId() {
- return tableId;
- }
-
- /**
- * Sets the value of the tableId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTableId(String value) {
- this.tableId = value;
- }
-
- /**
- * Gets the value of the dbColName property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDbColName() {
- return dbColName;
- }
-
- /**
- * Sets the value of the dbColName property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDbColName(String value) {
- this.dbColName = value;
- }
-
- /**
- * Gets the value of the crossTabValue property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getCrossTabValue() {
- return crossTabValue;
- }
-
- /**
- * Sets the value of the crossTabValue property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setCrossTabValue(String value) {
- this.crossTabValue = value;
- }
-
- /**
- * Gets the value of the colName property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getColName() {
- return colName;
- }
-
- /**
- * Sets the value of the colName property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setColName(String value) {
- this.colName = value;
- }
-
- /**
- * Gets the value of the displayName property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDisplayName() {
- return displayName;
- }
-
- /**
- * Sets the value of the displayName property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDisplayName(String value) {
- this.displayName = value;
- }
-
- /**
- * Gets the value of the displayWidth property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getDisplayWidth() {
- return displayWidth;
- }
-
- /**
- * Sets the value of the displayWidth property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setDisplayWidth(Integer value) {
- this.displayWidth = value;
- }
-
- /**
- * Gets the value of the displayWidthInPxls property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDisplayWidthInPxls() {
- return displayWidthInPxls;
- }
-
- /**
- * Sets the value of the displayWidthInPxls property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDisplayWidthInPxls(String value) {
- this.displayWidthInPxls = value;
- }
-
- /**
- * Gets the value of the pdfDisplayWidthInPxls property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getPdfDisplayWidthInPxls() {
- return pdfDisplayWidthInPxls;
- }
-
- /**
- * Sets the value of the pdfDisplayWidthInPxls property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setPdfDisplayWidthInPxls(String value) {
- this.pdfDisplayWidthInPxls = value;
- }
-
- /**
- * Gets the value of the displayAlignment property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDisplayAlignment() {
- return displayAlignment;
- }
-
- /**
- * Sets the value of the displayAlignment property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDisplayAlignment(String value) {
- this.displayAlignment = value;
- }
-
- /**
- * Gets the value of the displayHeaderAlignment property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDisplayHeaderAlignment() {
- return displayHeaderAlignment;
- }
-
- /**
- * Sets the value of the displayHeaderAlignment property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDisplayHeaderAlignment(String value) {
- this.displayHeaderAlignment = value;
- }
-
- /**
- * Gets the value of the orderSeq property.
- *
- */
- public int getOrderSeq() {
- return orderSeq;
- }
-
- /**
- * Sets the value of the orderSeq property.
- *
- */
- public void setOrderSeq(int value) {
- this.orderSeq = value;
- }
-
- /**
- * Gets the value of the visible property.
- *
- */
- public boolean isVisible() {
- return visible;
- }
-
- /**
- * Sets the value of the visible property.
- *
- */
- public void setVisible(boolean value) {
- this.visible = value;
- }
-
- /**
- * Gets the value of the calculated property.
- *
- */
- public boolean isCalculated() {
- return calculated;
- }
-
- /**
- * Sets the value of the calculated property.
- *
- */
- public void setCalculated(boolean value) {
- this.calculated = value;
- }
-
- /**
- * Gets the value of the colType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getColType() {
- return colType;
- }
-
- /**
- * Sets the value of the colType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setColType(String value) {
- this.colType = value;
- }
-
- /**
- * Gets the value of the hyperlinkURL property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getHyperlinkURL() {
- return hyperlinkURL;
- }
-
- /**
- * Sets the value of the hyperlinkURL property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setHyperlinkURL(String value) {
- this.hyperlinkURL = value;
- }
-
- /**
- * Gets the value of the hyperlinkType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getHyperlinkType() {
- return hyperlinkType;
- }
-
- /**
- * Sets the value of the hyperlinkType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setHyperlinkType(String value) {
- this.hyperlinkType = value;
- }
-
- /**
- * Gets the value of the actionImg property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getActionImg() {
- return actionImg;
- }
-
- /**
- * Sets the value of the actionImg property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setActionImg(String value) {
- this.actionImg = value;
- }
-
- /**
- * Gets the value of the groupByPos property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getGroupByPos() {
- return groupByPos;
- }
-
- /**
- * Sets the value of the groupByPos property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setGroupByPos(Integer value) {
- this.groupByPos = value;
- }
-
- /**
- * Gets the value of the subTotalCustomText property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getSubTotalCustomText() {
- return subTotalCustomText;
- }
-
- /**
- * Sets the value of the subTotalCustomText property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setSubTotalCustomText(String value) {
- this.subTotalCustomText = value;
- }
-
- /**
- * Gets the value of the hideRepeatedKey property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isHideRepeatedKey() {
- return hideRepeatedKey;
- }
-
- /**
- * Sets the value of the hideRepeatedKey property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setHideRepeatedKey(Boolean value) {
- this.hideRepeatedKey = value;
- }
-
- /**
- * Gets the value of the colFormat property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getColFormat() {
- return colFormat;
- }
-
- /**
- * Sets the value of the colFormat property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setColFormat(String value) {
- this.colFormat = value;
- }
-
- /**
- * Gets the value of the groupBreak property.
- *
- */
- public boolean isGroupBreak() {
- return groupBreak;
- }
-
- /**
- * Sets the value of the groupBreak property.
- *
- */
- public void setGroupBreak(boolean value) {
- this.groupBreak = value;
- }
-
- /**
- * Gets the value of the orderBySeq property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getOrderBySeq() {
- return orderBySeq;
- }
-
- /**
- * Sets the value of the orderBySeq property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setOrderBySeq(Integer value) {
- this.orderBySeq = value;
- }
-
- /**
- * Gets the value of the orderByAscDesc property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getOrderByAscDesc() {
- return orderByAscDesc;
- }
-
- /**
- * Sets the value of the orderByAscDesc property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setOrderByAscDesc(String value) {
- this.orderByAscDesc = value;
- }
-
- /**
- * Gets the value of the displayTotal property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDisplayTotal() {
- return displayTotal;
- }
-
- /**
- * Sets the value of the displayTotal property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDisplayTotal(String value) {
- this.displayTotal = value;
- }
-
- /**
- * Gets the value of the colOnChart property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getColOnChart() {
- return colOnChart;
- }
-
- /**
- * Sets the value of the colOnChart property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setColOnChart(String value) {
- this.colOnChart = value;
- }
-
- /**
- * Gets the value of the chartSeq property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getChartSeq() {
- return chartSeq;
- }
-
- /**
- * Sets the value of the chartSeq property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setChartSeq(Integer value) {
- this.chartSeq = value;
- }
-
- /**
- * Gets the value of the chartColor property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartColor() {
- return chartColor;
- }
-
- /**
- * Sets the value of the chartColor property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartColor(String value) {
- this.chartColor = value;
- }
-
- /**
- * Gets the value of the chartLineType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartLineType() {
- return chartLineType;
- }
-
- /**
- * Sets the value of the chartLineType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartLineType(String value) {
- this.chartLineType = value;
- }
-
- /**
- * Gets the value of the chartSeries property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isChartSeries() {
- return chartSeries;
- }
-
- /**
- * Sets the value of the chartSeries property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setChartSeries(Boolean value) {
- this.chartSeries = value;
- }
-
- /**
- * Gets the value of the isRangeAxisFilled property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isIsRangeAxisFilled() {
- return isRangeAxisFilled;
- }
-
- /**
- * Sets the value of the isRangeAxisFilled property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setIsRangeAxisFilled(Boolean value) {
- this.isRangeAxisFilled = value;
- }
-
- /**
- * Gets the value of the isSortable property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isIsSortable() {
- return isSortable;
- }
-
- /**
- * Sets the value of the isSortable property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setIsSortable(Boolean value) {
- this.isSortable = value;
- }
-
- /**
- * Gets the value of the createInNewChart property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isCreateInNewChart() {
- return createInNewChart;
- }
-
- /**
- * Sets the value of the createInNewChart property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setCreateInNewChart(Boolean value) {
- this.createInNewChart = value;
- }
-
- /**
- * Gets the value of the drillDownType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDrillDownType() {
- return drillDownType;
- }
-
- /**
- * Sets the value of the drillDownType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDrillDownType(String value) {
- this.drillDownType = value;
- }
-
- /**
- * Gets the value of the drillinPoPUp property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isDrillinPoPUp() {
- return drillinPoPUp;
- }
-
- /**
- * Sets the value of the drillinPoPUp property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setDrillinPoPUp(Boolean value) {
- this.drillinPoPUp = value;
- }
-
- /**
- * Gets the value of the drillDownURL property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDrillDownURL() {
- return drillDownURL;
- }
-
- /**
- * Sets the value of the drillDownURL property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDrillDownURL(String value) {
- this.drillDownURL = value;
- }
-
- /**
- * Gets the value of the drillDownParams property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDrillDownParams() {
- return drillDownParams;
- }
-
- /**
- * Sets the value of the drillDownParams property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDrillDownParams(String value) {
- this.drillDownParams = value;
- }
-
- /**
- * Gets the value of the comment property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getComment() {
- return comment;
- }
-
- /**
- * Sets the value of the comment property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setComment(String value) {
- this.comment = value;
- }
-
- /**
- * Gets the value of the colFilterList property.
- *
- * @return
- * possible object is
- * {@link ColFilterList }
- *
- */
- public ColFilterList getColFilterList() {
- return colFilterList;
- }
-
- /**
- * Sets the value of the colFilterList property.
- *
- * @param value
- * allowed object is
- * {@link ColFilterList }
- *
- */
- public void setColFilterList(ColFilterList value) {
- this.colFilterList = value;
- }
-
- /**
- * Gets the value of the semaphoreId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getSemaphoreId() {
- return semaphoreId;
- }
-
- /**
- * Sets the value of the semaphoreId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setSemaphoreId(String value) {
- this.semaphoreId = value;
- }
-
- /**
- * Gets the value of the dbColType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDbColType() {
- return dbColType;
- }
-
- /**
- * Sets the value of the dbColType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDbColType(String value) {
- this.dbColType = value;
- }
-
- /**
- * Gets the value of the chartGroup property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getChartGroup() {
- return chartGroup;
- }
-
- /**
- * Sets the value of the chartGroup property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setChartGroup(String value) {
- this.chartGroup = value;
- }
-
- /**
- * Gets the value of the yAxis property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getYAxis() {
- return yAxis;
- }
-
- /**
- * Sets the value of the yAxis property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setYAxis(String value) {
- this.yAxis = value;
- }
-
- /**
- * Gets the value of the dependsOnFormField property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDependsOnFormField() {
- return dependsOnFormField;
- }
-
- /**
- * Sets the value of the dependsOnFormField property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDependsOnFormField(String value) {
- this.dependsOnFormField = value;
- }
-
- /**
- * Gets the value of the nowrap property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getNowrap() {
- return nowrap;
- }
-
- /**
- * Sets the value of the nowrap property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setNowrap(String value) {
- this.nowrap = value;
- }
-
- /**
- * Gets the value of the indentation property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getIndentation() {
- return indentation;
- }
-
- /**
- * Sets the value of the indentation property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setIndentation(Integer value) {
- this.indentation = value;
- }
-
- /**
- * Gets the value of the enhancedPagination property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isEnhancedPagination() {
- return enhancedPagination;
- }
-
- /**
- * Sets the value of the enhancedPagination property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setEnhancedPagination(Boolean value) {
- this.enhancedPagination = value;
- }
-
- /**
- * Gets the value of the level property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getLevel() {
- return level;
- }
-
- /**
- * Sets the value of the level property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setLevel(Integer value) {
- this.level = value;
- }
-
- /**
- * Gets the value of the start property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getStart() {
- return start;
- }
-
- /**
- * Sets the value of the start property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setStart(Integer value) {
- this.start = value;
- }
-
- /**
- * Gets the value of the colspan property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getColspan() {
- return colspan;
- }
-
- /**
- * Sets the value of the colspan property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setColspan(Integer value) {
- this.colspan = value;
- }
-
- /**
- * Gets the value of the dataMiningCol property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDataMiningCol() {
- return dataMiningCol;
- }
-
- /**
- * Sets the value of the dataMiningCol property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDataMiningCol(String value) {
- this.dataMiningCol = value;
- }
-
- /**
- * Gets the value of the colId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getColId() {
- return colId;
- }
-
- /**
- * Sets the value of the colId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setColId(String value) {
- this.colId = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for DataSourceList complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="DataSourceList">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="dataSource" type="{}DataSourceType" maxOccurs="unbounded" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "DataSourceList", propOrder = {
- "dataSource"
-})
-public class DataSourceList {
-
- protected List<DataSourceType> dataSource;
-
- /**
- * Gets the value of the dataSource property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the dataSource property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getDataSource().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link DataSourceType }
- *
- *
- */
- public List<DataSourceType> getDataSource() {
- if (dataSource == null) {
- dataSource = new ArrayList<DataSourceType>();
- }
- return this.dataSource;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for DataSourceType complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="DataSourceType">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="tableName" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="tablePK" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="displayName" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="refTableId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="refDefinition" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element ref="{}comment" minOccurs="0"/>
- * <element name="dataColumnList" type="{}DataColumnList"/>
- * </sequence>
- * <attribute name="tableId" type="{http://www.w3.org/2001/XMLSchema}string" />
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "DataSourceType", propOrder = {
- "tableName",
- "tablePK",
- "displayName",
- "refTableId",
- "refDefinition",
- "comment",
- "dataColumnList"
-})
-public class DataSourceType {
-
- @XmlElement(required = true)
- protected String tableName;
- @XmlElement(required = true)
- protected String tablePK;
- @XmlElement(required = true)
- protected String displayName;
- protected String refTableId;
- protected String refDefinition;
- protected String comment;
- @XmlElement(required = true)
- protected DataColumnList dataColumnList;
- @XmlAttribute(name = "tableId")
- protected String tableId;
-
- /**
- * Gets the value of the tableName property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTableName() {
- return tableName;
- }
-
- /**
- * Sets the value of the tableName property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTableName(String value) {
- this.tableName = value;
- }
-
- /**
- * Gets the value of the tablePK property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTablePK() {
- return tablePK;
- }
-
- /**
- * Sets the value of the tablePK property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTablePK(String value) {
- this.tablePK = value;
- }
-
- /**
- * Gets the value of the displayName property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDisplayName() {
- return displayName;
- }
-
- /**
- * Sets the value of the displayName property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDisplayName(String value) {
- this.displayName = value;
- }
-
- /**
- * Gets the value of the refTableId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getRefTableId() {
- return refTableId;
- }
-
- /**
- * Sets the value of the refTableId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setRefTableId(String value) {
- this.refTableId = value;
- }
-
- /**
- * Gets the value of the refDefinition property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getRefDefinition() {
- return refDefinition;
- }
-
- /**
- * Sets the value of the refDefinition property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setRefDefinition(String value) {
- this.refDefinition = value;
- }
-
- /**
- * Gets the value of the comment property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getComment() {
- return comment;
- }
-
- /**
- * Sets the value of the comment property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setComment(String value) {
- this.comment = value;
- }
-
- /**
- * Gets the value of the dataColumnList property.
- *
- * @return
- * possible object is
- * {@link DataColumnList }
- *
- */
- public DataColumnList getDataColumnList() {
- return dataColumnList;
- }
-
- /**
- * Sets the value of the dataColumnList property.
- *
- * @param value
- * allowed object is
- * {@link DataColumnList }
- *
- */
- public void setDataColumnList(DataColumnList value) {
- this.dataColumnList = value;
- }
-
- /**
- * Gets the value of the tableId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTableId() {
- return tableId;
- }
-
- /**
- * Sets the value of the tableId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTableId(String value) {
- this.tableId = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for DataminingOptions complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="DataminingOptions">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="classifier" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="timeAttribute" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="timeformat" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="forecastingUnits" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "DataminingOptions", propOrder = {
- "classifier",
- "timeAttribute",
- "timeformat",
- "forecastingUnits"
-})
-public class DataminingOptions {
-
- protected String classifier;
- protected String timeAttribute;
- protected String timeformat;
- protected String forecastingUnits;
-
- /**
- * Gets the value of the classifier property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getClassifier() {
- return classifier;
- }
-
- /**
- * Sets the value of the classifier property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setClassifier(String value) {
- this.classifier = value;
- }
-
- /**
- * Gets the value of the timeAttribute property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTimeAttribute() {
- return timeAttribute;
- }
-
- /**
- * Sets the value of the timeAttribute property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTimeAttribute(String value) {
- this.timeAttribute = value;
- }
-
- /**
- * Gets the value of the timeformat property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTimeformat() {
- return timeformat;
- }
-
- /**
- * Sets the value of the timeformat property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTimeformat(String value) {
- this.timeformat = value;
- }
-
- /**
- * Gets the value of the forecastingUnits property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getForecastingUnits() {
- return forecastingUnits;
- }
-
- /**
- * Sets the value of the forecastingUnits property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setForecastingUnits(String value) {
- this.forecastingUnits = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for FormFieldList complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="FormFieldList">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="formField" type="{}FormFieldType" maxOccurs="unbounded" minOccurs="0"/>
- * <element ref="{}comment" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "FormFieldList", propOrder = {
- "formField",
- "comment"
-})
-public class FormFieldList {
-
- protected List<FormFieldType> formField;
- protected String comment;
-
- /**
- * Gets the value of the formField property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the formField property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getFormField().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link FormFieldType }
- *
- *
- */
- public List<FormFieldType> getFormField() {
- if (formField == null) {
- formField = new ArrayList<FormFieldType>();
- }
- return this.formField;
- }
-
- /**
- * Gets the value of the comment property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getComment() {
- return comment;
- }
-
- /**
- * Sets the value of the comment property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setComment(String value) {
- this.comment = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlSchemaType;
-import javax.xml.bind.annotation.XmlType;
-import javax.xml.datatype.XMLGregorianCalendar;
-
-
-/**
- * <p>Java class for FormFieldType complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="FormFieldType">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="colId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="fieldName" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="fieldType" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="visible" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="validationType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="mandatory" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="defaultValue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="orderBySeq" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="fieldSQL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="fieldDefaultSQL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="rangeStartDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
- * <element name="rangeEndDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
- * <element name="rangeStartDateSQL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="rangeEndDateSQL" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element ref="{}comment" minOccurs="0"/>
- * <element name="predefinedValueList" type="{}PredefinedValueList" minOccurs="0"/>
- * <element name="dependsOn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="groupFormField" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="multiSelectListSize" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * </sequence>
- * <attribute name="fieldId" type="{http://www.w3.org/2001/XMLSchema}string" />
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "FormFieldType", propOrder = {
- "colId",
- "fieldName",
- "fieldType",
- "visible",
- "validationType",
- "mandatory",
- "defaultValue",
- "orderBySeq",
- "fieldSQL",
- "fieldDefaultSQL",
- "rangeStartDate",
- "rangeEndDate",
- "rangeStartDateSQL",
- "rangeEndDateSQL",
- "comment",
- "predefinedValueList",
- "dependsOn",
- "groupFormField",
- "multiSelectListSize"
-})
-public class FormFieldType {
-
- @XmlElement(required = true)
- protected String colId;
- @XmlElement(required = true)
- protected String fieldName;
- @XmlElement(required = true)
- protected String fieldType;
- protected String visible;
- protected String validationType;
- protected String mandatory;
- protected String defaultValue;
- protected Integer orderBySeq;
- protected String fieldSQL;
- protected String fieldDefaultSQL;
- @XmlSchemaType(name = "date")
- protected XMLGregorianCalendar rangeStartDate;
- @XmlSchemaType(name = "date")
- protected XMLGregorianCalendar rangeEndDate;
- protected String rangeStartDateSQL;
- protected String rangeEndDateSQL;
- protected String comment;
- protected PredefinedValueList predefinedValueList;
- protected String dependsOn;
- @XmlElement(defaultValue = "false")
- protected Boolean groupFormField;
- @XmlElement(defaultValue = "4")
- protected String multiSelectListSize;
- @XmlAttribute(name = "fieldId")
- protected String fieldId;
-
- /**
- * Gets the value of the colId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getColId() {
- return colId;
- }
-
- /**
- * Sets the value of the colId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setColId(String value) {
- this.colId = value;
- }
-
- /**
- * Gets the value of the fieldName property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getFieldName() {
- return fieldName;
- }
-
- /**
- * Sets the value of the fieldName property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setFieldName(String value) {
- this.fieldName = value;
- }
-
- /**
- * Gets the value of the fieldType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getFieldType() {
- return fieldType;
- }
-
- /**
- * Sets the value of the fieldType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setFieldType(String value) {
- this.fieldType = value;
- }
-
- /**
- * Gets the value of the visible property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getVisible() {
- return visible;
- }
-
- /**
- * Sets the value of the visible property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setVisible(String value) {
- this.visible = value;
- }
-
- /**
- * Gets the value of the validationType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getValidationType() {
- return validationType;
- }
-
- /**
- * Sets the value of the validationType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setValidationType(String value) {
- this.validationType = value;
- }
-
- /**
- * Gets the value of the mandatory property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getMandatory() {
- return mandatory;
- }
-
- /**
- * Sets the value of the mandatory property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setMandatory(String value) {
- this.mandatory = value;
- }
-
- /**
- * Gets the value of the defaultValue property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDefaultValue() {
- return defaultValue;
- }
-
- /**
- * Sets the value of the defaultValue property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDefaultValue(String value) {
- this.defaultValue = value;
- }
-
- /**
- * Gets the value of the orderBySeq property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getOrderBySeq() {
- return orderBySeq;
- }
-
- /**
- * Sets the value of the orderBySeq property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setOrderBySeq(Integer value) {
- this.orderBySeq = value;
- }
-
- /**
- * Gets the value of the fieldSQL property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getFieldSQL() {
- return fieldSQL;
- }
-
- /**
- * Sets the value of the fieldSQL property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setFieldSQL(String value) {
- this.fieldSQL = value;
- }
-
- /**
- * Gets the value of the fieldDefaultSQL property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getFieldDefaultSQL() {
- return fieldDefaultSQL;
- }
-
- /**
- * Sets the value of the fieldDefaultSQL property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setFieldDefaultSQL(String value) {
- this.fieldDefaultSQL = value;
- }
-
- /**
- * Gets the value of the rangeStartDate property.
- *
- * @return
- * possible object is
- * {@link XMLGregorianCalendar }
- *
- */
- public XMLGregorianCalendar getRangeStartDate() {
- return rangeStartDate;
- }
-
- /**
- * Sets the value of the rangeStartDate property.
- *
- * @param value
- * allowed object is
- * {@link XMLGregorianCalendar }
- *
- */
- public void setRangeStartDate(XMLGregorianCalendar value) {
- this.rangeStartDate = value;
- }
-
- /**
- * Gets the value of the rangeEndDate property.
- *
- * @return
- * possible object is
- * {@link XMLGregorianCalendar }
- *
- */
- public XMLGregorianCalendar getRangeEndDate() {
- return rangeEndDate;
- }
-
- /**
- * Sets the value of the rangeEndDate property.
- *
- * @param value
- * allowed object is
- * {@link XMLGregorianCalendar }
- *
- */
- public void setRangeEndDate(XMLGregorianCalendar value) {
- this.rangeEndDate = value;
- }
-
- /**
- * Gets the value of the rangeStartDateSQL property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getRangeStartDateSQL() {
- return rangeStartDateSQL;
- }
-
- /**
- * Sets the value of the rangeStartDateSQL property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setRangeStartDateSQL(String value) {
- this.rangeStartDateSQL = value;
- }
-
- /**
- * Gets the value of the rangeEndDateSQL property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getRangeEndDateSQL() {
- return rangeEndDateSQL;
- }
-
- /**
- * Sets the value of the rangeEndDateSQL property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setRangeEndDateSQL(String value) {
- this.rangeEndDateSQL = value;
- }
-
- /**
- * Gets the value of the comment property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getComment() {
- return comment;
- }
-
- /**
- * Sets the value of the comment property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setComment(String value) {
- this.comment = value;
- }
-
- /**
- * Gets the value of the predefinedValueList property.
- *
- * @return
- * possible object is
- * {@link PredefinedValueList }
- *
- */
- public PredefinedValueList getPredefinedValueList() {
- return predefinedValueList;
- }
-
- /**
- * Sets the value of the predefinedValueList property.
- *
- * @param value
- * allowed object is
- * {@link PredefinedValueList }
- *
- */
- public void setPredefinedValueList(PredefinedValueList value) {
- this.predefinedValueList = value;
- }
-
- /**
- * Gets the value of the dependsOn property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDependsOn() {
- return dependsOn;
- }
-
- /**
- * Sets the value of the dependsOn property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDependsOn(String value) {
- this.dependsOn = value;
- }
-
- /**
- * Gets the value of the groupFormField property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isGroupFormField() {
- return groupFormField;
- }
-
- /**
- * Sets the value of the groupFormField property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setGroupFormField(Boolean value) {
- this.groupFormField = value;
- }
-
- /**
- * Gets the value of the multiSelectListSize property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getMultiSelectListSize() {
- return multiSelectListSize;
- }
-
- /**
- * Sets the value of the multiSelectListSize property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setMultiSelectListSize(String value) {
- this.multiSelectListSize = value;
- }
-
- /**
- * Gets the value of the fieldId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getFieldId() {
- return fieldId;
- }
-
- /**
- * Sets the value of the fieldId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setFieldId(String value) {
- this.fieldId = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for FormatList complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="FormatList">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="format" type="{}FormatType" maxOccurs="unbounded"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "FormatList", propOrder = {
- "format"
-})
-public class FormatList {
-
- @XmlElement(required = true)
- protected List<FormatType> format;
-
- /**
- * Gets the value of the format property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the format property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getFormat().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link FormatType }
- *
- *
- */
- public List<FormatType> getFormat() {
- if (format == null) {
- format = new ArrayList<FormatType>();
- }
- return this.format;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for FormatType complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="FormatType">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="lessThanValue" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="expression" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="bold" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
- * <element name="italic" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
- * <element name="underline" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
- * <element name="bgColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="fontColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="fontFace" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="fontSize" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="alignment" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element ref="{}comment" minOccurs="0"/>
- * </sequence>
- * <attribute name="formatId" type="{http://www.w3.org/2001/XMLSchema}string" />
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "FormatType", propOrder = {
- "lessThanValue",
- "expression",
- "bold",
- "italic",
- "underline",
- "bgColor",
- "fontColor",
- "fontFace",
- "fontSize",
- "alignment",
- "comment"
-})
-public class FormatType {
-
- @XmlElement(required = true)
- protected String lessThanValue;
- @XmlElement(required = true)
- protected String expression;
- @XmlElement(defaultValue = "false")
- protected boolean bold;
- @XmlElement(defaultValue = "false")
- protected boolean italic;
- @XmlElement(defaultValue = "false")
- protected boolean underline;
- protected String bgColor;
- protected String fontColor;
- protected String fontFace;
- protected String fontSize;
- protected String alignment;
- protected String comment;
- @XmlAttribute(name = "formatId")
- protected String formatId;
-
- /**
- * Gets the value of the lessThanValue property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getLessThanValue() {
- return lessThanValue;
- }
-
- /**
- * Sets the value of the lessThanValue property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setLessThanValue(String value) {
- this.lessThanValue = value;
- }
-
- /**
- * Gets the value of the expression property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getExpression() {
- return expression;
- }
-
- /**
- * Sets the value of the expression property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setExpression(String value) {
- this.expression = value;
- }
-
- /**
- * Gets the value of the bold property.
- *
- */
- public boolean isBold() {
- return bold;
- }
-
- /**
- * Sets the value of the bold property.
- *
- */
- public void setBold(boolean value) {
- this.bold = value;
- }
-
- /**
- * Gets the value of the italic property.
- *
- */
- public boolean isItalic() {
- return italic;
- }
-
- /**
- * Sets the value of the italic property.
- *
- */
- public void setItalic(boolean value) {
- this.italic = value;
- }
-
- /**
- * Gets the value of the underline property.
- *
- */
- public boolean isUnderline() {
- return underline;
- }
-
- /**
- * Sets the value of the underline property.
- *
- */
- public void setUnderline(boolean value) {
- this.underline = value;
- }
-
- /**
- * Gets the value of the bgColor property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getBgColor() {
- return bgColor;
- }
-
- /**
- * Sets the value of the bgColor property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setBgColor(String value) {
- this.bgColor = value;
- }
-
- /**
- * Gets the value of the fontColor property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getFontColor() {
- return fontColor;
- }
-
- /**
- * Sets the value of the fontColor property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setFontColor(String value) {
- this.fontColor = value;
- }
-
- /**
- * Gets the value of the fontFace property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getFontFace() {
- return fontFace;
- }
-
- /**
- * Sets the value of the fontFace property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setFontFace(String value) {
- this.fontFace = value;
- }
-
- /**
- * Gets the value of the fontSize property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getFontSize() {
- return fontSize;
- }
-
- /**
- * Sets the value of the fontSize property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setFontSize(String value) {
- this.fontSize = value;
- }
-
- /**
- * Gets the value of the alignment property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getAlignment() {
- return alignment;
- }
-
- /**
- * Sets the value of the alignment property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setAlignment(String value) {
- this.alignment = value;
- }
-
- /**
- * Gets the value of the comment property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getComment() {
- return comment;
- }
-
- /**
- * Sets the value of the comment property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setComment(String value) {
- this.comment = value;
- }
-
- /**
- * Gets the value of the formatId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getFormatId() {
- return formatId;
- }
-
- /**
- * Sets the value of the formatId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setFormatId(String value) {
- this.formatId = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for JavascriptItemType complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="JavascriptItemType">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="fieldId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="callText" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "JavascriptItemType", propOrder = {
- "id",
- "fieldId",
- "callText"
-})
-public class JavascriptItemType {
-
- @XmlElement(required = true)
- protected String id;
- @XmlElement(required = true)
- protected String fieldId;
- @XmlElement(required = true)
- protected String callText;
-
- /**
- * Gets the value of the id property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getId() {
- return id;
- }
-
- /**
- * Sets the value of the id property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setId(String value) {
- this.id = value;
- }
-
- /**
- * Gets the value of the fieldId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getFieldId() {
- return fieldId;
- }
-
- /**
- * Sets the value of the fieldId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setFieldId(String value) {
- this.fieldId = value;
- }
-
- /**
- * Gets the value of the callText property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getCallText() {
- return callText;
- }
-
- /**
- * Sets the value of the callText property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setCallText(String value) {
- this.callText = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for JavascriptList complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="JavascriptList">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="javascriptItem" type="{}JavascriptItemType" maxOccurs="unbounded" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "JavascriptList", propOrder = {
- "javascriptItem"
-})
-public class JavascriptList {
-
- protected List<JavascriptItemType> javascriptItem;
-
- /**
- * Gets the value of the javascriptItem property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the javascriptItem property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getJavascriptItem().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link JavascriptItemType }
- *
- *
- */
- public List<JavascriptItemType> getJavascriptItem() {
- if (javascriptItem == null) {
- javascriptItem = new ArrayList<JavascriptItemType>();
- }
- return this.javascriptItem;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for Marker complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="Marker">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="markerColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="dataHeader" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="addressColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="dataColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "Marker", propOrder = {
- "markerColor",
- "dataHeader",
- "addressColumn",
- "dataColumn"
-})
-public class Marker {
-
- protected String markerColor;
- protected String dataHeader;
- protected String addressColumn;
- protected String dataColumn;
-
- /**
- * Gets the value of the markerColor property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getMarkerColor() {
- return markerColor;
- }
-
- /**
- * Sets the value of the markerColor property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setMarkerColor(String value) {
- this.markerColor = value;
- }
-
- /**
- * Gets the value of the dataHeader property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDataHeader() {
- return dataHeader;
- }
-
- /**
- * Sets the value of the dataHeader property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDataHeader(String value) {
- this.dataHeader = value;
- }
-
- /**
- * Gets the value of the addressColumn property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getAddressColumn() {
- return addressColumn;
- }
-
- /**
- * Sets the value of the addressColumn property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setAddressColumn(String value) {
- this.addressColumn = value;
- }
-
- /**
- * Gets the value of the dataColumn property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDataColumn() {
- return dataColumn;
- }
-
- /**
- * Sets the value of the dataColumn property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDataColumn(String value) {
- this.dataColumn = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.annotation.XmlElementDecl;
-import javax.xml.bind.annotation.XmlRegistry;
-import javax.xml.namespace.QName;
-
-
-/**
- * This object contains factory methods for each
- * Java content interface and Java element interface
- * generated in the org.openecomp.portalsdk.analytics.xmlobj package.
- * <p>An ObjectFactory allows you to programatically
- * construct new instances of the Java representation
- * for XML content. The Java representation of XML
- * content can consist of schema derived interfaces
- * and classes representing the binding of schema
- * type definitions, element declarations and model
- * groups. Factory methods for each of these are
- * provided in this class.
- *
- */
-@XmlRegistry
-public class ObjectFactory {
-
- private final static QName _CustomReport_QNAME = new QName("", "customReport");
- private final static QName _Comment_QNAME = new QName("", "comment");
-
- /**
- * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.openecomp.portalsdk.analytics.xmlobj
- *
- */
- public ObjectFactory() {
- }
-
- /**
- * Create an instance of {@link CustomReportType }
- *
- */
- public CustomReportType createCustomReportType() {
- return new CustomReportType();
- }
-
- /**
- * Create an instance of {@link ChartAdditionalOptions }
- *
- */
- public ChartAdditionalOptions createChartAdditionalOptions() {
- return new ChartAdditionalOptions();
- }
-
- /**
- * Create an instance of {@link DataminingOptions }
- *
- */
- public DataminingOptions createDataminingOptions() {
- return new DataminingOptions();
- }
-
- /**
- * Create an instance of {@link FormFieldType }
- *
- */
- public FormFieldType createFormFieldType() {
- return new FormFieldType();
- }
-
- /**
- * Create an instance of {@link PredefinedValueList }
- *
- */
- public PredefinedValueList createPredefinedValueList() {
- return new PredefinedValueList();
- }
-
- /**
- * Create an instance of {@link DashboardEditorReport }
- *
- */
- public DashboardEditorReport createDashboardEditorReport() {
- return new DashboardEditorReport();
- }
-
- /**
- * Create an instance of {@link DataSourceList }
- *
- */
- public DataSourceList createDataSourceList() {
- return new DataSourceList();
- }
-
- /**
- * Create an instance of {@link DashboardReports }
- *
- */
- public DashboardReports createDashboardReports() {
- return new DashboardReports();
- }
-
- /**
- * Create an instance of {@link ReportMap }
- *
- */
- public ReportMap createReportMap() {
- return new ReportMap();
- }
-
- /**
- * Create an instance of {@link FormatList }
- *
- */
- public FormatList createFormatList() {
- return new FormatList();
- }
-
- /**
- * Create an instance of {@link JavascriptList }
- *
- */
- public JavascriptList createJavascriptList() {
- return new JavascriptList();
- }
-
- /**
- * Create an instance of {@link JavascriptItemType }
- *
- */
- public JavascriptItemType createJavascriptItemType() {
- return new JavascriptItemType();
- }
-
- /**
- * Create an instance of {@link DataColumnType }
- *
- */
- public DataColumnType createDataColumnType() {
- return new DataColumnType();
- }
-
- /**
- * Create an instance of {@link DataSourceType }
- *
- */
- public DataSourceType createDataSourceType() {
- return new DataSourceType();
- }
-
- /**
- * Create an instance of {@link DashboardEditorList }
- *
- */
- public DashboardEditorList createDashboardEditorList() {
- return new DashboardEditorList();
- }
-
- /**
- * Create an instance of {@link SemaphoreList }
- *
- */
- public SemaphoreList createSemaphoreList() {
- return new SemaphoreList();
- }
-
- /**
- * Create an instance of {@link ColFilterType }
- *
- */
- public ColFilterType createColFilterType() {
- return new ColFilterType();
- }
-
- /**
- * Create an instance of {@link ChartDrillOptions }
- *
- */
- public ChartDrillOptions createChartDrillOptions() {
- return new ChartDrillOptions();
- }
-
- /**
- * Create an instance of {@link DashboardReportsNew }
- *
- */
- public DashboardReportsNew createDashboardReportsNew() {
- return new DashboardReportsNew();
- }
-
- /**
- * Create an instance of {@link ChartDrillFormfield }
- *
- */
- public ChartDrillFormfield createChartDrillFormfield() {
- return new ChartDrillFormfield();
- }
-
- /**
- * Create an instance of {@link PDFAdditionalOptions }
- *
- */
- public PDFAdditionalOptions createPDFAdditionalOptions() {
- return new PDFAdditionalOptions();
- }
-
- /**
- * Create an instance of {@link Reports }
- *
- */
- public Reports createReports() {
- return new Reports();
- }
-
- /**
- * Create an instance of {@link Marker }
- *
- */
- public Marker createMarker() {
- return new Marker();
- }
-
- /**
- * Create an instance of {@link FormatType }
- *
- */
- public FormatType createFormatType() {
- return new FormatType();
- }
-
- /**
- * Create an instance of {@link DataColumnList }
- *
- */
- public DataColumnList createDataColumnList() {
- return new DataColumnList();
- }
-
- /**
- * Create an instance of {@link FormFieldList }
- *
- */
- public FormFieldList createFormFieldList() {
- return new FormFieldList();
- }
-
- /**
- * Create an instance of {@link SemaphoreType }
- *
- */
- public SemaphoreType createSemaphoreType() {
- return new SemaphoreType();
- }
-
- /**
- * Create an instance of {@link ColFilterList }
- *
- */
- public ColFilterList createColFilterList() {
- return new ColFilterList();
- }
-
- /**
- * Create an instance of {@link JAXBElement }{@code <}{@link CustomReportType }{@code >}}
- *
- */
- @XmlElementDecl(namespace = "", name = "customReport")
- public JAXBElement<CustomReportType> createCustomReport(CustomReportType value) {
- return new JAXBElement<CustomReportType>(_CustomReport_QNAME, CustomReportType.class, null, value);
- }
-
- /**
- * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
- *
- */
- @XmlElementDecl(namespace = "", name = "comment")
- public JAXBElement<String> createComment(String value) {
- return new JAXBElement<String>(_Comment_QNAME, String.class, null, value);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for PDFAdditionalOptions complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="PDFAdditionalOptions">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="PDF_font" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="PDF_fontSize" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="PDF_orientation" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="PDF_logo1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="PDF_logo2" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="PDF_logo1Size" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="PDF_logo2Size" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
- * <element name="PDF_coverPage" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- * <element name="PDF_footer1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="PDF_footer2" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "PDFAdditionalOptions", propOrder = {
- "pdfFont",
- "pdfFontSize",
- "pdfOrientation",
- "pdfLogo1",
- "pdfLogo2",
- "pdfLogo1Size",
- "pdfLogo2Size",
- "pdfCoverPage",
- "pdfFooter1",
- "pdfFooter2"
-})
-public class PDFAdditionalOptions {
-
- @XmlElement(name = "PDF_font")
- protected String pdfFont;
- @XmlElement(name = "PDF_fontSize")
- protected Integer pdfFontSize;
- @XmlElement(name = "PDF_orientation")
- protected String pdfOrientation;
- @XmlElement(name = "PDF_logo1")
- protected String pdfLogo1;
- @XmlElement(name = "PDF_logo2")
- protected String pdfLogo2;
- @XmlElement(name = "PDF_logo1Size")
- protected Integer pdfLogo1Size;
- @XmlElement(name = "PDF_logo2Size")
- protected Integer pdfLogo2Size;
- @XmlElement(name = "PDF_coverPage", defaultValue = "false")
- protected Boolean pdfCoverPage;
- @XmlElement(name = "PDF_footer1")
- protected String pdfFooter1;
- @XmlElement(name = "PDF_footer2")
- protected String pdfFooter2;
-
- /**
- * Gets the value of the pdfFont property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getPDFFont() {
- return pdfFont;
- }
-
- /**
- * Sets the value of the pdfFont property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setPDFFont(String value) {
- this.pdfFont = value;
- }
-
- /**
- * Gets the value of the pdfFontSize property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getPDFFontSize() {
- return pdfFontSize;
- }
-
- /**
- * Sets the value of the pdfFontSize property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setPDFFontSize(Integer value) {
- this.pdfFontSize = value;
- }
-
- /**
- * Gets the value of the pdfOrientation property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getPDFOrientation() {
- return pdfOrientation;
- }
-
- /**
- * Sets the value of the pdfOrientation property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setPDFOrientation(String value) {
- this.pdfOrientation = value;
- }
-
- /**
- * Gets the value of the pdfLogo1 property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getPDFLogo1() {
- return pdfLogo1;
- }
-
- /**
- * Sets the value of the pdfLogo1 property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setPDFLogo1(String value) {
- this.pdfLogo1 = value;
- }
-
- /**
- * Gets the value of the pdfLogo2 property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getPDFLogo2() {
- return pdfLogo2;
- }
-
- /**
- * Sets the value of the pdfLogo2 property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setPDFLogo2(String value) {
- this.pdfLogo2 = value;
- }
-
- /**
- * Gets the value of the pdfLogo1Size property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getPDFLogo1Size() {
- return pdfLogo1Size;
- }
-
- /**
- * Sets the value of the pdfLogo1Size property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setPDFLogo1Size(Integer value) {
- this.pdfLogo1Size = value;
- }
-
- /**
- * Gets the value of the pdfLogo2Size property.
- *
- * @return
- * possible object is
- * {@link Integer }
- *
- */
- public Integer getPDFLogo2Size() {
- return pdfLogo2Size;
- }
-
- /**
- * Sets the value of the pdfLogo2Size property.
- *
- * @param value
- * allowed object is
- * {@link Integer }
- *
- */
- public void setPDFLogo2Size(Integer value) {
- this.pdfLogo2Size = value;
- }
-
- /**
- * Gets the value of the pdfCoverPage property.
- *
- * @return
- * possible object is
- * {@link Boolean }
- *
- */
- public Boolean isPDFCoverPage() {
- return pdfCoverPage;
- }
-
- /**
- * Sets the value of the pdfCoverPage property.
- *
- * @param value
- * allowed object is
- * {@link Boolean }
- *
- */
- public void setPDFCoverPage(Boolean value) {
- this.pdfCoverPage = value;
- }
-
- /**
- * Gets the value of the pdfFooter1 property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getPDFFooter1() {
- return pdfFooter1;
- }
-
- /**
- * Sets the value of the pdfFooter1 property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setPDFFooter1(String value) {
- this.pdfFooter1 = value;
- }
-
- /**
- * Gets the value of the pdfFooter2 property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getPDFFooter2() {
- return pdfFooter2;
- }
-
- /**
- * Sets the value of the pdfFooter2 property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setPDFFooter2(String value) {
- this.pdfFooter2 = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for PredefinedValueList complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="PredefinedValueList">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="predefinedValue" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "PredefinedValueList", propOrder = {
- "predefinedValue"
-})
-public class PredefinedValueList {
-
- protected List<String> predefinedValue;
-
- /**
- * Gets the value of the predefinedValue property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the predefinedValue property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getPredefinedValue().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link String }
- *
- *
- */
- public List<String> getPredefinedValue() {
- if (predefinedValue == null) {
- predefinedValue = new ArrayList<String>();
- }
- return this.predefinedValue;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for ReportMap complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="ReportMap">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="markerColor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="useDefaultSize" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="height" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="width" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="isMapAllowedYN" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="addAddressInDataYN" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="addressColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="dataColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="defaultMapType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="latColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="longColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="colorColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="legendColumn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="markers" type="{}Marker" maxOccurs="unbounded" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "ReportMap", propOrder = {
- "markerColor",
- "useDefaultSize",
- "height",
- "width",
- "isMapAllowedYN",
- "addAddressInDataYN",
- "addressColumn",
- "dataColumn",
- "defaultMapType",
- "latColumn",
- "longColumn",
- "colorColumn",
- "legendColumn",
- "markers"
-})
-public class ReportMap {
-
- protected String markerColor;
- protected String useDefaultSize;
- protected String height;
- protected String width;
- protected String isMapAllowedYN;
- protected String addAddressInDataYN;
- protected String addressColumn;
- protected String dataColumn;
- protected String defaultMapType;
- protected String latColumn;
- protected String longColumn;
- protected String colorColumn;
- protected String legendColumn;
- protected List<Marker> markers;
-
- /**
- * Gets the value of the markerColor property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getMarkerColor() {
- return markerColor;
- }
-
- /**
- * Sets the value of the markerColor property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setMarkerColor(String value) {
- this.markerColor = value;
- }
-
- /**
- * Gets the value of the useDefaultSize property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getUseDefaultSize() {
- return useDefaultSize;
- }
-
- /**
- * Sets the value of the useDefaultSize property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setUseDefaultSize(String value) {
- this.useDefaultSize = value;
- }
-
- /**
- * Gets the value of the height property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getHeight() {
- return height;
- }
-
- /**
- * Sets the value of the height property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setHeight(String value) {
- this.height = value;
- }
-
- /**
- * Gets the value of the width property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getWidth() {
- return width;
- }
-
- /**
- * Sets the value of the width property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setWidth(String value) {
- this.width = value;
- }
-
- /**
- * Gets the value of the isMapAllowedYN property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getIsMapAllowedYN() {
- return isMapAllowedYN;
- }
-
- /**
- * Sets the value of the isMapAllowedYN property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setIsMapAllowedYN(String value) {
- this.isMapAllowedYN = value;
- }
-
- /**
- * Gets the value of the addAddressInDataYN property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getAddAddressInDataYN() {
- return addAddressInDataYN;
- }
-
- /**
- * Sets the value of the addAddressInDataYN property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setAddAddressInDataYN(String value) {
- this.addAddressInDataYN = value;
- }
-
- /**
- * Gets the value of the addressColumn property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getAddressColumn() {
- return addressColumn;
- }
-
- /**
- * Sets the value of the addressColumn property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setAddressColumn(String value) {
- this.addressColumn = value;
- }
-
- /**
- * Gets the value of the dataColumn property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDataColumn() {
- return dataColumn;
- }
-
- /**
- * Sets the value of the dataColumn property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDataColumn(String value) {
- this.dataColumn = value;
- }
-
- /**
- * Gets the value of the defaultMapType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getDefaultMapType() {
- return defaultMapType;
- }
-
- /**
- * Sets the value of the defaultMapType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setDefaultMapType(String value) {
- this.defaultMapType = value;
- }
-
- /**
- * Gets the value of the latColumn property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getLatColumn() {
- return latColumn;
- }
-
- /**
- * Sets the value of the latColumn property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setLatColumn(String value) {
- this.latColumn = value;
- }
-
- /**
- * Gets the value of the longColumn property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getLongColumn() {
- return longColumn;
- }
-
- /**
- * Sets the value of the longColumn property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setLongColumn(String value) {
- this.longColumn = value;
- }
-
- /**
- * Gets the value of the colorColumn property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getColorColumn() {
- return colorColumn;
- }
-
- /**
- * Sets the value of the colorColumn property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setColorColumn(String value) {
- this.colorColumn = value;
- }
-
- /**
- * Gets the value of the legendColumn property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getLegendColumn() {
- return legendColumn;
- }
-
- /**
- * Sets the value of the legendColumn property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setLegendColumn(String value) {
- this.legendColumn = value;
- }
-
- /**
- * Gets the value of the markers property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the markers property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getMarkers().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link Marker }
- *
- *
- */
- public List<Marker> getMarkers() {
- if (markers == null) {
- markers = new ArrayList<Marker>();
- }
- return this.markers;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for Reports complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="Reports">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="reportId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * <element name="bgcolor" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "Reports", propOrder = {
- "reportId",
- "bgcolor"
-})
-public class Reports {
-
- protected String reportId;
- protected String bgcolor;
-
- /**
- * Gets the value of the reportId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getReportId() {
- return reportId;
- }
-
- /**
- * Sets the value of the reportId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setReportId(String value) {
- this.reportId = value;
- }
-
- /**
- * Gets the value of the bgcolor property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getBgcolor() {
- return bgcolor;
- }
-
- /**
- * Sets the value of the bgcolor property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setBgcolor(String value) {
- this.bgcolor = value;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for SemaphoreList complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="SemaphoreList">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="semaphore" type="{}SemaphoreType" maxOccurs="unbounded" minOccurs="0"/>
- * </sequence>
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "SemaphoreList", propOrder = {
- "semaphore"
-})
-public class SemaphoreList {
-
- protected List<SemaphoreType> semaphore;
-
- /**
- * Gets the value of the semaphore property.
- *
- * <p>
- * This accessor method returns a reference to the live list,
- * not a snapshot. Therefore any modification you make to the
- * returned list will be present inside the JAXB object.
- * This is why there is not a <CODE>set</CODE> method for the semaphore property.
- *
- * <p>
- * For example, to add a new item, do as follows:
- * <pre>
- * getSemaphore().add(newItem);
- * </pre>
- *
- *
- * <p>
- * Objects of the following type(s) are allowed in the list
- * {@link SemaphoreType }
- *
- *
- */
- public List<SemaphoreType> getSemaphore() {
- if (semaphore == null) {
- semaphore = new ArrayList<SemaphoreType>();
- }
- return this.semaphore;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
-// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
-// Any modifications to this file will be lost upon recompilation of the source schema.
-// Generated on: 2016.06.07 at 02:07:29 PM EDT
-//
-
-
-package org.openecomp.portalsdk.analytics.xmlobj;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-
-/**
- * <p>Java class for SemaphoreType complex type.
- *
- * <p>The following schema fragment specifies the expected content contained within this class.
- *
- * <pre>
- * <complexType name="SemaphoreType">
- * <complexContent>
- * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- * <sequence>
- * <element name="semaphoreName" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="semaphoreType" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element ref="{}comment" minOccurs="0"/>
- * <element name="target" type="{http://www.w3.org/2001/XMLSchema}string"/>
- * <element name="formatList" type="{}FormatList"/>
- * </sequence>
- * <attribute name="semaphoreId" type="{http://www.w3.org/2001/XMLSchema}string" />
- * </restriction>
- * </complexContent>
- * </complexType>
- * </pre>
- *
- *
- */
-@XmlAccessorType(XmlAccessType.FIELD)
-@XmlType(name = "SemaphoreType", propOrder = {
- "semaphoreName",
- "semaphoreType",
- "comment",
- "target",
- "formatList"
-})
-public class SemaphoreType {
-
- @XmlElement(required = true)
- protected String semaphoreName;
- @XmlElement(required = true)
- protected String semaphoreType;
- protected String comment;
- @XmlElement(required = true)
- protected String target;
- @XmlElement(required = true)
- protected FormatList formatList;
- @XmlAttribute(name = "semaphoreId")
- protected String semaphoreId;
-
- /**
- * Gets the value of the semaphoreName property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getSemaphoreName() {
- return semaphoreName;
- }
-
- /**
- * Sets the value of the semaphoreName property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setSemaphoreName(String value) {
- this.semaphoreName = value;
- }
-
- /**
- * Gets the value of the semaphoreType property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getSemaphoreType() {
- return semaphoreType;
- }
-
- /**
- * Sets the value of the semaphoreType property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setSemaphoreType(String value) {
- this.semaphoreType = value;
- }
-
- /**
- * Gets the value of the comment property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getComment() {
- return comment;
- }
-
- /**
- * Sets the value of the comment property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setComment(String value) {
- this.comment = value;
- }
-
- /**
- * Gets the value of the target property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getTarget() {
- return target;
- }
-
- /**
- * Sets the value of the target property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setTarget(String value) {
- this.target = value;
- }
-
- /**
- * Gets the value of the formatList property.
- *
- * @return
- * possible object is
- * {@link FormatList }
- *
- */
- public FormatList getFormatList() {
- return formatList;
- }
-
- /**
- * Sets the value of the formatList property.
- *
- * @param value
- * allowed object is
- * {@link FormatList }
- *
- */
- public void setFormatList(FormatList value) {
- this.formatList = value;
- }
-
- /**
- * Gets the value of the semaphoreId property.
- *
- * @return
- * possible object is
- * {@link String }
- *
- */
- public String getSemaphoreId() {
- return semaphoreId;
- }
-
- /**
- * Sets the value of the semaphoreId property.
- *
- * @param value
- * allowed object is
- * {@link String }
- *
- */
- public void setSemaphoreId(String value) {
- this.semaphoreId = value;
- }
-
-}
### ONAP Distributions
-Version 1.3.0
-- [Portal-19] Renaming the Group Id in the POM file to org.onap.portal.sdk
+Version 1.4.0
+- PORTAL-19 Rename Java package base to org.onap
+- PORTAL-42 Use OParent as parent POM
+- PORTAL-72 Address Sonar Scan code issues
+- PORTAL-90 Use approved ONAP license text
+
+Version 1.3.0, 28 August 2017
+- Portal-19 Renaming the Group Id in the POM file to org.onap.portal.sdk
Version 1.1.0
-- [Portal-7] Improvements added as part of the rebasing process
+- Portal-7 Improvements added as part of the rebasing process
Version 1.0.0
- Initial release
<parent>
<groupId>org.onap.portal.sdk</groupId>
<artifactId>epsdk-project</artifactId>
- <version>1.3.0-SNAPSHOT</version>
+ <version>1.4.0-SNAPSHOT</version>
</parent>
<!-- GroupId is inherited from parent -->
<artifactId>epsdk-app-common</artifactId>
<!-- Version is inherited from parent -->
<packaging>jar</packaging>
- <name>ECOMP Portal SDK Webapp Common Classes</name>
- <description>ECOMP Portal SDK Web Application common classes</description>
+ <name>ONAP Portal SDK Webapp Common Classes</name>
+ <description>ONAP Portal SDK Web Application common classes</description>
<url>https://wiki.onap.org/display/DW/Portal</url>
- <properties>
- <encoding>UTF-8</encoding>
- <springframework.version>4.2.0.RELEASE</springframework.version>
- <hibernate.version>4.3.11.Final</hibernate.version>
- <!-- Skip assembling the zip; assemble via mvn -Dskipassembly=false .. -->
- <skipassembly>true</skipassembly>
- <!-- Tests usually require some setup that maven cannot do, so skip. -->
- <skiptests>true</skiptests>
- <nexusproxy>https://nexus.onap.org</nexusproxy>
- <snapshotNexusPath>/content/repositories/snapshots/</snapshotNexusPath>
- <releaseNexusPath>/content/repositories/releases/</releaseNexusPath>
- </properties>
+ <!-- properties inherited from parent -->
- <repositories>
- <repository>
- <!-- Releases repository has ECOMP release artifacts -->
- <id>ecomp-releases</id>
- <name>OpenECOMP - Release Repository</name>
- <url>${nexusproxy}/${releaseNexusPath}</url>
- </repository>
- <repository>
- <!-- Snapshots repository has ECOMP snapshot artifacts -->
- <id>ecomp-snapshots</id>
- <name>OpenECOMP - Snapshot Repository</name>
- <url>${nexusproxy}/${snapshotNexusPath}</url>
- </repository>
- <repository>
- <id>oss-snapshots</id>
- <name>oss Central - Snapshots</name>
- <url>https://oss.sonatype.org/service/local/repositories/releases/content/</url>
- </repository>
- </repositories>
+ <!-- repositories inherited from parent -->
- <profiles>
- <!-- disable doclint, a new feature in Java 8, when generating javadoc -->
- <profile>
- <id>doclint-java8-disable</id>
- <activation>
- <jdk>[1.8,)</jdk>
- </activation>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>2.10.4</version>
- <configuration>
- <additionalparam>-Xdoclint:none</additionalparam>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
+ <!-- profiles inherited from parent -->
<build>
--- /dev/null
+/*
+ *
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+public class AdminController {
+ @Controller
+ @RequestMapping("/")
+ public class AngularSinglePageController extends RestrictedBaseController {
+
+ @RequestMapping(value = { "/admin" }, method = RequestMethod.GET)
+ public ModelAndView view(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ return new ModelAndView("admin", "model", model);
+ }
+
+ @RequestMapping(value = { "/admin2" }, method = RequestMethod.GET)
+ public ModelAndView adminView(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ return new ModelAndView("admin2", "model", model);
+ }
+
+
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+@Controller
+@RequestMapping("/")
+public class AngularAdminController extends RestrictedBaseController{
+
+ @RequestMapping(value = {"/userProfile" }, method = RequestMethod.GET)
+ public ModelAndView view(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+
+ return new ModelAndView("user_profile_list","model", model);
+ }
+
+ @RequestMapping(value = {"/admin" }, method = RequestMethod.GET)
+ public ModelAndView adminView(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+
+ return new ModelAndView(getViewName(),"model", model);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+/**
+ * Controller for welcome view. The view is restricted to authenticated users.
+ * The view name defaults to the request name with no suffix, "bootstrap_sample", which
+ * resolves to page welcome.jsp.
+ */
+@Controller
+@RequestMapping("/")
+public class BootstrapSampleController extends RestrictedBaseController {
+ @RequestMapping(value = { "/bootstrap_sample" }, method = RequestMethod.GET)
+ public ModelAndView welcome(HttpServletRequest request) {
+ final String defaultViewName = null;
+ return new ModelAndView(defaultViewName);
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.jcs.JCS;
+import org.apache.jcs.admin.CacheRegionInfo;
+import org.apache.jcs.admin.JCSAdminBean;
+import org.apache.jcs.engine.behavior.ICacheElement;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+
+@Controller
+@RequestMapping("/")
+public class CacheAdminController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CacheAdminController.class);
+
+ private JCSAdminBean jcsAdminBean = new JCSAdminBean();
+
+ @RequestMapping(value = { "/jcs_admin" }, method = RequestMethod.GET)
+ public ModelAndView cacheAdmin(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+
+ model.put("model", getRegions());
+
+ return new ModelAndView(getViewName(), model);
+ }
+
+ @RequestMapping(value = { "/get_regions" }, method = RequestMethod.GET)
+ public void getRegions(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ JsonMessage msg = new JsonMessage(getRegions().toString());
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getRegions failed", e);
+ }
+ }
+
+ @RequestMapping(value = { "/jcs_admin/clearRegion" }, method = RequestMethod.GET)
+ public void clearRegion(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ String cacheName = (String) request.getParameter("cacheName");
+ clearCacheRegion(cacheName);
+
+ response.setContentType("application/json");
+ PrintWriter out = response.getWriter();
+ out.write(getRegions().toString());
+ }
+
+ @RequestMapping(value = { "/jcs_admin/clearAll" }, method = RequestMethod.GET)
+ public void clearAll(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ clearAllRegions();
+
+ response.setContentType("application/json");
+ PrintWriter out = response.getWriter();
+ out.write(getRegions().toString());
+ }
+
+ @RequestMapping(value = { "/jcs_admin/clearItem" }, method = RequestMethod.GET)
+ public void clearItem(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ String keyName = (String) request.getParameter("keyName");
+ String cacheName = (String) request.getParameter("cacheName");
+ clearCacheRegionItem(cacheName, keyName);
+
+ response.setContentType("application/json");
+ PrintWriter out = response.getWriter();
+ out.write(getRegions().toString());
+ }
+
+ @RequestMapping(value = { "/jcs_admin/showItemDetails" }, method = RequestMethod.GET)
+ public void showItemDetails(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ String cacheName = (String) request.getParameter("cacheName");
+ String keyName = (String) request.getParameter("keyName");
+ String details = null;
+
+ try {
+ details = getItemDetails(cacheName, keyName);
+ } catch (Exception e) {
+ details = "There was an error retrieving the region details. Please try again.";
+ logger.error(EELFLoggerDelegate.errorLogger, "showItemDetails failed for cache name " + cacheName, e);
+ }
+ JSONObject j = new JSONObject(details);
+ response.setContentType("application/json");
+ // response.setContentType("text/plain");
+ PrintWriter out = response.getWriter();
+ out.write(j.toString());
+ }
+
+ @RequestMapping(value = { "/jcs_admin/showRegionDetails" }, method = RequestMethod.GET)
+ public void showRegionDetails(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ String cacheName = (String) request.getParameter("cacheName");
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ String details = getRegionStats(cacheName);
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(details));
+ JSONObject j = new JSONObject(msg);
+ response.setContentType("application/json");
+ PrintWriter out = response.getWriter();
+ out.write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "showRegionDetailed failed for cache name " + cacheName, e);
+ return;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public JSONArray getRegions() {
+ LinkedList<CacheRegionInfo> regions = null;
+ JSONArray ja = new JSONArray();
+ try {
+ regions = getJcsAdminBean().buildCacheInfo();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
+ for (CacheRegionInfo cri : regions) {
+ if (cri.getCache().getCacheName() != null && !cri.getCache().getCacheName().equals("[object Object]")) {
+ JSONObject jo = new JSONObject();
+ jo.put("cacheName", cri.getCache().getCacheName());
+ jo.put("size", cri.getCache().getSize());
+ jo.put("byteCount", cri.getByteCount());
+ jo.put("status", cri.getStatus());
+ jo.put("hitCountRam", cri.getCache().getHitCountRam());
+ jo.put("hitCountAux", cri.getCache().getHitCountAux());
+ jo.put("missCountNotFound", cri.getCache().getMissCountNotFound());
+ jo.put("missCountExpired", cri.getCache().getMissCountExpired());
+ jo.put("items",
+ new JSONArray(mapper.writeValueAsString(getRegionItems(cri.getCache().getCacheName()))));
+ ja.put(jo);
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getRegions failed", e);
+ }
+
+ return ja;
+ }
+
+ private String getRegionStats(String cacheName) throws Exception {
+ String stats = "";
+
+ JCS cache = JCS.getInstance(cacheName);
+ stats = cache.getStats();
+
+ return stats;
+ }
+
+ private String getItemDetails(String cacheName, String keyName) throws Exception {
+ String details = "";
+
+ JCS cache = JCS.getInstance(cacheName);
+ ICacheElement element = cache.getCacheElement(keyName);
+
+ if (element != null) {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
+ details = mapper.writeValueAsString(element);
+ }
+
+ return details;
+ }
+
+ @SuppressWarnings("rawtypes")
+ private List getRegionItems(String cacheName) {
+ List items = null;
+
+ try {
+ items = getJcsAdminBean().buildElementInfo(cacheName);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getRegionItems failed for cache name " + cacheName, e);
+ }
+ return items;
+ }
+
+ private void clearAllRegions() {
+ try {
+ getJcsAdminBean().clearAllRegions();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "clearAllRegions faield", e);
+ }
+ }
+
+ private void clearCacheRegion(String cacheName) {
+ try {
+ getJcsAdminBean().clearRegion(cacheName);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "clearCacheRegion failed for cache name " + cacheName, e);
+ }
+ }
+
+ private void clearCacheRegionItem(String cacheName, String keyName) {
+ try {
+ getJcsAdminBean().removeItem(cacheName, keyName);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "clearCacheRegionItem failed for key name " + keyName, e);
+ }
+ }
+
+ public JCSAdminBean getJcsAdminBean() {
+ return jcsAdminBean;
+ }
+
+ public void setJcsAdminBean(JCSAdminBean jcsAdminBean) {
+ this.jcsAdminBean = jcsAdminBean;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.App;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.aspect.AuditLog;
+import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.rest.FavoritesClient;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.service.AppService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+
+@Controller
+@RequestMapping("/")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@AuditLog
+public class FavoritesController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FavoritesController.class);
+
+ @Autowired
+ private AppService appService;
+
+ /**
+ * Makes the REST API call to Portal Back-end and retrieves Favorite menu
+ * items for the currently logged in user.
+ *
+ * @param request
+ * @param response
+ */
+ @RequestMapping(value = { "/get_favorites" }, method = RequestMethod.GET)
+ public void getFavorites(HttpServletRequest request, HttpServletResponse response) {
+ String appName = "";
+ String requestId = "";
+ String appUserName = "";
+ String decryptedPwd = "";
+
+ try {
+ HttpSession session = request.getSession();
+ User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
+ if (user == null || user.getId() == null) {
+ logger.info(EELFLoggerDelegate.errorLogger,
+ ("Http request did not contain user info, cannot retrieve favorites."));
+
+ response.setContentType("application/json");
+ JSONArray jsonResponse = new JSONArray();
+ JSONObject error = new JSONObject();
+ error.put("error", "Http request did not contain user info, cannot retrieve favorites.");
+ jsonResponse.put(error);
+ response.getWriter().write(jsonResponse.toString());
+ } else {
+ logger.info(EELFLoggerDelegate.errorLogger,
+ "Retrieving Favorites for the user '" + MDC.get(SystemProperties.MDC_LOGIN_ID) + "'.");
+
+ App app = appService.getDefaultApp();
+ if (app!=null) {
+ appName = app.getName();
+ appUserName = app.getUsername();
+ try{
+ decryptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: " + e.getMessage());
+ }
+ } else {
+ logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database.");
+ appName = SystemProperties.SDK_NAME;
+ }
+ requestId = MDC.get(MDC_KEY_REQUEST_ID);
+
+ String jsonResponse = FavoritesClient.getFavorites(MDC.get(SystemProperties.MDC_LOGIN_ID), appName, requestId, appUserName, decryptedPwd);
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "FavoritesMenu response: " + jsonResponse);
+
+ response.setContentType("application/json");
+ response.getWriter().write(jsonResponse);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred in FavoritesController.getFavorites while performing get_favorites. Details: "
+ + e.getMessage(), AlarmSeverityEnum.MINOR);
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.Menu;
+import org.onap.portalsdk.core.domain.MenuData;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.FnMenuService;
+import org.onap.portalsdk.core.service.FunctionalMenuListService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * A controller for Admin to add/edit/delete menu items from FN_MENU.
+ */
+
+@Controller
+@RequestMapping("/")
+public class FnMenuController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnMenuController.class);
+
+ @Autowired
+ FnMenuService service;
+
+ @Autowired
+ FunctionalMenuListService functionalMenuListService;
+
+ private String viewName;
+
+ @RequestMapping(value = { "/admin_fn_menu/get_parent_list" }, method = RequestMethod.GET)
+ public void getParentList(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ response.getWriter().write(mapper.writeValueAsString(service.getParentList()));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getParentListFailed", e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ }
+
+ @RequestMapping(value = { "/admin_fn_menu/get_function_cd_list" }, method = RequestMethod.GET)
+ public void getFunctionCDList(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ response.getWriter().write(mapper.writeValueAsString(functionalMenuListService.getFunctionCDList(request)));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getFunctionCDList", e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+
+ }
+
+ @RequestMapping(value = { "/admin_fn_menu" }, method = RequestMethod.GET)
+ public void getFnMenuList(HttpServletRequest request, HttpServletResponse response) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ List<MenuData> temp = null;
+ List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>();
+ List<MenuData> parentList = new ArrayList<>();
+
+ try {
+ temp = service.getFnMenuItems();
+ for (MenuData menu : temp) {
+ MenuData parentData = new MenuData();
+ parentData.setId(menu.getId());
+ parentData.setLabel(menu.getLabel());
+ if (menu.getParentMenu() != null) {
+ parentData.setParentId(menu.getParentMenu().getId());
+ }
+ parentData.setAction(menu.getAction());
+ parentData.setFunctionCd(menu.getFunctionCd());
+ parentData.setImageSrc(menu.getImageSrc());
+ parentData.setSortOrder(menu.getSortOrder());
+ parentData.setActive(menu.isActive());
+ parentData.setServlet(menu.getServlet());
+ parentData.setQueryString(menu.getQueryString());
+ parentData.setExternalUrl(menu.getExternalUrl());
+ parentData.setTarget(menu.getTarget());
+ parentData.setMenuSetCode(menu.getMenuSetCode());
+ parentData.setSeparator(menu.isSeparator());
+ parentData.setImageSrc(menu.getImageSrc());
+ parentList.add(parentData);
+ List<MenuData> tempList = new ArrayList<MenuData>();
+ // int countChildAction = 0;
+ /*
+ * for(Object o:menu.getChildMenus()){ Menu m = (Menu)o; Menu
+ * data = new Menu(); data.setId(m.getId());
+ * data.setLabel(m.getLabel()); data.setAction(m.getAction());
+ * data.setImageSrc(m.getImageSrc()); tempList.add(data); }
+ */
+ childItemList.add(tempList);
+ }
+ model.put("fnMenuItems", parentList);
+ // JsonMessage msg = new
+ // JsonMessage(mapper.writeValueAsString(parentList),mapper.writeValueAsString(childItemList),"none");
+
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getFnMenuList failed", e);
+ }
+
+ }
+
+ @RequestMapping(value = { "/admin_fn_menu/updateFnMenu" }, method = RequestMethod.POST)
+ public ModelAndView updateFnMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {
+
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ Menu fnMenuItem = mapper.readValue(root.get("availableFnMenuItem").toString(), Menu.class);
+
+ service.saveFnMenu(fnMenuItem);
+ request.getSession()
+ .removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
+ request.getSession().removeAttribute(SystemProperties.LEFT_MENU_CHILDREND);
+ request.getSession().removeAttribute(SystemProperties.LEFT_MENU_PARENT);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(service.getMenuItem(fnMenuItem.getId()));
+
+ out.write(responseString);
+
+ return null;
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "updateFnMenu failed", e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+
+ }
+
+ @RequestMapping(value = { "/admin_fn_menu/removeMenuItem" }, method = RequestMethod.POST)
+ public ModelAndView removeFnMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {
+
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ Menu fnMenuItem = mapper.readValue(root.get("fnMenuItem").toString(), Menu.class);
+ Menu fnMenuItemRow = service.getMenuItemRow(fnMenuItem.getId());
+
+ service.removeMenuItem(fnMenuItemRow);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(service.getMenuItem(fnMenuItem.getId()));
+ out.write(responseString);
+
+ return null;
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "removeFnMenu failed", e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+
+ }
+
+ public String getViewName() {
+ return viewName;
+ }
+
+ public void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
+
+import java.io.IOException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.App;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.aspect.AuditLog;
+import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.rest.FunctionalMenuClient;
+import org.onap.portalsdk.core.onboarding.ueb.UebException;
+import org.onap.portalsdk.core.onboarding.ueb.UebManager;
+import org.onap.portalsdk.core.onboarding.ueb.UebMsg;
+import org.onap.portalsdk.core.onboarding.ueb.UebMsgTypes;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+import org.onap.portalsdk.core.service.AppService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+
+@Controller
+@RequestMapping("/")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+public class FuncMenuController extends RestrictedBaseController{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FuncMenuController.class);
+
+ @Autowired
+ private AppService appService;
+
+ @AuditLog
+ @RequestMapping(value = {"/get_functional_menu" }, method = RequestMethod.GET)
+ public void functionalMenu(HttpServletRequest request, HttpServletResponse response) {
+
+ User user = UserUtils.getUserSession(request);
+ //JSONArray validMenu = new JSONArray("[{\"menuId\":140,\"column\":1,\"text\":\"RT SDK Menu\",\"parentMenuId\":139,\"url\":\"http://www.cnn.com\"},{\"menuId\":139,\"column\":1,\"text\":\"RT Menu\",\"parentMenuId\":11,\"url\":\"\"},{\"menuId\":11,\"column\":1,\"text\":\"Product Design\",\"parentMenuId\":1,\"url\":\"\"},{\"menuId\":1,\"column\":1,\"text\":\"Design\",\"url\":\"\"}]");
+
+ try {
+ if ( user != null ) {
+ String useRestForFunctionalMenu = PortalApiProperties.getProperty(PortalApiConstants.USE_REST_FOR_FUNCTIONAL_MENU);
+ String funcMenuJsonString = "";
+ if (useRestForFunctionalMenu==null || useRestForFunctionalMenu=="" || useRestForFunctionalMenu.equalsIgnoreCase("false")) {
+ logger.info(EELFLoggerDelegate.errorLogger, "Making use of UEB communication and Requesting functional menu for user " + user.getOrgUserId());
+ funcMenuJsonString = getFunctionalMenu(user.getOrgUserId());
+ } else {
+ funcMenuJsonString = getFunctionalMenuViaREST(user.getOrgUserId());
+ }
+ response.setContentType("application/json");
+ response.getWriter().write(funcMenuJsonString);
+ } else {
+ logger.info(EELFLoggerDelegate.errorLogger, "Http request did not contain user info, cannot retrieve functional menu");
+ response.setContentType("application/json");
+ JSONArray jsonResponse = new JSONArray();
+ JSONObject error = new JSONObject();
+ error.put("error","Http request did not contain user info, cannot retrieve functional menu");
+ jsonResponse.put(error);
+ response.getWriter().write(jsonResponse.toString());
+ }
+ } catch (Exception e) {
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application/json");
+ JSONArray jsonResponse = new JSONArray();
+ JSONObject error = new JSONObject();
+ try {
+ if ( null == e.getMessage() ) {
+ error.put("error","No menu data");
+ } else {
+ error.put("error",e.getMessage());
+ }
+ jsonResponse.put(error);
+ response.getWriter().write(jsonResponse.toString());
+ logger.error(EELFLoggerDelegate.errorLogger, "Error getting functional_menu: " + e.getMessage(),AlarmSeverityEnum.MAJOR);
+ } catch (IOException e1) {
+ e1.printStackTrace();
+ }
+ }
+
+ }
+
+ //--------------------------------------------------------------------------
+ // Makes a synchronous call to ECOMP Portal to get the JSON file that
+ // contains the contents of the functional menu. The JSON file will be
+ // in the payload of the returned UEB message.
+ //--------------------------------------------------------------------------
+ private String getFunctionalMenu(String userId) throws UebException
+ {
+ String returnString = null;
+ UebMsg funcMenuUebMsg = null;
+ UebMsg msg = new UebMsg();
+ msg.putMsgType(UebMsgTypes.UEB_MSG_TYPE_GET_FUNC_MENU);
+ msg.putUserId(userId);
+ funcMenuUebMsg = UebManager.getInstance().requestReply(msg);
+ if (funcMenuUebMsg != null) {
+ if (funcMenuUebMsg.getPayload().startsWith("Error:")) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenu received an error in UEB msg = " + funcMenuUebMsg.getPayload());
+ } else {
+ returnString = funcMenuUebMsg.getPayload();
+ }
+ }
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenu response: " + returnString);
+
+ return returnString;
+ }
+
+ private String getFunctionalMenuViaREST(String userId) {
+ String appName = "";
+ String requestId = "";
+ String appUserName = "";
+ String decryptedPwd = "";
+
+ logger.info(EELFLoggerDelegate.debugLogger, "Making use of REST API communication and Requesting functional menu for user " + userId);
+
+ App app = appService.getDefaultApp();
+ if (app!=null) {
+ appName = app.getName();
+ appUserName = app.getUsername();
+ try{
+ decryptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: " + e.toString());
+ }
+ } else {
+ logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database.");
+ appName = SystemProperties.SDK_NAME;
+ }
+ requestId = MDC.get(MDC_KEY_REQUEST_ID);
+
+ String fnMenu = null;
+ try {
+ fnMenu = FunctionalMenuClient.getFunctionalMenu(userId, appName, requestId, appUserName, decryptedPwd);
+ }catch(Exception ex) {
+ fnMenu = "Failed to get functional menu: " + ex.toString();
+ }
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenu response: {}", fnMenu);
+
+ return fnMenu;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.portalsdk.core.controller.UnRestrictedBaseController;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import org.springframework.web.servlet.ModelAndView;
+
+@Controller
+@RequestMapping("/")
+public class LogoutController extends UnRestrictedBaseController{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LogoutController.class);
+
+ private User user;
+
+ /**
+ * @param request
+ * @param response
+ * @return modelView
+ *
+ * globalLogout will invalid the current application session, then redirects to portal logout
+ */
+ @RequestMapping(value = {"/logout.htm" }, method = RequestMethod.GET)
+ public ModelAndView globalLogout(HttpServletRequest request, HttpServletResponse response) {
+ ModelAndView modelView = null;
+ try{
+ chatRoomLogout(request);
+ request.getSession().invalidate();
+ String portalUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
+ String portalDomain = portalUrl.substring(0, portalUrl.lastIndexOf('/'));
+ String redirectUrl = portalDomain+"/logout.htm";
+ modelView = new ModelAndView("redirect:"+redirectUrl);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Logout Error: " + e.getMessage(),AlarmSeverityEnum.MAJOR);
+ }
+ return modelView;
+ }
+
+ /**
+ * @param request
+ * @param response
+ * @return modelView
+ *
+ * appLogout is a function that will invalid the current session (application logout) and redirects user to Portal.
+ */
+ @RequestMapping(value = {"/app_logout.htm" }, method = RequestMethod.GET)
+ public ModelAndView appLogout(HttpServletRequest request, HttpServletResponse response) {
+ ModelAndView modelView = null;
+ try{
+ chatRoomLogout(request);
+ modelView = new ModelAndView("redirect:"+PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL));
+ UserUtils.clearUserSession(request);
+ request.getSession().invalidate();
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Application Logout Error: " + e.getMessage(),AlarmSeverityEnum.MAJOR);
+ }
+ return modelView;
+ }
+
+
+ public void chatRoomLogout(HttpServletRequest request){
+ request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
+ setUser(UserUtils.getUserSession(request));
+ // if(getUser()!=null){
+ // Long login_IdLong = getUser().getId();
+ // String name = getUser().getFirstName();
+ // String login_IdStr = Long.toString(login_IdLong);
+ // }
+ //UserListName.getInstance().delUserName(name);
+ //UserListID.getInstance().delUserName(login_IdStr);
+ }
+
+ public User getUser() {
+ return user;
+ }
+
+ public void setUser(User user) {
+ this.user = user;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * This controller responds to a request for the web application manifest,
+ * returning a JSON with the information that was created at build time.
+ *
+ * Manifest entries have names with hyphens, which means Javascript code can't
+ * simply use the shorthand object.key; instead use object['key'].
+ */
+@RestController
+@RequestMapping("/")
+public class ManifestController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ManifestController.class);
+
+ /**
+ * Required to obtain the webapp manifest.
+ */
+ @Autowired
+ private ServletContext context;
+
+ /** Path to resource on classpath */
+ private final String MANIFEST_RESOURCE_PATH = "/META-INF/MANIFEST.MF";
+
+ /**
+ * Gets the content of the webapp manifest file META-INF/MANIFEST.MF.
+ *
+ * @return Attributes object with key-value pairs from the manifest
+ * @throws IOException
+ */
+ private Attributes getWebappManifest() throws IOException {
+ // Manifest is formatted as Java-style properties
+ InputStream inputStream = context.getResourceAsStream(MANIFEST_RESOURCE_PATH);
+ if (inputStream == null)
+ throw new IOException("getWebappManifest: failed to get resource at path " + MANIFEST_RESOURCE_PATH);
+ Manifest manifest = new Manifest(inputStream);
+ inputStream.close();
+ return manifest.getMainAttributes();
+ }
+
+ /**
+ * Gets the webapp manifest contents as a JSON object.
+ *
+ * @param request
+ * @return A map of key-value pairs. On success:
+ *
+ * <pre>
+ * {
+ * "key1": "value1",
+ * "key2": "value2"
+ * }
+ * </pre>
+ *
+ * On failure:
+ *
+ * <pre>
+ * { "error": "message" }
+ * </pre>
+ */
+ @RequestMapping(value = { "/manifest" }, method = RequestMethod.GET, produces = "application/json")
+ @ResponseBody
+ public Map<Object, Object> getManifest(HttpServletRequest request) {
+ try {
+ Attributes attributes = getWebappManifest();
+ return attributes;
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getManifest failed", ex);
+ Map<Object, Object> response = new HashMap<Object, Object>();
+ response.put("error", "failed to get manifest: " + ex.toString());
+ return response;
+ }
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.MenuData;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+import org.onap.portalsdk.core.restful.client.SharedContextRestClient;
+import org.onap.portalsdk.core.restful.domain.SharedContext;
+import org.onap.portalsdk.core.service.FnMenuService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+public class MenuListController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MenuListController.class);
+
+ @Autowired
+ private FnMenuService fnMenuService;
+ @Autowired
+ private SharedContextRestClient sharedContextRestClient;
+
+ /**
+ *
+ * Gets Menu items and stores into session.
+ *
+ * @param request
+ * @param response
+ */
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value = { "/get_menu" }, method = RequestMethod.GET)
+ public void getMenu(HttpServletRequest request, HttpServletResponse response) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getMenu begins");
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ Set<MenuData> menuResult = null;
+ HttpSession session = request.getSession();
+ List<List<MenuData>> childItemList = (List<List<MenuData>>) session
+ .getAttribute(SystemProperties.LEFT_MENU_CHILDREND);
+ List<MenuData> parentList = (List<MenuData>) session.getAttribute(SystemProperties.LEFT_MENU_PARENT);
+ if (parentList == null || childItemList == null || parentList.size() == 0 || childItemList.size() == 0) {
+ childItemList = new ArrayList<List<MenuData>>();
+ parentList = new ArrayList<MenuData>();
+ menuResult = (Set<MenuData>) session
+ .getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
+ fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult);
+ logger.debug(EELFLoggerDelegate.debugLogger, "storing leftmenu items into session");
+ session.setAttribute(SystemProperties.LEFT_MENU_PARENT, parentList);
+ session.setAttribute(SystemProperties.LEFT_MENU_CHILDREND, childItemList);
+ }
+ String userName = (String) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(parentList),
+ mapper.writeValueAsString(childItemList), userName);
+ JSONObject j = new JSONObject(msg);
+ response.setContentType("application/json");
+ response.getWriter().write(j.toString());
+ logger.debug(EELFLoggerDelegate.debugLogger, "getMenu ends");
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getMenu failed", e);
+ }
+ }
+
+ /**
+ *
+ * Gets app name from system.properties file.
+ *
+ * @param request
+ * @param response
+ */
+ @RequestMapping(value = { "/get_app_name" }, method = RequestMethod.GET)
+ public void getAppName(HttpServletRequest request, HttpServletResponse response) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getAppName begins");
+ HttpSession session = request.getSession(true);
+ try {
+ String appName = (String) session
+ .getAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME));
+ if (appName != null && appName.equals("app_display_name")) {
+ appName = "";
+ }
+ JsonMessage msg = new JsonMessage(appName);
+ JSONObject j = new JSONObject(msg);
+ response.setContentType("application/json");
+ response.getWriter().write(j.toString());
+ logger.debug(EELFLoggerDelegate.debugLogger, "getAppName ends");
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getAppName failed", e);
+ }
+ }
+
+ /**
+ * Apparently unused?
+ *
+ * @param request
+ * @return Map with childItemList and parentList keys, associated values.
+ */
+ @SuppressWarnings("unchecked")
+ @ModelAttribute("menu")
+ public Map<String, Object> getLeftMenuJSP(HttpServletRequest request) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getLeftMenuJSP begins");
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String, Object> model = new HashMap<String, Object>();
+ try {
+ HttpSession session = request.getSession();
+ List<List<MenuData>> childItemList = (List<List<MenuData>>) session
+ .getAttribute(SystemProperties.LEFT_MENU_CHILDREND);
+ List<MenuData> parentList = (List<MenuData>) session.getAttribute(SystemProperties.LEFT_MENU_PARENT);
+ if (parentList == null || childItemList == null) {
+ childItemList = new ArrayList<List<MenuData>>();
+ parentList = new ArrayList<MenuData>();
+ Set<MenuData> menuResult = (Set<MenuData>) session
+ .getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
+ fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult);
+ session.setAttribute(SystemProperties.LEFT_MENU_PARENT, parentList);
+ session.setAttribute(SystemProperties.LEFT_MENU_CHILDREND, childItemList);
+ }
+ model.put("childItemList", mapper.writeValueAsString(childItemList));
+ model.put("parentList", mapper.writeValueAsString(parentList));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getLeftMenuJSP failed", e);
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "getLeftMenuJSP ends");
+ return model;
+ }
+
+ /**
+ * Answers requests for user information, which is fetched from the shared
+ * context at Portal.
+ *
+ * @param request
+ * @param response
+ */
+ @RequestMapping(value = { "/get_userinfo" }, method = RequestMethod.GET)
+ public void getUserInfo(HttpServletRequest request, HttpServletResponse response) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getUserInfo begins");
+ try {
+ String contextId = null;
+ if (request.getCookies() != null) {
+ for (Cookie ck : request.getCookies()) {
+ if (ck.getName().equalsIgnoreCase("EPService"))
+ contextId = ck.getValue();
+ }
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "getUserInfo: ContextId is : " + contextId);
+ List<SharedContext> sharedContextRes = sharedContextRestClient.getUserContext(contextId);
+ logger.debug(EELFLoggerDelegate.debugLogger, "getUserInfo: Shared Context Response is {}",
+ sharedContextRes);
+ Map<String, Object> model = new HashMap<String, Object>();
+ for (SharedContext sharedContext : sharedContextRes) {
+ model.put(sharedContext.getCkey(), sharedContext.getCvalue());
+ }
+ JSONObject j = new JSONObject(model);
+ response.setContentType("application/json");
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getUserInfo failed", e);
+ }
+ }
+
+ /**
+ * Get User information from app sessions
+ *
+ * @param request
+ * @param response
+ */
+ @RequestMapping(value = { "/get_topMenuInfo" }, method = RequestMethod.GET)
+ public void getTopMenu(HttpServletRequest request, HttpServletResponse response) {
+ @SuppressWarnings("unused")
+ boolean isAppCentralized = false;
+ HttpSession session = request.getSession();
+ try {
+ String userName = (String) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME));
+ String firstName = (String) session.getAttribute(SystemProperties.FIRST_NAME);
+ String lastName = (String) session.getAttribute(SystemProperties.LAST_NAME);
+ User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
+ Map<String, String> map = new HashMap<String, String>();
+ String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
+ String portalDomain = redirectUrl.substring(0, redirectUrl.lastIndexOf('/'));
+ String portalUrl = portalDomain + "/process_csp";
+ String getAccessUrl = portalDomain + "/get_access";
+ String contactUsLink = SystemProperties.getProperty(SystemProperties.CONTACT_US_LINK);
+ map.put("portalUrl", portalUrl);
+ map.put("contactUsLink", contactUsLink);
+ map.put("userName", userName);
+ map.put("firstName", firstName);
+ map.put("lastName", lastName);
+ map.put("userid", user.getOrgUserId());
+ map.put("email", user.getEmail());
+ map.put("getAccessUrl", getAccessUrl);
+ String roleAccessCentralized = PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED);
+ if (roleAccessCentralized != null && "remote".equals(roleAccessCentralized))
+ isAppCentralized = true;
+ map.put("isAppCentralized", Boolean.toString(isAppCentralized));
+ JSONObject j = new JSONObject(map);
+ response.setContentType("application/json");
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to serialize JSON", e);
+ }
+
+ }
+
+ @RequestMapping(value = { "/page_redirect" }, method = RequestMethod.GET)
+ public void pageRedirect(HttpServletRequest request, HttpServletResponse response) {
+ String pageToURL = null;
+ try {
+ String pageTo = request.getParameter("page");
+ if (pageTo.equals("contact"))
+ pageToURL = SystemProperties.getProperty(SystemProperties.CONTACT_US_LINK);
+ else if (pageTo.equals("access")) {
+ String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
+ String portalDomain = redirectUrl.substring(0, redirectUrl.lastIndexOf('/'));
+ pageToURL = portalDomain + "/get_access";
+ }
+ response.getWriter().write(pageToURL);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "pageRedirect failed", e);
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.command.PostSearchBean;
+import org.onap.portalsdk.core.command.support.SearchResult;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.Lookup;
+import org.onap.portalsdk.core.domain.Profile;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.LdapService;
+import org.onap.portalsdk.core.service.PostSearchService;
+import org.onap.portalsdk.core.service.ProfileService;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+public class PostSearchController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostSearchController.class);
+
+ @SuppressWarnings("rawtypes")
+ private static List sortByList = null;
+
+ @Autowired
+ private PostSearchService postSearchService;
+
+ @Autowired
+ private LdapService ldapService;
+
+ @Autowired
+ private ProfileService profileService;
+
+ @RequestMapping(value = { "/post_search" }, method = RequestMethod.GET)
+ public ModelAndView welcome(HttpServletRequest request,
+ @ModelAttribute("postSearchBean") PostSearchBean postSearchBean) {
+ Map<String, Object> model = new HashMap<String, Object>();
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ postSearchBean = new PostSearchBean();
+ model.put("profileList", mapper.writeValueAsString(postSearchBean.getSearchResult()));
+ model.put("postSearchBean", mapper.writeValueAsString(postSearchBean));
+ model.put("existingUsers", mapper.writeValueAsString(getExistingUsers()));
+ model.put("sortByList", mapper.writeValueAsString(getSortByList()));
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "welcome: failed to write JSON" + ex.getMessage());
+ }
+
+ return new ModelAndView(getViewName(), model);
+ }
+
+ @RequestMapping(value = { "/post_search_sample" }, method = RequestMethod.GET)
+ public void getPostSearchProfile(HttpServletRequest request, HttpServletResponse response,
+ @ModelAttribute("postSearchBean") PostSearchBean postSearchBean) {
+ Map<String, Object> model = new HashMap<String, Object>();
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ postSearchBean = new PostSearchBean();
+ model.put("profileList", mapper.writeValueAsString(postSearchBean.getSearchResult()));
+ model.put("postSearchBean", mapper.writeValueAsString(postSearchBean));
+ model.put("existingUsers", mapper.writeValueAsString(getExistingUsers()));
+ model.put("sortByList", mapper.writeValueAsString(getSortByList()));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getPostSearchProfile: failed to write JSON" + ex.getMessage());
+ }
+
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ private HashMap getExistingUsers() throws Exception {
+ HashMap existingUsers = new HashMap();
+
+ // get the list of user ids in the system
+ List<Profile> list = profileService.findAll();
+
+ if (list != null) {
+ Iterator<Profile> i = list.iterator();
+ while (i.hasNext()) {
+ Profile user = i.next();
+ String orgUserId = user.getOrgUserId(); // userid scalar
+ Long id = user.getId(); // id scalar
+ if (orgUserId != null)
+ existingUsers.put(orgUserId, id);
+ }
+ }
+ return existingUsers;
+ }
+
+ @RequestMapping(value = { "/post_search/search" }, method = RequestMethod.POST)
+ public ModelAndView search(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PostSearchBean postSearchBean = mapper.readValue(root.get("postSearchBean").toString(),
+ PostSearchBean.class);
+
+ postSearchBean.setSearchResult(loadSearchResultData(request, postSearchBean));
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(postSearchBean);
+ JSONObject j = new JSONObject("{postSearchBean: " + responseString + "}");
+
+ out.write(j.toString());
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "search: failed to send search result" + ex.getMessage());
+ }
+
+ return null;
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public static List getSortByList() {
+ if (sortByList == null) {
+ sortByList = new ArrayList();
+ sortByList.add(new Lookup("Last Name", "last_name"));
+ sortByList.add(new Lookup("First Name", "first_name"));
+ sortByList.add(new Lookup("HRID", "hrid"));
+ sortByList.add(new Lookup("SBCID", "sbcid"));
+ sortByList.add(new Lookup("Organization", "org_code"));
+ sortByList.add(new Lookup("Email", "email"));
+ } // if
+
+ return sortByList;
+ } // getSortByList
+
+ private SearchResult loadSearchResultData(HttpServletRequest request, PostSearchBean searchCriteria)
+ throws Exception {
+ return ldapService.searchPost(searchCriteria.getUser(), searchCriteria.getSortBy1(),
+ searchCriteria.getSortBy2(), searchCriteria.getSortBy3(), searchCriteria.getPageNo(),
+ searchCriteria.getNewDataSize(), UserUtils.getUserSession(request).getId().intValue());
+ }
+
+ @RequestMapping(value = { "/post_search/process" }, method = RequestMethod.POST)
+ public ModelAndView process(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
+ JsonNode root = mapper.readTree(request.getReader());
+ PostSearchBean postSearch = mapper.readValue(root.get("postSearchBean").toString(), PostSearchBean.class);
+ String errorMsg = "{}";
+ try{
+ postSearchService.process(request, postSearch);
+ postSearch.setSearchResult(loadSearchResultData(request, postSearch));
+ }catch(Exception e){
+ errorMsg=e.getMessage();
+ logger.error(EELFLoggerDelegate.errorLogger,"Exception occurred while performing PostSearchController.process. Details:", e);
+ }
+ logger.info(EELFLoggerDelegate.auditLogger, "Import new user from webphone ");
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String postSearchString = mapper.writeValueAsString(postSearch);
+ JSONObject j = new JSONObject("{postSearchBean: " + postSearchString + ",existingUsers: "
+ + mapper.writeValueAsString(getExistingUsers()) + ",errorMsg:"+errorMsg+"}");
+
+ out.write(j.toString());
+
+ return null;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.UnsupportedEncodingException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.RoleService;
+import org.onap.portalsdk.core.service.UserProfileService;
+import org.onap.portalsdk.core.service.UserService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.AppUtils;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+public class ProfileController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProfileController.class);
+
+ @Autowired
+ UserProfileService service;
+
+ @Autowired
+ UserService userService;
+
+ @Autowired
+ RoleService roleService;
+
+ private String viewName;
+
+ @RequestMapping(value = { "/profile" }, method = RequestMethod.GET)
+ public ModelAndView profile(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+
+ User profile = null;
+ Long profileId = null;
+
+ if (request.getRequestURI().indexOf("self_profile.htm") > -1) {
+ profile = UserUtils.getUserSession(request);
+ profileId = profile.getId();
+ } else {
+ profileId = Long.parseLong(request.getParameter("profile_id"));
+ profile = (User) userService.getUser(String.valueOf(profileId));
+ }
+
+ try {
+ model.put("stateList", mapper.writeValueAsString(getStates()));
+ model.put("countries", mapper.writeValueAsString(getCountries()));
+ model.put("timeZones", mapper.writeValueAsString(getTimeZones()));
+ model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles(user.getOrgUserId())));
+ model.put("profile", mapper.writeValueAsString(profile));
+ model.put("profileId", mapper.writeValueAsString(profileId));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "profile: failed to write JSON", e);
+ }
+ return new ModelAndView("profile", "model", model);
+ }
+
+ @RequestMapping(value = { "/self_profile" }, method = RequestMethod.GET)
+ public ModelAndView self_profile(HttpServletRequest request) throws Exception{
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+
+ User profile = null;
+ Long profileId = null;
+ User user = UserUtils.getUserSession(request);
+
+ profile = UserUtils.getUserSession(request);
+ try {
+ model.put("stateList", mapper.writeValueAsString(getStates()));
+ model.put("countries", mapper.writeValueAsString(getCountries()));
+ model.put("timeZones", mapper.writeValueAsString(getTimeZones()));
+ model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles(user.getOrgUserId())));
+ model.put("profile", mapper.writeValueAsString(profile));
+ model.put("profileId", mapper.writeValueAsString(profileId));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "self_profile: failed to write JSON" + e.getMessage());
+ }
+ return new ModelAndView("profile", "model", model);
+ }
+
+ @RequestMapping(value = { "/get_self_profile" }, method = RequestMethod.GET)
+ public void getSelfProfile(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+
+ User profile = null;
+ Long profileId = null;
+
+ profile = (User) UserUtils.getUserSession(request);
+ try {
+ model.put("stateList", mapper.writeValueAsString(getStates()));
+ model.put("countries", mapper.writeValueAsString(getCountries()));
+ model.put("timeZones", mapper.writeValueAsString(getTimeZones()));
+ model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles(user.getOrgUserId())));
+ model.put("profile", mapper.writeValueAsString(profile));
+ model.put("profileId", mapper.writeValueAsString(profileId));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getSelfProfile: failed to write JSON" + e.getMessage());
+ }
+
+ }
+
+ @RequestMapping(value = { "/get_profile" }, method = RequestMethod.GET)
+ public void GetUser(HttpServletRequest request, HttpServletResponse response) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ User user = UserUtils.getUserSession(request);
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ User profile = null;
+ Long profileId = null;
+ if (request.getRequestURI().indexOf("self_profile.htm") > -1) {
+ profile = UserUtils.getUserSession(request);
+ profileId = profile.getId();
+ } else {
+ profileId = Long.parseLong(request.getParameter("profile_id"));
+ profile = (User) userService.getUser(String.valueOf(profileId));
+
+ }
+ model.put("stateList", mapper.writeValueAsString(getStates()));
+ model.put("countries", mapper.writeValueAsString(getCountries()));
+ model.put("timeZones", mapper.writeValueAsString(getTimeZones()));
+ model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles(user.getOrgUserId())));
+ model.put("profile", mapper.writeValueAsString(profile));
+ model.put("profileId", mapper.writeValueAsString(profileId));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "GetUser: failed to write JSON" + e.getMessage());
+ }
+ }
+
+ @RequestMapping(value = { "/profile/saveProfile" }, method = RequestMethod.POST)
+ public ModelAndView saveProfile(HttpServletRequest request, HttpServletResponse response) {
+ logger.info(EELFLoggerDelegate.debugLogger, "ProfileController.save");
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ User user = mapper.readValue(root.get("profile").toString(), User.class);
+
+ String selectedCountry = mapper.readValue(root.get("selectedCountry").toString(), String.class);
+ String selectedState = mapper.readValue(root.get("selectedState").toString(), String.class);
+ String selectedTimeZone = mapper.readValue(root.get("selectedTimeZone").toString(), String.class);
+
+ Long profileId = Long.parseLong(request.getParameter("profile_id"));
+
+ User domainUser = (User) userService.getUser(String.valueOf(profileId));
+ // user.setRoles(domainUser.getRoles());
+ user.setPseudoRoles(domainUser.getPseudoRoles());
+ user.setUserApps(domainUser.getUserApps());
+ if (!selectedCountry.equals("")) {
+ user.setCountry(selectedCountry);
+ }
+ if (!selectedState.equals("")) {
+ user.setState(selectedState);
+ }
+ if (!selectedTimeZone.equals("")) {
+ user.setTimeZoneId(Long.parseLong(selectedTimeZone));
+ }
+ service.saveUser(user);
+ logger.info(EELFLoggerDelegate.auditLogger, "Save user's profile for user " + profileId);
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ PrintWriter out = response.getWriter();
+ out.write("" + profileId);
+ return null;
+ } catch (Exception e) {
+ response.setCharacterEncoding("UTF-8");
+ try {
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ } catch (IOException e1) {
+ logger.error(EELFLoggerDelegate.errorLogger, "saveProfile: failed to write", e1);
+ }
+ return null;
+ }
+ }
+
+ @RequestMapping(value = { "/profile/removeRole" }, method = RequestMethod.POST)
+ public ModelAndView removeRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
+
+ logger.info(EELFLoggerDelegate.debugLogger, "ProfileController.save");
+ try {
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ Role role = mapper.readValue(root.get("role").toString(), Role.class);
+
+ String profileId = request.getParameter("profile_id");
+
+ User domainUser = (User) userService.getUser(profileId);
+
+ domainUser.removeRole(role.getId());
+
+ service.saveUser(domainUser);
+ /*If adding new roles on the current logged in user, we need to update the user value in session*/
+ if(UserUtils.getUserId(request)==Integer.valueOf(profileId)){
+ HttpSession session = request.getSession(true);
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), domainUser);
+ }
+ logger.info(EELFLoggerDelegate.auditLogger, "Remove role " + role.getId() + " from user " + profileId);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+
+ Map<String, Object> model = new HashMap<String, Object>();
+ model.put("profile", mapper.writeValueAsString(domainUser));
+ JSONObject j = new JSONObject(mapper.writeValueAsString(domainUser));
+
+ out.write(j.toString());
+
+ return null;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "removeRole" + e.getMessage());
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ return null;
+ }
+
+ }
+
+ @RequestMapping(value = { "/profile/addNewRole" }, method = RequestMethod.POST)
+ public ModelAndView addNewRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
+
+ logger.info(EELFLoggerDelegate.debugLogger, "ProfileController.save" );
+ try {
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ Role role = mapper.readValue(root.get("role").toString(), Role.class);
+ String profileId = request.getParameter("profile_id");
+ User domainUser = (User) userService.getUser(profileId);
+ domainUser.addRole(role);
+ service.saveUser(domainUser);
+ /*If removing roles on the current logged in user, we need to update the user value in session*/
+ if(UserUtils.getUserId(request)==Integer.valueOf(profileId)){
+ HttpSession session = request.getSession(true);
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), domainUser);
+ }
+ logger.info(EELFLoggerDelegate.auditLogger, "Add new role " + role.getName() + " to user " + profileId);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ Map<String, Object> model = new HashMap<String, Object>();
+ model.put("profile", mapper.writeValueAsString(domainUser));
+ JSONObject j = new JSONObject(mapper.writeValueAsString(domainUser));
+
+ out.write(j.toString());
+
+ return null;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "addNewRole" + e.getMessage());
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ return null;
+ }
+
+ }
+
+ public String getViewName() {
+ return viewName;
+ }
+
+ public void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public List getStates() {
+ return AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD");
+ }
+
+ @SuppressWarnings("rawtypes")
+ public List getCountries() {
+ return AppUtils.getLookupList("FN_LU_COUNTRY", "COUNTRY_CD", "COUNTRY", null, "COUNTRY");
+ }
+
+ @SuppressWarnings("rawtypes")
+ public List getTimeZones() {
+ return AppUtils.getLookupList("FN_LU_TIMEZONE", "TIMEZONE_ID", "TIMEZONE_NAME", null, "TIMEZONE_NAME");
+ }
+
+ @SuppressWarnings("rawtypes")
+ public List getAvailableRoles(String requestedLoginId) throws Exception {
+ return roleService.getAvailableRoles(requestedLoginId);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.MenuData;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.FnMenuService;
+import org.onap.portalsdk.core.service.UserProfileService;
+import org.onap.portalsdk.core.service.UserService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+public class ProfileSearchController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProfileSearchController.class);
+
+ @Autowired
+ private UserProfileService service;
+
+ @Autowired
+ UserService userService;
+
+ @Autowired
+ private FnMenuService fnMenuService;
+
+ @RequestMapping(value = { "/profile_search" }, method = RequestMethod.GET)
+ public ModelAndView profileSearch(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ List<User> profileList = null;
+ logger.info(EELFLoggerDelegate.applicationLogger, "Initiating ProfileSearch in ProfileSearchController");
+ try {
+ profileList = service.findAll();
+ model.putAll(setDashboardData(request));
+ model.put("profileList", mapper.writeValueAsString(profileList));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.applicationLogger, "profileSearch failed", e);
+ }
+ return new ModelAndView(getViewName(), "model", model);
+ }
+
+ @RequestMapping(value = { "/get_user" }, method = RequestMethod.GET)
+ public void getUser(HttpServletRequest request, HttpServletResponse response) {
+ logger.info(EELFLoggerDelegate.applicationLogger, "Initiating get_user in ProfileSearchController");
+ ObjectMapper mapper = new ObjectMapper();
+ List<User> profileList = null;
+ try {
+ profileList = service.findAll();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(profileList));
+ JSONObject j = new JSONObject(msg);
+ response.setContentType("application/json");
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.applicationLogger, "getUser failed", e);
+ }
+ }
+
+ @RequestMapping(value = { "/get_user_pagination" }, method = RequestMethod.GET)
+ public void getUserPagination(HttpServletRequest request, HttpServletResponse response) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ logger.info(EELFLoggerDelegate.applicationLogger, "Initiating get_user_pagination in ProfileSearchController");
+ int pageNum = Integer.parseInt(request.getParameter("pageNum"));
+ int viewPerPage = Integer.parseInt(request.getParameter("viewPerPage"));
+ List<User> profileList = null;
+ try {
+ profileList = service.findAll();
+ model.put("totalPage", (int) Math.ceil((double) profileList.size() / viewPerPage));
+ profileList = profileList.subList(
+ viewPerPage * (pageNum - 1) < profileList.size() ? viewPerPage * (pageNum - 1) : profileList.size(),
+ viewPerPage * pageNum < profileList.size() ? viewPerPage * pageNum : profileList.size());
+ model.put("profileList", mapper.writeValueAsString(profileList));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.setContentType("application/json");
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.applicationLogger, "getUserPagination failed", e);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private Map<String, Object> setDashboardData(HttpServletRequest request) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String, Object> model = new HashMap<String, Object>();
+ List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>();
+ List<MenuData> parentList = new ArrayList<MenuData>();
+ logger.info(EELFLoggerDelegate.applicationLogger, "Initiating setDashboardData in ProfileSearchController");
+ HttpSession session = request.getSession();
+ try {
+ Set<MenuData> menuResult = (Set<MenuData>) session
+ .getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
+ fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.applicationLogger, "setDashboardData failed", e);
+ }
+ model.put("childItemList", mapper.writeValueAsString(childItemList));
+ model.put("parentList", mapper.writeValueAsString(parentList));
+ return model;
+ }
+
+ @RequestMapping(value = { "/profile/toggleProfileActive" }, method = RequestMethod.GET)
+ public void toggleProfileActive(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ try {
+ logger.info(EELFLoggerDelegate.applicationLogger,
+ "Initiating toggleProfileActive in ProfileSearchController");
+ String userId = request.getParameter("profile_id");
+ User user = (User) userService.getUser(userId);
+ user.setActive(!user.getActive());
+ service.saveUser(user);
+ logger.info(EELFLoggerDelegate.auditLogger,
+ "Change active status for user " + user.getId() + " to " + user.getActive());
+ ObjectMapper mapper = new ObjectMapper();
+ response.setContentType("application/json");
+ PrintWriter out = response.getWriter();
+ out.write(mapper.writeValueAsString(user.getActive()));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.applicationLogger, "toggleProfileActive failed", e);
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.RoleFunction;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.aspect.EELFLoggerAdvice;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.RoleService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.ServletRequestUtils;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+
+@Controller
+@RequestMapping("/")
+public class RoleController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleController.class);
+
+ @Autowired
+ private RoleService roleService;
+
+ private String viewName;
+
+ @RequestMapping(value = { "/role" }, method = RequestMethod.GET)
+ public ModelAndView role(HttpServletRequest request) throws Exception {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+
+
+ Role role = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
+ logger.info("role_id" + role.getId());
+ try {
+ model.put("availableRoleFunctions", mapper.writeValueAsString(roleService.getRoleFunctions(user.getOrgUserId())));
+ model.put("availableRoles", mapper.writeValueAsString(roleService.getAvailableChildRoles(user.getOrgUserId(),role.getId())));
+ model.put("role", mapper.writeValueAsString(role));
+ } catch (Exception e) {
+ logger.error("role: failed", e);
+ logger.error(EELFLoggerDelegate.errorLogger, "role failed", e);
+ }
+ return new ModelAndView(getViewName(), model);
+ }
+
+ @RequestMapping(value = { "/get_role" }, method = RequestMethod.GET)
+ public void getRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+
+ Role role = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
+ logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + role.getId());
+ try {
+ model.put("availableRoleFunctions", mapper.writeValueAsString(roleService.getRoleFunctions(user.getOrgUserId())));
+ model.put("availableRoles", mapper.writeValueAsString(roleService.getAvailableChildRoles(user.getOrgUserId(),role.getId())));
+ model.put("role", mapper.writeValueAsString(role));
+
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
+ }
+
+ }
+
+ /**
+ * Creates a new role or updates an existing role.
+ *
+ * @param request
+ * @param response
+ * @return Always returns null.
+ * @throws IOException
+ * If the write to the result project fails
+ */
+ @RequestMapping(value = { "/role/saveRole" }, method = RequestMethod.POST)
+ public ModelAndView saveRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ JSONObject j = null;
+ User user = UserUtils.getUserSession(request);
+ logger.debug(EELFLoggerDelegate.debugLogger, "RoleController.save");
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ Role role = mapper.readValue(root.get("role").toString(), Role.class);
+
+ List<Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
+ TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
+
+ List<RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
+ TypeFactory.defaultInstance().constructCollectionType(List.class, RoleFunction.class));
+
+ Role domainRole = null;
+ if (role.getId() != null) {
+ doAuditLog("saveRole: updating existing role {}", role.getId());
+ domainRole = roleService.getRole(user.getOrgUserId(),role.getId());
+
+ domainRole.setName(role.getName());
+ domainRole.setPriority(role.getPriority());
+ } else {
+ doAuditLog("saveRole: creating new role", role.getName());
+ // check for existing role of same name
+ List<Role> roles = roleService.getAvailableRoles(user.getOrgUserId());
+ for (Role existRole : roles)
+ if (existRole.getName().equalsIgnoreCase(role.getName()))
+ throw new Exception("role already exists: " + existRole.getName());
+
+ domainRole = new Role();
+ domainRole.setName(role.getName());
+ domainRole.setPriority(role.getPriority());
+ if(role.getChildRoles() != null && role.getChildRoles().size() > 0 ){
+// if (role.getChildRoles().size() > 0 ) {
+ for (Object childRole : childRoles) {
+ domainRole.addChildRole((Role) childRole);
+ }
+// }
+ }
+ if(role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0){
+// if (role.getRoleFunctions().size() > 0) {
+ for (Object roleFunction : roleFunctions) {
+ domainRole.addRoleFunction((RoleFunction) roleFunction);
+ }
+// }
+ }
+ }
+
+ roleService.saveRole(user.getOrgUserId(),domainRole);
+
+ String responseString = mapper.writeValueAsString(domainRole);
+ j = new JSONObject("{role: " + responseString + "}");
+ } catch (Exception e) {
+ // Produce JSON error message
+ logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
+ j = new JSONObject("{error: '" + e.getMessage() + "'}");
+ }
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application/json");
+ PrintWriter out = response.getWriter();
+ out.write(j.toString());
+ return null;
+ }
+
+ @RequestMapping(value = { "/role/removeRoleFunction" }, method = RequestMethod.POST)
+ public ModelAndView removeRoleFunction(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ User user = UserUtils.getUserSession(request);
+ logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction");
+ try {
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class);
+
+ Role domainRole = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
+ doAuditLog("Remove role function {} from role {}", roleFunction.getCode(),
+ ServletRequestUtils.getIntParameter(request, "role_id", 0));
+
+ domainRole.removeRoleFunction(roleFunction.getCode());
+
+ roleService.saveRole(user.getOrgUserId(),domainRole);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application/json");
+ String responseString = mapper.writeValueAsString(domainRole);
+ JSONObject j = new JSONObject("{role: " + responseString + "}");
+ PrintWriter out = response.getWriter();
+ out.write(j.toString());
+ return null;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
+ response.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ return null;
+ }
+
+ }
+
+ @RequestMapping(value = { "/role/addRoleFunction" }, method = RequestMethod.POST)
+ public ModelAndView addRoleFunction(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ User user = UserUtils.getUserSession(request);
+ logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction");
+ try {
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class);
+
+ Role domainRole = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
+
+ domainRole.addRoleFunction(roleFunction);
+
+ roleService.saveRole(user.getOrgUserId(),domainRole);
+ doAuditLog("Add role function {} to role {}", roleFunction.getCode(),
+ ServletRequestUtils.getIntParameter(request, "role_id", 0));
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application/json");
+ String responseString = mapper.writeValueAsString(domainRole);
+ JSONObject j = new JSONObject("{role: " + responseString + "}");
+ PrintWriter out = response.getWriter();
+ out.write(j.toString());
+ return null;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
+ response.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ return null;
+ }
+
+ }
+
+ @RequestMapping(value = { "/role/removeChildRole" }, method = RequestMethod.POST)
+ public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ User user = UserUtils.getUserSession(request);
+ logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeChileRole");
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class);
+
+ Role domainRole = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
+
+ domainRole.removeChildRole(childRole.getId());
+ doAuditLog("remove child role {} from role {}", childRole.getId(),
+ ServletRequestUtils.getIntParameter(request, "role_id", 0));
+
+ roleService.saveRole(user.getOrgUserId(),domainRole);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application/json");
+ String responseString = mapper.writeValueAsString(domainRole);
+ JSONObject j = new JSONObject("{role: " + responseString + "}");
+ PrintWriter out = response.getWriter();
+ out.write(j.toString());
+ return null;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "removeChildRole failed", e);
+ response.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ return null;
+ }
+
+ }
+
+ @RequestMapping(value = { "/role/addChildRole" }, method = RequestMethod.POST)
+ public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ User user = UserUtils.getUserSession(request);
+ logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.addChileRole");
+ try {
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class);
+ long role_id = new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0));
+
+ Role domainRole = roleService.getRole(user.getOrgUserId(),role_id );
+
+ domainRole.addChildRole(childRole);
+
+ roleService.saveRole(user.getOrgUserId(),domainRole);
+ doAuditLog("Add child role {} to role {}", childRole.getId(),
+ ServletRequestUtils.getIntParameter(request, "role_id", 0));
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application/json");
+ String responseString = mapper.writeValueAsString(domainRole);
+ JSONObject j = new JSONObject("{role: " + responseString + "}");
+ PrintWriter out = response.getWriter();
+ out.write(j.toString());
+ return null;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "addChildRole failed", e);
+ response.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ return null;
+ }
+
+ }
+
+ /**
+ * Sets context with begin and end timestamps at current date & time, writes
+ * the specified message and parameters to the audit log, then removes the
+ * timestamps from context.
+ *
+ * @param message
+ * @param parameters
+ */
+ private void doAuditLog(String message, Object... parameters) {
+ final String currentDateTime = EELFLoggerAdvice.getCurrentDateTimeUTC();
+ // Set the MDC with audit properties
+ MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, currentDateTime);
+ MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, currentDateTime);
+ logger.info(EELFLoggerDelegate.auditLogger, message, parameters);
+ MDC.remove(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+ MDC.remove(SystemProperties.AUDITLOG_END_TIMESTAMP);
+ }
+
+ public String getViewName() {
+ return viewName;
+ }
+
+ public void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.RoleFunction;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.RoleService;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+public class RoleFunctionListController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleFunctionListController.class);
+
+ @Autowired
+ private RoleService service;
+
+ private String viewName;
+
+ @RequestMapping(value = {"/role_function_list" }, method = RequestMethod.GET)
+ public ModelAndView welcome(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+
+
+ try {
+ model.put("availableRoleFunctions", mapper.writeValueAsString(service.getRoleFunctions(user.getOrgUserId())));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "welcome failed", e);
+ }
+
+ return new ModelAndView(getViewName(),model);
+ }
+
+ @RequestMapping(value = {"/get_role_functions" }, method = RequestMethod.GET)
+ public void getRoleFunctionList(HttpServletRequest request,HttpServletResponse response) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+ try {
+ model.put("availableRoleFunctions", mapper.writeValueAsString(service.getRoleFunctions(user.getOrgUserId())));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getROleFunctionList failed", e);
+ }
+
+ }
+
+ @RequestMapping(value = {"/role_function_list/saveRoleFunction" }, method = RequestMethod.POST)
+ public void saveRoleFunction(HttpServletRequest request,
+ HttpServletResponse response, @RequestBody String roleFunc) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+
+ String restCallStatus = "";
+ try {
+ String data = roleFunc;
+ RoleFunction availableRoleFunction = mapper.readValue(data, RoleFunction.class);
+ String code = availableRoleFunction.getCode();
+ RoleFunction domainRoleFunction = service.getRoleFunction(user.getOrgUserId(),code);
+ domainRoleFunction.setName(availableRoleFunction.getName());
+ domainRoleFunction.setCode(code);
+ restCallStatus="success";
+ service.saveRoleFunction(user.getOrgUserId(),domainRoleFunction);
+ } catch (Exception e) {
+ restCallStatus="fail";
+ logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed", e);
+ throw new Exception("failed while Saving RoleFunction");
+ }
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(restCallStatus));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+
+ @RequestMapping(value = {"/role_function_list/addRoleFunction" }, method = RequestMethod.POST)
+ public void addRoleFunction(HttpServletRequest request,
+ HttpServletResponse response, @RequestBody String roleFunc) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+
+ String restCallStatus = "";
+ boolean canSave=true;
+ try {
+ String data = roleFunc;
+ RoleFunction availableRoleFunction = mapper.readValue(data, RoleFunction.class);
+ String code = availableRoleFunction.getCode();
+ List<RoleFunction> currentRoleFunction = service.getRoleFunctions(user.getOrgUserId());
+ restCallStatus="success";
+ for(RoleFunction roleF:currentRoleFunction){
+ if(roleF.getCode().equals(code)){
+ restCallStatus="code exists";
+ canSave=false;
+ break;
+ }
+ }
+ if(canSave)
+ service.saveRoleFunction(user.getOrgUserId(),availableRoleFunction);
+ } catch (Exception e) {
+ restCallStatus="fail";
+ logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunction failed", e);
+ throw new Exception(e.getMessage());
+ }
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(restCallStatus));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+
+ @RequestMapping(value = {"/role_function_list/removeRoleFunction" }, method = RequestMethod.POST)
+ public void removeRoleFunction(HttpServletRequest request,
+ HttpServletResponse response, @RequestBody String roleFunc) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+
+ String restCallStatus = "";
+ try {
+ String data = roleFunc;
+
+ RoleFunction availableRoleFunction = mapper.readValue(data, RoleFunction.class);
+
+ RoleFunction domainRoleFunction = service.getRoleFunction(user.getOrgUserId(),availableRoleFunction.getCode());
+
+ service.deleteRoleFunction(user.getOrgUserId(),domainRoleFunction);
+ logger.info(EELFLoggerDelegate.auditLogger, "Remove role function " + domainRoleFunction.getName());
+ restCallStatus="success";
+ } catch (Exception e) {
+ restCallStatus="fail";
+ logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
+ throw new Exception(e.getMessage());
+ }
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(restCallStatus));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+
+ public String getViewName() {
+ return viewName;
+ }
+ public void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.RoleService;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+public class RoleListController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleListController.class);
+
+ @Autowired
+ private RoleService service;
+
+ private String viewName;
+
+ @RequestMapping(value = {"/role_list" }, method = RequestMethod.GET)
+ public ModelAndView getRoleList(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+
+
+ try {
+ model.put("availableRoles", mapper.writeValueAsString(service.getAvailableRoles(user.getOrgUserId())));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getRoleList failed", e);
+ }
+
+ return new ModelAndView(getViewName(),model);
+ }
+
+ @RequestMapping(value = {"/get_roles" }, method = RequestMethod.GET)
+ public void getRoles(HttpServletRequest request, HttpServletResponse response) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+
+
+ try {
+ model.put("availableRoles", mapper.writeValueAsString(service.getAvailableRoles(user.getOrgUserId())));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
+ }
+ }
+
+
+ @RequestMapping(value = {"/role_list/toggleRole" }, method = RequestMethod.POST)
+ public ModelAndView toggleRole(HttpServletRequest request,
+ HttpServletResponse response) throws Exception {
+ User user = UserUtils.getUserSession(request);
+
+
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ Role role = mapper.readValue(root.get("role").toString(), Role.class);
+
+ Role domainRole = service.getRole(user.getOrgUserId(),role.getId());
+ //role. toggle active ind
+ boolean active = domainRole.getActive();
+ domainRole.setActive(!active);
+
+ service.saveRole(user.getOrgUserId(),domainRole);
+ logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId());
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(service.getAvailableRoles(user.getOrgUserId()));
+ JSONObject j = new JSONObject("{availableRoles: "+responseString+"}");
+
+ out.write(j.toString());
+
+ return null;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ return null;
+ }
+
+ }
+
+ @RequestMapping(value = {"/role_list/removeRole" }, method = RequestMethod.POST)
+ public ModelAndView removeRole(HttpServletRequest request,
+ HttpServletResponse response) throws Exception {
+ User user = UserUtils.getUserSession(request);
+
+ try {
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ Role role = mapper.readValue(root.get("role").toString(), Role.class);
+
+ Role domainRole = service.getRole(user.getOrgUserId(),role.getId());
+
+ service.deleteDependcyRoleRecord(user.getOrgUserId(),role.getId());
+ service.deleteRole(user.getOrgUserId(),domainRole);
+ logger.info(EELFLoggerDelegate.auditLogger, "Remove role " + domainRole.getId());
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+
+ String responseString = mapper.writeValueAsString(service.getAvailableRoles(user.getOrgUserId()));
+ JSONObject j = new JSONObject("{availableRoles: "+responseString+"}");
+ out.write(j.toString());
+
+ return null;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ return null;
+ }
+
+ }
+
+ public String getViewName() {
+ return viewName;
+ }
+ public void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.portalsdk.core.auth.LoginStrategy;
+import org.onap.portalsdk.core.controller.UnRestrictedBaseController;
+import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
+import org.onap.portalsdk.core.service.LoginService;
+import org.onap.portalsdk.core.service.ProfileService;
+import org.onap.portalsdk.core.web.support.AppUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+@Controller
+@RequestMapping("/")
+public class SDKLoginController extends UnRestrictedBaseController {
+ @Autowired
+ ProfileService service;
+ @Autowired
+ private LoginService loginService;
+ @Autowired
+ private LoginStrategy loginStrategy;
+
+ private String viewName;
+
+ @RequestMapping(value = { "/login.htm" }, method = RequestMethod.GET)
+ public ModelAndView login(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ return new ModelAndView("login", "model", model);
+ }
+
+ @RequestMapping(value = { "/login_external.htm" }, method = RequestMethod.GET)
+ public ModelAndView externalLogin(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ return new ModelAndView("login_external", "model", model);
+ }
+
+ @RequestMapping(value = { "/login_external" }, method = RequestMethod.POST)
+ public ModelAndView doexternalLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ return loginStrategy.doExternalLogin(request, response);
+ }
+
+ @RequestMapping(value = { "/doLogin" }, method = RequestMethod.GET)
+ public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ return loginStrategy.doLogin(request, response);
+ }
+
+ public String getJessionId(HttpServletRequest request) {
+ return request.getSession().getId();
+ }
+
+ protected void initateSessionMgtHandler(HttpServletRequest request) {
+ String jSessionId = getJessionId(request);
+ PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
+ }
+
+ public String getViewName() {
+ return viewName;
+ }
+
+ public void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+ public LoginService getLoginService() {
+ return loginService;
+ }
+
+ public void setLoginService(LoginService loginService) {
+ this.loginService = loginService;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalsdk.core.auth.LoginStrategy;
+import org.onap.portalsdk.core.command.LoginBean;
+import org.onap.portalsdk.core.controller.UnRestrictedBaseController;
+import org.onap.portalsdk.core.domain.RoleFunction;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.menu.MenuProperties;
+import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+import org.onap.portalsdk.core.service.LoginService;
+import org.onap.portalsdk.core.service.RoleService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.AppUtils;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+import org.springframework.web.util.WebUtils;
+
+@Controller
+@RequestMapping("/")
+public class SingleSignOnController extends UnRestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SingleSignOnController.class);
+
+ @Autowired
+ private LoginService loginService;
+
+ @Autowired
+ private LoginStrategy loginStrategy;
+
+ private String viewName;
+ private String welcomeView;
+
+ public String getWelcomeView() {
+ return welcomeView;
+ }
+
+ public void setWelcomeView(String welcomeView) {
+ this.welcomeView = welcomeView;
+ }
+
+ @Autowired
+ RoleService roleService;
+
+ /**
+ * Handles requests directed to the single sign-on page by the session
+ * timeout interceptor.
+ *
+ * @param request
+ * @return Redirect to an appropriate address
+ * @throws Exception
+ */
+ @RequestMapping(value = { "/single_signon.htm" }, method = RequestMethod.GET)
+ public ModelAndView singleSignOnLogin(HttpServletRequest request) throws Exception {
+
+ Map<String, String> model = new HashMap<String, String>();
+ HashMap<String, String> additionalParamsMap = new HashMap<String, String>();
+ LoginBean commandBean = new LoginBean();
+
+ // SessionTimeoutInterceptor sets these parameters
+ String forwardURL = URLDecoder.decode(request.getParameter("forwardURL"), "UTF-8");
+ String redirectToPortal = request.getParameter("redirectToPortal");
+
+ if (isLoginCookieExist(request) && redirectToPortal == null) {
+ HttpSession session = null;
+ session = AppUtils.getSession(request);
+ User user = UserUtils.getUserSession(request);
+ if (session == null || user == null) {
+
+ final String authMech = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM);
+ String userId = loginStrategy.getUserId(request);
+ commandBean.setUserid(userId);
+ commandBean = getLoginService().findUser(commandBean,
+ (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY),
+ additionalParamsMap);
+ List<RoleFunction> roleFunctionList= roleService.getRoleFunctions(userId);
+ if (commandBean.getUser() == null) {
+ String loginErrorMessage = (commandBean.getLoginErrorMessage() != null)
+ ? commandBean.getLoginErrorMessage()
+ : SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_NOT_FOUND;
+ model.put(LoginStrategy.ERROR_MESSAGE_KEY, SystemProperties.getProperty(loginErrorMessage));
+ final String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL)
+ + "?noUserError=Yes";
+ logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: user is null, redirect URL is {}",
+ redirectUrl);
+ return new ModelAndView("redirect:" + redirectUrl);
+ } else {
+ // store the user's information in the session
+ String loginMethod;
+ if (null == authMech || "".equals(authMech) || "BOTH".equals(authMech)) {
+ loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_CSP);
+ } else if ("CSP".equals(authMech)) {
+ loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_CSP);
+ } else {
+ loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_WEB_JUNCTION);
+ }
+ UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
+ commandBean.getBusinessDirectMenu(), loginMethod, roleFunctionList);
+ initateSessionMgtHandler(request);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "singleSignOnLogin: create new user session for expired user {}; user {} exists in the system",
+ userId, commandBean.getUser().getOrgUserId());
+ return new ModelAndView("redirect:" + forwardURL);
+ }
+ } // user is null or session is null
+ else {
+ // both user and session are non-null.
+ logger.info(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: redirecting to the forwardURL {}",
+ forwardURL);
+ return new ModelAndView("redirect:" + forwardURL);
+ }
+
+ } else {
+ /*
+ * Login cookie not found, or redirect-to-portal parameter was
+ * found.
+ *
+ * Redirect the user to the portal with a suitable return URL. The
+ * forwardURL parameter that arrives as a parameter is a partial
+ * (not absolute) request path for a page in the application. The
+ * challenge here is to compute the correct absolute path for the
+ * original request so the portal can redirect the user back to the
+ * right place. If the application sits behind WebJunction, or if
+ * separate FE-BE hosts are used, then the URL yielded by the
+ * request has a host name that is not reachable by the user.
+ */
+ String returnToAppUrl = null;
+ if (SystemProperties.containsProperty(SystemProperties.APP_BASE_URL)) {
+ // New feature as of 1610, release 3.3.3:
+ // application can publish a base URL in system.properties
+ String appUrl = SystemProperties.getProperty(SystemProperties.APP_BASE_URL);
+ returnToAppUrl = appUrl + (appUrl.endsWith("/") ? "" : "/") + forwardURL;
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "singleSignOnLogin: using app base URL {} and redirectURL {}", appUrl, returnToAppUrl);
+ } else {
+ // Be backward compatible with applications that don't need this
+ // feature.
+ // This is the controller for the single_signon.htm page, so the
+ // replace
+ // should always find the specified token.
+ returnToAppUrl = ((HttpServletRequest) request).getRequestURL().toString().replace("single_signon.htm",
+ forwardURL);
+ logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: computed redirectURL {}",
+ returnToAppUrl);
+ }
+ final String encodedReturnToAppUrl = URLEncoder.encode(returnToAppUrl, "UTF-8");
+ // Also send the application's UEB key so Portal can block URL
+ // reflection attacks.
+ final String uebAppKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
+ final String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
+ final String portalUrl = url.substring(0, url.lastIndexOf('/')) + "/process_csp";
+ final String redirectUrl = portalUrl + "?uebAppKey=" + uebAppKey + "&redirectUrl=" + encodedReturnToAppUrl;
+ logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: portal-bound redirect URL is {}",
+ redirectUrl);
+ return new ModelAndView("redirect:" + redirectUrl);
+ }
+ }
+
+ protected void initateSessionMgtHandler(HttpServletRequest request) {
+ String portalJSessionId = getPortalJSessionId(request);
+ String jSessionId = getJessionId(request);
+ PortalTimeoutHandler.sessionCreated(portalJSessionId, jSessionId, AppUtils.getSession(request));
+ }
+
+ public boolean isLoginCookieExist(HttpServletRequest request) {
+ Cookie ep = WebUtils.getCookie(request, LoginStrategy.EP_SERVICE);
+ return (ep != null);
+ }
+
+ public String getPortalJSessionId(HttpServletRequest request) {
+ Cookie ep = WebUtils.getCookie(request, LoginStrategy.EP_SERVICE);
+ return ep.getValue();
+ }
+
+ public String getJessionId(HttpServletRequest request) {
+ return request.getSession().getId();
+ }
+
+ public String getViewName() {
+ return viewName;
+ }
+
+ public void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+ public LoginService getLoginService() {
+ return loginService;
+ }
+
+ public void setLoginService(LoginService loginService) {
+ this.loginService = loginService;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.onap.portalsdk.core.command.UserRowBean;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.util.UsageUtils;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+@Controller
+@RequestMapping("/")
+public class UsageListController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UsageListController.class);
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @RequestMapping(value = { "/usage_list" }, method = RequestMethod.GET)
+ public ModelAndView usageList(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+
+ HttpSession httpSession = request.getSession();
+ HashMap activeUsers = (HashMap) httpSession.getServletContext().getAttribute("activeUsers");
+ if (activeUsers.size() == 0) {
+ activeUsers.put(httpSession.getId(), httpSession);
+ httpSession.getServletContext().setAttribute("activeUsers", activeUsers);
+ }
+ ArrayList<UserRowBean> rows = UsageUtils.getActiveUsers(activeUsers);
+ JSONArray ja = new JSONArray();
+ try {
+ for (UserRowBean userRowBean : rows) {
+ JSONObject jo = new JSONObject();
+ jo.put("id", userRowBean.getId());
+ jo.put("lastName", userRowBean.getLastName());
+ jo.put("email", userRowBean.getEmail());
+ jo.put("lastAccess", userRowBean.getLastAccess());
+ jo.put("remaining", userRowBean.getRemaining());
+ jo.put("sessionId", userRowBean.getSessionId());
+ if (!(httpSession.getId().equals(userRowBean.getSessionId()))) {
+ jo.put("delete", "yes");
+ } else {
+ jo.put("delete", "no");
+ }
+ ja.put(jo);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "usageList failed", e);
+ }
+
+ model.put("model", ja);
+
+ return new ModelAndView(getViewName(), model);
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @RequestMapping(value = { "/get_usage_list" }, method = RequestMethod.GET)
+ public void getUsageList(HttpServletRequest request, HttpServletResponse response) {
+
+ HttpSession httpSession = request.getSession();
+ HashMap activeUsers = (HashMap) httpSession.getServletContext().getAttribute("activeUsers");
+ if (activeUsers.size() == 0) {
+ activeUsers.put(httpSession.getId(), httpSession);
+ httpSession.getServletContext().setAttribute("activeUsers", activeUsers);
+ }
+ ArrayList<UserRowBean> rows = UsageUtils.getActiveUsers(activeUsers);
+ JSONArray ja = new JSONArray();
+ try {
+ for (UserRowBean userRowBean : rows) {
+ JSONObject jo = new JSONObject();
+ jo.put("id", userRowBean.getId());
+ jo.put("lastName", userRowBean.getLastName());
+ jo.put("email", userRowBean.getEmail());
+ jo.put("lastAccess", userRowBean.getLastAccess());
+ jo.put("remaining", userRowBean.getRemaining());
+ jo.put("sessionId", userRowBean.getSessionId());
+ if (!(httpSession.getId().equals(userRowBean.getSessionId()))) {
+ jo.put("delete", "yes");
+ } else {
+ jo.put("delete", "no");
+ }
+ ja.put(jo);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getUsageList failed", e);
+ }
+ JsonMessage msg;
+ try {
+ msg = new JsonMessage(ja.toString());
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getUsageList failed to serialize", e);
+ }
+
+ }
+
+ @SuppressWarnings("rawtypes")
+ @RequestMapping(value = { "/usage_list/removeSession" }, method = RequestMethod.GET)
+ public void removeSession(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ HashMap activeUsers = (HashMap) request.getSession().getServletContext().getAttribute("activeUsers");
+ UserRowBean data = new UserRowBean();
+ data.setSessionId(request.getParameter("deleteSessionId"));
+ UsageUtils.getActiveUsersAfterDelete(activeUsers, data);
+
+ HttpSession httpSession = request.getSession();
+ ArrayList<UserRowBean> rows = UsageUtils.getActiveUsers(activeUsers);
+ JSONArray ja = new JSONArray();
+ try {
+ for (UserRowBean userRowBean : rows) {
+ JSONObject jo = new JSONObject();
+ jo.put("id", userRowBean.getId());
+ jo.put("lastName", userRowBean.getLastName());
+ jo.put("email", userRowBean.getEmail());
+ jo.put("lastAccess", userRowBean.getLastAccess());
+ jo.put("remaining", userRowBean.getRemaining());
+ jo.put("sessionId", userRowBean.getSessionId());
+ if (!(httpSession.getId().equals(userRowBean.getSessionId()))) {
+ jo.put("delete", "yes");
+ } else {
+ jo.put("delete", "no");
+ }
+ ja.put(jo);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "removeSession failed", e);
+ }
+
+ response.setContentType("application/json");
+ PrintWriter out = response.getWriter();
+ out.write(ja.toString());
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.Profile;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.ProfileService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * Controller for user profile view. The view is restricted to authenticated
+ * users. The view name resolves to page user_profile.jsp which uses Angular.
+ */
+
+@Controller
+@RequestMapping("/")
+public class UserProfileController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserProfileController.class);
+
+ @Autowired
+ private ProfileService service;
+
+ @RequestMapping(value = { "/user_profile" }, method = RequestMethod.GET)
+ public ModelAndView userProfile(HttpServletRequest request) throws Exception {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ List<Profile> profileList = service.findAll();
+ try {
+ model.put("customerInfo", mapper.writeValueAsString(profileList));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "userProfile failed", e);
+ }
+
+ return new ModelAndView("user_profile", "model", model);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.core;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+/**
+ * Controller for welcome view. The view is restricted to authenticated users.
+ * The view name defaults to the request name with no suffix, "welcome", which
+ * resolves to page welcome.jsp.
+ */
+@Controller
+@RequestMapping("/")
+public class WelcomeController extends RestrictedBaseController {
+ @RequestMapping(value = { "/welcome" }, method = RequestMethod.GET)
+ public ModelAndView welcome(HttpServletRequest request) {
+ final String defaultViewName = null;
+ return new ModelAndView(defaultViewName);
+ }
+}
--- /dev/null
+package org.onap.portalapp.controller.core;
+
+/**
+ * Provides controllers for EPSDK application core functionality such as logging
+ * in, managing roles, editing menus, etc.
+ */
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+/**
+ * Controller for a single-page application sample. The view is restricted to
+ * authenticated users. The named view resolves to page singlePageSample.html,
+ * which uses Angular.
+ */
+@Controller
+@RequestMapping("/")
+public class AngularSinglePageController extends RestrictedBaseController {
+
+ @RequestMapping(value = { "/singlePageSample" }, method = RequestMethod.GET)
+ public ModelAndView view(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ return new ModelAndView("single_page_sample", "model", model);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.BroadcastMessage;
+import org.onap.portalsdk.core.service.BroadcastService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.AppUtils;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+public class BroadcastController extends RestrictedBaseController {
+
+ @Autowired
+ private BroadcastService broadcastService;
+
+ @RequestMapping(value = { "/broadcast" }, method = RequestMethod.GET)
+ public ModelAndView broadcast(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+
+ try {
+ model.put("broadcastMessage", mapper.writeValueAsString(broadcastService.getBroadcastMessage(request)));
+ model.put("broadcastSites", mapper.writeValueAsString(referenceData(request).get("broadcastSites")));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return new ModelAndView(getViewName(), model);
+ }
+
+ @RequestMapping(value = { "/get_broadcast" }, method = RequestMethod.GET)
+ public void getBroadcast(HttpServletRequest request, HttpServletResponse response) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+
+ try {
+
+ model.put("broadcastMessage", mapper.writeValueAsString(broadcastService.getBroadcastMessage(request)));
+ model.put("broadcastSites", mapper.writeValueAsString(referenceData(request).get("broadcastSites")));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ protected Map referenceData(HttpServletRequest request) {
+ Map lookupData = new HashMap();
+
+ if ("true".equals(SystemProperties.getProperty(SystemProperties.CLUSTERED))) {
+ lookupData.put("broadcastSites", AppUtils.getLookupList("fn_lu_broadcast_site", "broadcast_site_cd",
+ "broadcast_site_descr", "", "broadcast_site_descr"));
+ }
+
+ return lookupData;
+ }
+
+ @RequestMapping(value = { "/broadcast/save" }, method = RequestMethod.POST)
+ public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception {
+
+ try {
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ BroadcastMessage broadcastMessage = mapper.readValue(root.get("broadcastMessage").toString(),
+ BroadcastMessage.class);
+
+ broadcastService.saveBroadcastMessage(broadcastMessage);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(broadcastMessage);
+ JSONObject j = new JSONObject("{broadcastMessage: " + responseString + "}");
+
+ out.write(j.toString());
+
+ return null;
+ } catch (Exception e) {
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ return null;
+ }
+
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.BroadcastMessage;
+import org.onap.portalsdk.core.service.BroadcastService;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+public class BroadcastListController extends RestrictedBaseController {
+
+ @Autowired
+ private BroadcastService broadcastService;
+
+ @RequestMapping(value = { "/broadcast_list" }, method = RequestMethod.GET)
+ public ModelAndView broadcastList(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+
+ model.put("model", broadcastService.getBcModel(request));
+ return new ModelAndView(getViewName(), model);
+ }
+
+ @RequestMapping(value = { "/get_broadcast_list" }, method = RequestMethod.GET)
+ public void getBroadcast(HttpServletRequest request, HttpServletResponse response) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ model.put("model", broadcastService.getBcModel(request));
+ model.put("messagesList", broadcastService.getBcModel(request).get("messagesList"));
+ model.put("messageLocations", broadcastService.getBcModel(request).get("messageLocations"));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ @RequestMapping(value = { "/broadcast_list/remove" }, method = RequestMethod.POST)
+ public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception {
+
+ try {
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ BroadcastMessage broadcastMessage = mapper.readValue(root.get("broadcastMessage").toString(),
+ BroadcastMessage.class);
+
+ broadcastService.removeBroadcastMessage(broadcastMessage);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(broadcastMessage);
+ JSONObject j = new JSONObject("{broadcastMessage: " + responseString + "}");
+
+ out.write(j.toString());
+
+ return null;
+ } catch (Exception e) {
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ return null;
+ }
+
+ }
+
+ @RequestMapping(value = { "/broadcast_list/toggleActive" }, method = RequestMethod.POST)
+ public ModelAndView toggleActive(HttpServletRequest request, HttpServletResponse response) throws Exception {
+
+ try {
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ BroadcastMessage broadcastMessage = mapper.readValue(root.get("broadcastMessage").toString(),
+ BroadcastMessage.class);
+
+ broadcastService.saveBroadcastMessage(broadcastMessage);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(broadcastMessage);
+ JSONObject j = new JSONObject("{broadcastMessage: " + responseString + "}");
+
+ out.write(j.toString());
+
+ return null;
+ } catch (Exception e) {
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ return null;
+ }
+
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+
+/**
+ * Controller for a message sequence chart view. The view is restricted to
+ * authenticated users. The view name defaults to the request name with no
+ * suffix, "callflow", which resolves to page details.jsp. That page is an
+ * iframe around page details.html.
+ */
+@Controller
+@RequestMapping("/")
+public class CallflowController extends RestrictedBaseController {
+
+ @RequestMapping(value = { "/callflow" }, method = RequestMethod.GET)
+ public ModelAndView plot() {
+ final String defaultViewName = null;
+ return new ModelAndView(defaultViewName);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+
+
+/**
+ * @author chris zeng
+ *
+ */
+
+@Controller
+@RequestMapping("/")
+public class CamundaCockpitController extends RestrictedBaseController {
+ @SuppressWarnings("rawtypes")
+ @RequestMapping(value = {"/get_camunda_cockpit_link" }, method = RequestMethod.GET, produces = "application/json")
+ @ResponseBody
+ public Map getCamundaCockpitLink(HttpServletRequest request,HttpServletResponse response) {
+ Map<String,String> map = new HashMap<String,String>();
+ String camundaCockpitUrl = "";
+ String camundaCockpitlinkDefined = "false";
+ if (SystemProperties.containsProperty("camunda_cockpit_link")){
+ camundaCockpitUrl = SystemProperties.getProperty("camunda_cockpit_link");
+ camundaCockpitlinkDefined = "true";
+ };
+ map.put("link_defined", camundaCockpitlinkDefined);
+ map.put("camunda_cockpit_link", camundaCockpitUrl);
+ return map;
+ };
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.UserProfileService;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+public class CollaborateListController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CollaborateListController.class);
+
+ @Autowired
+ private UserProfileService service;
+
+ @RequestMapping(value = {"/collaborate_list" }, method = RequestMethod.GET)
+ public ModelAndView ProfileSearch(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+
+ List<User> profileList =null;
+ try {
+ profileList = service.findAllUserWithOnOffline(user.getOrgUserId());
+ model.put("profileList", mapper.writeValueAsString(profileList));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Error happened during collaborate list search" + e.getMessage());
+
+ }
+ return new ModelAndView(getViewName(),"model", model);
+ }
+
+ @RequestMapping(value = {"/get_collaborate_list" }, method = RequestMethod.GET)
+ public void getCollaborateList(HttpServletRequest request,HttpServletResponse response) {
+
+ ObjectMapper mapper = new ObjectMapper();
+ User user = UserUtils.getUserSession(request);
+
+ List<User> profileList =null;
+ try {
+ profileList = service.findAllUserWithOnOffline(user.getOrgUserId());
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(profileList));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Error happened during get collaborate list" + e.getMessage());
+
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+@Controller
+@RequestMapping("/")
+public class CollaborationController extends RestrictedBaseController{
+
+ @RequestMapping(value = {"/collaboration" }, method = RequestMethod.GET)
+ public ModelAndView view(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ User user = UserUtils.getUserSession(request);
+
+ model.put("name",(user.getFirstName() + " " + (user.getLastName() != null? user.getLastName().substring(0,1): "" )));
+ return new ModelAndView(getViewName(),"model", model);
+ }
+ @RequestMapping(value = {"/openCollaboration" }, method = RequestMethod.GET)
+ public ModelAndView openCollaboration(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ User user = UserUtils.getUserSession(request);
+
+ model.put("name",(user.getFirstName() + " " + (user.getLastName() != null? user.getLastName().substring(0,1): "" )));
+ return new ModelAndView("openCollaboration","model", model);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.UnRestrictedBaseController;
+import org.onap.portalsdk.core.service.ProfileService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+
+/**
+ * Controller for user profile view. The view is restricted to authenticated
+ * users. The view name resolves to page user_profile.jsp which uses Angular.
+ */
+
+@Controller
+@RequestMapping("/")
+public class DS2SampleController extends UnRestrictedBaseController {
+
+ @Autowired
+ ProfileService service;
+
+ @RequestMapping(value = { "/ds2_sample" }, method = RequestMethod.GET)
+ public ModelAndView ProfileSearch(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ return new ModelAndView("ds2_sample", "model", model);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import java.io.IOException;
+
+import org.json.JSONObject;
+import org.onap.portalapp.model.Result;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.servlet.ModelAndView;
+
+import io.searchbox.client.JestClient;
+import io.searchbox.client.JestClientFactory;
+import io.searchbox.client.config.HttpClientConfig;
+import io.searchbox.core.Search;
+import io.searchbox.core.SearchResult;
+import io.searchbox.core.Suggest;
+import io.searchbox.core.SuggestResult;
+import io.searchbox.params.Parameters;
+
+/**
+ * Controller for views that demonstrate Elastic Search features.
+ */
+@RestController
+public class ElasticSearchController extends RestrictedBaseController{
+
+ @RequestMapping(value = {"/es_search_demo" }, method = RequestMethod.GET)
+ public ModelAndView search() {
+ return new ModelAndView("es_search_demo");
+ }
+
+ @RequestMapping(value = {"/es_suggest_demo" }, method = RequestMethod.GET)
+ public ModelAndView suggest() {
+ return new ModelAndView("es_suggest_demo");
+ }
+
+ @RequestMapping(value="/es_suggest/{task}",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity<Result> doSuggest(@PathVariable("task") String task) throws IOException {
+ JSONObject obj = new JSONObject(task);
+ String searchTerm = obj.getString("data");
+ String searchSize = obj.getString("size");
+ String searchFuzzy = obj.getString("fuzzy");
+ String resultName = obj.getString("resultname");
+
+ JestClientFactory factory = new JestClientFactory();
+ factory.setHttpClientConfig(new HttpClientConfig
+ .Builder("http://todo_elastic_search_server")
+ .multiThreaded(true)
+ .build());
+ JestClient client = factory.getObject();
+
+
+ Suggest suggest = new Suggest.Builder("{\n"
+ +"\"" + resultName +"\" : {\n"
+ +"\"text\" : \""+ searchTerm +"\",\n"
+ +"\"completion\" : {\n"
+ +"\"field\" : \"suggest\",\n"
+ +"\"size\" : " + searchSize + ",\n"
+ +"\"fuzzy\" : \"" + searchFuzzy + "\"\n"
+ +"}\n"
+ +"}\n"
+ +"}").addIndex("customer").build();
+
+ SuggestResult result = client.execute(suggest);
+ System.err.println(result.getJsonObject().toString());
+ return new ResponseEntity<Result>(new Result(result.getJsonObject().toString()),HttpStatus.OK);
+ }
+
+ @RequestMapping(value="/es_search/{task}",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity<Result> doSearch(@PathVariable("task") String task) throws IOException {
+ JSONObject obj = new JSONObject(task);
+ String searchTerm = obj.getString("data");
+ String searchSize = obj.getString("size");
+ // String searchFuzzy = obj.getString("fuzzy");
+
+ JestClientFactory factory = new JestClientFactory();
+ factory.setHttpClientConfig(new HttpClientConfig
+ .Builder("http://todo_elastic_search_server")
+ .multiThreaded(true)
+ .build());
+ JestClient client = factory.getObject();
+
+ Search search = new Search.Builder("{\n"
+ +"\"query\" : {\n"
+ +"\"query_string\" : {\n"
+ +"\"query\" : \"name:"+ searchTerm +"\"\n"
+ +"}\n"
+ +"}\n"
+ +"}").addIndex("customer").setParameter(Parameters.SIZE,Integer.valueOf(searchSize)).build();
+
+ SearchResult result = client.execute(search);
+ System.err.println(result.getJsonObject().toString());
+ return new ResponseEntity<Result>(new Result(result.getJsonObject().toString()),HttpStatus.OK);
+ }
+
+ public ResponseEntity<Result> sendResult(Result result) {
+ return new ResponseEntity<Result>(result, HttpStatus.OK);
+ }
+
+ @Override
+ public boolean isRESTfulCall() {
+ return true;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.ElementLinkService;
+import org.onap.portalsdk.core.service.ElementMapService;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/")
+public class ElementModelController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ElementModelController.class);
+
+ @RequestMapping(value = { "/elementMapLayout" }, method = RequestMethod.GET, produces = "text/plain")
+ public String layout(HttpServletRequest request, HttpServletResponse response) throws Exception {
+
+ String collapseDomains = request.getParameter("collapsedDomains");
+ String expandDomains = request.getParameter("expandedDomains");
+
+ String contentFileName = request.getParameter("contentFileName");
+ String layoutFileName = request.getParameter("layoutFileName");
+
+ final String realPath = request.getServletContext().getRealPath("/");
+ logger.debug(EELFLoggerDelegate.debugLogger, "layout: servlet context real path: {}", realPath);
+
+ ElementMapService eltMapSvc = new ElementMapService();
+ String yamlString = eltMapSvc.buildElementMapYaml(
+ new String[] { collapseDomains, expandDomains, realPath, contentFileName, layoutFileName });
+
+ return yamlString;
+ }
+
+ @RequestMapping(value = { "/elementMapLink" }, method = RequestMethod.GET, produces = "text/plain")
+ public String callflow(HttpServletRequest request, HttpServletResponse response) throws Exception {
+
+ String callFlowName = request.getParameter("callFlowName");
+ String callFlowStep = request.getParameter("callFlowStep");
+
+ final String realPath = request.getServletContext().getRealPath("/");
+ logger.debug(EELFLoggerDelegate.debugLogger, "callflow: servlet context real path: {}", realPath);
+
+ ElementLinkService eltLinkSvc = new ElementLinkService();
+ String yamlString = eltLinkSvc.buildElementLinkYaml(new String[] { realPath, callFlowName, callFlowStep });
+
+ return yamlString;
+ }
+
+ /*
+ public ModelAndView callflowAdditional(HttpServletRequest request, HttpServletResponse response) throws Exception {
+
+ Map<String, Object> model = new HashMap<String, Object>();
+ String callFlowName = request.getParameter("callFlowName");
+ String callFlowStep = request.getParameter("callFlowStep");
+
+ ElementLinkService main = new ElementLinkService();
+ String yamlString = main.main2(new String[] { callFlowName, callFlowStep });
+ model.put("output_string", yamlString);
+ return new ModelAndView("data_out", "model", model);
+ }
+ */
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+/**
+ * Controller for geographic map view. The view is restricted to authenticated
+ * users. The view name defaults to the request name with no suffix,
+ * "leafletMap", which resolves to page leafletMap.jsp.
+ */
+@Controller
+@RequestMapping("/")
+public class LeafletMapContoller extends RestrictedBaseController {
+
+ @RequestMapping(value = { "/leafletMap" }, method = RequestMethod.GET)
+ public ModelAndView plot() {
+ final String defaultViewName = null;
+ return new ModelAndView(defaultViewName);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+/**
+ * Controller for a network map view that uses iframes. The view is restricted
+ * to authenticated users.
+ */
+@Controller
+@RequestMapping("/")
+public class NetMapController extends RestrictedBaseController {
+
+ @RequestMapping(value = { "/net_map" }, method = RequestMethod.GET)
+ public ModelAndView plot(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ model.put("frame_int", "net_map_int");
+ // This view resolves to page frame_insert.jsp
+ return new ModelAndView("frame_insert", model);
+ }
+
+ @RequestMapping(value = { "/net_map_int" }, method = RequestMethod.GET)
+ public ModelAndView plot2() {
+ // The view name defaults to the request without any suffix.
+ final String defaultViewName = null;
+ // This view resolves to page net_map.jsp
+ return new ModelAndView(defaultViewName);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import java.io.PrintWriter;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.command.PostDroolsBean;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.PostDroolsService;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+public class PostDroolsController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostDroolsController.class);
+
+ @Autowired
+ private PostDroolsService postDroolsService;
+
+ @RequestMapping(value = { "/drools" }, method = RequestMethod.GET)
+ public ModelAndView drools(HttpServletRequest request) {
+ return new ModelAndView(getViewName());
+ }
+
+ @RequestMapping(value = { "/getDrools" }, method = RequestMethod.GET)
+ public void getDrools(HttpServletRequest request, HttpServletResponse response) {
+ // Map<String, Object> model = new HashMap<String, Object>();
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ List<PostDroolsBean> beanList = postDroolsService.fetchDroolBeans();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(beanList));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getDrools failed", e);
+ }
+ }
+
+ @RequestMapping(value = { "/getDroolDetails" }, method = RequestMethod.GET)
+ public void getDroolDetails(HttpServletRequest request, HttpServletResponse response) {
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+
+ PostDroolsBean postDroolsBean = new PostDroolsBean();
+ String selectedFile = request.getParameter("selectedFile");
+ postDroolsBean.setDroolsFile(selectedFile);// sample populated
+ // postDroolsBean.setSelectedRules("[\"NJ\",\"NY\",\"KY\"]");
+ postDroolsBean.setClassName(postDroolsService.retrieveClass(selectedFile));
+
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(postDroolsBean));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getDroolDetails failed", e);
+ }
+ }
+
+ @RequestMapping(value = { "/post_drools/execute" }, method = RequestMethod.POST)
+ public ModelAndView search(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PostDroolsBean postDroolsBean = mapper.readValue(root.get("postDroolsBean").toString(),
+ PostDroolsBean.class);
+
+ String resultsString = postDroolsService.execute(postDroolsBean.getDroolsFile(),
+ postDroolsBean.getClassName(), postDroolsBean.getSelectedRules());
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ // String responseString = mapper.writeValueAsString(resultsString);
+ JSONObject j = new JSONObject("{resultsString: " + resultsString + "}");
+
+ out.write(j.toString());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "search failed", e);
+ }
+
+ return null;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+/**
+ * Report dashboard
+ *
+ */
+
+@Controller
+@RequestMapping("/")
+public class ReportDashboardController extends RestrictedBaseController {
+ @RequestMapping(value = {"/report_dashboard" }, method = RequestMethod.GET)
+ public ModelAndView adminView(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ return new ModelAndView(getViewName(),"model", model);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.controller.sample;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+/**
+ * Controller for a network map view that uses iframes. The view is restricted
+ * to authenticated users.
+ */
+@Controller
+@RequestMapping("/")
+public class SamplePageController extends RestrictedBaseController {
+
+ @RequestMapping(value = { "/samplePage" }, method = RequestMethod.GET)
+ public ModelAndView plot(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ /*model.put("frame_int", "net_map_int");
+ // This view resolves to page frame_insert.jsp
+ return new ModelAndView("frame_insert", model);*/
+ return new ModelAndView("samplePage", "model", model);
+ }
+
+}
--- /dev/null
+package org.onap.portalapp.controller.sample;
+
+/**
+ * Provides controllers for EPSDK application sample pages such as call flow etc.
+ */
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.model;
+
+public class Result {
+ private String result;
+
+ public Result(String result) {
+ this.result = result;
+ }
+
+ public String getResult() {
+ return result;
+ }
+
+ public void setResult(String result) {
+ this.result = result;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.scheduler;
+
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.quartz.DisallowConcurrentExecution;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import org.quartz.PersistJobDataAfterExecution;
+import org.springframework.scheduling.quartz.QuartzJobBean;
+
+@PersistJobDataAfterExecution
+@DisallowConcurrentExecution
+public class LogJob extends QuartzJobBean {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LogJob.class);
+
+ @Override
+ protected void executeInternal(JobExecutionContext ctx)
+ throws JobExecutionException {
+ // JobDataMap dataMap = ctx.getJobDetail().getJobDataMap();
+ //int cnt = dataMap.getInt("");
+ // JobKey jobKey = ctx.getJobDetail().getKey();
+ logger.info(EELFLoggerDelegate.debugLogger, (Runtime.getRuntime().maxMemory() + " " + Runtime.getRuntime().maxMemory()));
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.scheduler;
+
+import java.text.ParseException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.onap.portalsdk.core.scheduler.CronRegistry;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.context.annotation.DependsOn;
+import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
+import org.springframework.scheduling.quartz.JobDetailFactoryBean;
+import org.springframework.stereotype.Component;
+
+@Component
+@DependsOn({ "systemProperties" })
+public class LogRegistry extends CronRegistry {
+
+ private static final String groupName = "AppGroup";
+ private static final String jobName = "LogJob";
+ private static final String triggerName = "LogTrigger";
+
+ // @Autowired
+ // private SystemProperties systemProperties;
+
+ // @Bean
+ public JobDetailFactoryBean jobDetailFactoryBean() {
+ Map<String, Object> map = new HashMap<String, Object>();
+ map.put("units", "bytes");
+ return jobDetailFactoryBean(groupName, jobName, LogJob.class, map);
+ }
+
+ // @Bean
+ public CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException {
+ // "0 * * * * ? *
+ return cronTriggerFactoryBean(groupName, triggerName, SystemProperties.getProperty(SystemProperties.LOG_CRON));
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.portalapp.service;
+
+import java.util.Set;
+
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.User;
+
+/**
+ * Defines methods that can be used to extend the features of the user/role
+ * provisioning class supplied in EPSDK-Common.
+ */
+public interface IAdminAuthExtension {
+
+ /**
+ * Invoked from OnBoardingApiServiceImpl#pushUser after user was saved. App
+ * developers can provide a class with their own logic following this
+ * action; for example, updating app's related tables
+ *
+ * @param user
+ * User object sent by Portal
+ */
+ public void saveUserExtension(User user);
+
+ /**
+ * Invoked from OnBoardingApiServiceImpl#editUser after user was updated.
+ * App developers can provide a class with their own logic following this
+ * action; for example, updating app's related tables
+ *
+ * @param user
+ * User object sent by Portal
+ */
+ public void editUserExtension(User user);
+
+ /**
+ * Invoked from OnBoardingApiServiceImpl#pushUserRole after user's roles
+ * were updated. App developers can provide a class with their own logic
+ * following this action; for example, updating app's related tables
+ *
+ * @param roles
+ * Roles object sent by Portal
+ * @param user
+ * User object sent by Portal
+ */
+ public void saveUserRoleExtension(Set<Role> roles, User user);
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.service;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.auth.LoginStrategy;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.domain.UserApp;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.client.AppContextManager;
+import org.onap.portalsdk.core.onboarding.crossapi.IPortalRestAPIService;
+import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
+import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
+import org.onap.portalsdk.core.restful.domain.EcompRole;
+import org.onap.portalsdk.core.restful.domain.EcompUser;
+import org.onap.portalsdk.core.service.RoleService;
+import org.onap.portalsdk.core.service.UserProfileService;
+import org.onap.portalsdk.core.service.WebServiceCallService;
+import org.onap.portalsdk.core.util.JSONUtil;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.slf4j.MDC;
+import org.springframework.context.ApplicationContext;
+
+/**
+ * Implements the REST API interface to answer requests made by Portal app about
+ * users and active sessions.
+ *
+ * Since an instance of this class will be instantiated by the OnBoarding
+ * servlet from the ecompFW library, we cannot use Spring injections here. This
+ * 'injection' is done indirectly using AppContextManager class.
+ *
+ */
+public class OnBoardingApiServiceImpl implements IPortalRestAPIService {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(OnBoardingApiServiceImpl.class);
+
+ private RoleService roleService;
+ private UserProfileService userProfileService;
+ private IAdminAuthExtension adminAuthExtensionServiceImpl;
+
+ private LoginStrategy loginStrategy;
+
+ public OnBoardingApiServiceImpl() {
+ // Defend against null-pointer exception during server startup
+ // that was caused by a spurious Spring annotation on this class.
+ ApplicationContext appContext = AppContextManager.getAppContext();
+ if (appContext == null)
+ throw new RuntimeException("OnBoardingApiServiceImpl ctor failed to get appContext");
+ roleService = appContext.getBean(RoleService.class);
+ userProfileService = appContext.getBean(UserProfileService.class);
+ loginStrategy = appContext.getBean(LoginStrategy.class);
+ // initialize the base class definition for Admin Auth Extension
+ adminAuthExtensionServiceImpl = appContext.getBean(IAdminAuthExtension.class);
+ }
+
+ private void setCurrentAttributes(User user, EcompUser userJson) {
+
+ user.setEmail(userJson.getEmail());
+ user.setFirstName(userJson.getFirstName());
+ user.setHrid(userJson.getHrid());
+ user.setJobTitle(userJson.getJobTitle());
+ user.setLastName(userJson.getLastName());
+ user.setLoginId(userJson.getLoginId());
+ user.setOrgManagerUserId(userJson.getOrgManagerUserId());
+ user.setMiddleInitial(userJson.getMiddleInitial());
+ user.setOrgCode(userJson.getOrgCode());
+ user.setOrgId(userJson.getOrgId());
+ user.setPhone(userJson.getPhone());
+ user.setOrgUserId(userJson.getOrgUserId());
+ user.setActive(userJson.isActive());
+ // user.setRoles(new TreeSet(userJson.getRoles()));
+ }
+
+ @Override
+ public void pushUser(EcompUser userJson) throws PortalAPIException {
+
+ if (logger.isDebugEnabled())
+ logger.debug(EELFLoggerDelegate.debugLogger, "pushUser was invoked: {}", userJson);
+ User user = new User();
+ String response = "";
+ try {
+ // Set input attributes to the object obout to be saved
+ setCurrentAttributes(user, userJson);
+ user.setRoles(new TreeSet<Role>());
+ user.setUserApps(new TreeSet<UserApp>());
+ user.setPseudoRoles(new TreeSet<Role>());
+ userProfileService.saveUser(user);
+ logger.debug(EELFLoggerDelegate.debugLogger, "push user success.");
+
+ // After successful creation, call admin auth extension
+ if (adminAuthExtensionServiceImpl != null) {
+ try {
+ adminAuthExtensionServiceImpl.saveUserExtension(user);
+ } catch (Exception ex) {
+ logger.error("pushUser: saveUserExtension failed", ex);
+ }
+ }
+
+ response = "push user success.";
+ response = JSONUtil.convertResponseToJSON(response);
+ } catch (Exception e) {
+ response = "OnboardingApiService.pushUser failed";
+ logger.error(EELFLoggerDelegate.errorLogger, response, e);
+ throw new PortalAPIException(response, e);
+ } finally {
+ MDC.remove(SystemProperties.MDC_TIMER);
+ }
+ }
+
+ @Override
+ public void editUser(String loginId, EcompUser userJson) throws PortalAPIException {
+
+ if (logger.isDebugEnabled())
+ logger.debug(EELFLoggerDelegate.debugLogger, "OnboardingApi editUser was invoked with loginID {}, JSON {}",
+ loginId, userJson);
+ User editUser = new User();
+ String response = "";
+ try {
+ setCurrentAttributes(editUser, userJson);
+ if (editUser.getOrgUserId() != null) {
+ editUser.setLoginId(editUser.getOrgUserId());
+ }
+ User domainUser = userProfileService.getUserByLoginId(loginId);
+ if (domainUser != null)
+ domainUser = JSONUtil.mapToDomainUser(domainUser, editUser);
+ else
+ domainUser = editUser;
+ userProfileService.saveUser(domainUser);
+ logger.debug(EELFLoggerDelegate.debugLogger, "edit user success.");
+
+ // After successful edit, call the admin auth extension
+ if (adminAuthExtensionServiceImpl != null) {
+ try {
+ adminAuthExtensionServiceImpl.editUserExtension(domainUser);
+ } catch (Exception ex) {
+ logger.error("editUser: editUserExtension failed", ex);
+ }
+ }
+
+ response = "edit user success.";
+ response = JSONUtil.convertResponseToJSON(response);
+ } catch (Exception e) {
+ response = "OnboardingApiService.editUser failed";
+ logger.error(EELFLoggerDelegate.errorLogger, response, e);
+ throw new PortalAPIException(response, e);
+ } finally {
+ MDC.remove(SystemProperties.MDC_TIMER);
+ }
+
+ // return response;
+ }
+
+ @Override
+ public EcompUser getUser(String loginId) throws PortalAPIException {
+ try {
+ if (logger.isDebugEnabled())
+ logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: {}", loginId);
+ User user = userProfileService.getUserByLoginId(loginId);
+ if (user == null) {
+ logger.info(EELFLoggerDelegate.debugLogger, "User + " + loginId + " doesn't exist");
+ return null;
+ // Unfortunately, Portal is not ready to accept proper error
+ // response yet ..
+ // commenting throw clauses until portal is ready
+ // throw new PortalAPIException("User + " + loginId + " doesn't
+ // exist");
+ } else
+ return UserUtils.convertToEcompUser(user);
+ } catch (Exception e) {
+ String response = "OnboardingApiService.getUser failed";
+ logger.error(EELFLoggerDelegate.errorLogger, response, e);
+ return null;
+ // Unfortunately, Portal is not ready to accept proper error response
+ // yet .. commenting throw clauses until portal is ready
+ // throw new PortalAPIException(response, e);
+ }
+
+ }
+
+ @Override
+ public List<EcompUser> getUsers() throws PortalAPIException {
+ try {
+ List<User> users = userProfileService.findAllActive();
+ List<EcompUser> ecompUsers = new ArrayList<EcompUser>();
+ for (User user : users)
+ ecompUsers.add(UserUtils.convertToEcompUser(user));
+ return ecompUsers;
+ } catch (Exception e) {
+ String response = "OnboardingApiService.getUsers failed";
+ logger.error(EELFLoggerDelegate.errorLogger, response, e);
+ throw new PortalAPIException(response, e);
+ }
+ }
+
+ @Override
+ public List<EcompRole> getAvailableRoles(String requestedLoginId) throws PortalAPIException {
+ try {
+ List<Role> roles = roleService.getActiveRoles(requestedLoginId);
+ List<EcompRole> ecompRoles = new ArrayList<EcompRole>();
+ for (Role role : roles)
+ ecompRoles.add(UserUtils.convertToEcompRole(role));
+ return ecompRoles;
+ } catch (Exception e) {
+ String response = "OnboardingApiService.getAvailableRoles failed";
+ logger.error(EELFLoggerDelegate.errorLogger, response, e);
+ throw new PortalAPIException(response, e);
+ }
+ }
+
+ @Override
+ public void pushUserRole(String loginId, List<EcompRole> rolesJson) throws PortalAPIException {
+ String response = "";
+ try {
+ if (logger.isDebugEnabled())
+ logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: {}, roles Json {}", loginId,
+ rolesJson);
+ User user = userProfileService.getUserByLoginId(loginId);
+ /*
+ * List<EcompRole> ecompRoles = mapper.readValue(rolesJson,
+ * TypeFactory.defaultInstance().constructCollectionType(List.class,
+ * EcompRole.class));
+ */
+ SortedSet<Role> roles = new TreeSet<Role>();
+ for (EcompRole role : rolesJson) {
+ roles.add(roleService.getRole(loginId,role.getId()));
+ }
+ // Replace existing roles with new ones
+ replaceExistingRoles(roles, user);
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "push user role success.");
+
+ // After successful creation, call admin auth extension
+ if (adminAuthExtensionServiceImpl != null) {
+ try {
+ adminAuthExtensionServiceImpl.saveUserRoleExtension(roles, user);
+ } catch (Exception ex) {
+ logger.error("pushUserRole: saveUserRoleExtension failed", ex);
+ }
+ }
+ response = "push user role success.";
+ response = JSONUtil.convertResponseToJSON(response);
+
+ } catch (Exception e) {
+ response = "OnboardingApiService.pushUserRole failed";
+ logger.error(EELFLoggerDelegate.errorLogger, response, e);
+ throw new PortalAPIException(response, e);
+ } finally {
+ MDC.remove(SystemProperties.MDC_TIMER);
+ }
+
+ }
+
+ @Override
+ public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException {
+ if (logger.isDebugEnabled())
+ logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: {}", loginId);
+ List<EcompRole> ecompRoles = new ArrayList<EcompRole>();
+ try {
+ User user = userProfileService.getUserByLoginId(loginId);
+ SortedSet<Role> currentRoles = null;
+ if (user != null) {
+ currentRoles = user.getRoles();
+ if (currentRoles != null)
+ for (Role role : currentRoles)
+ ecompRoles.add(UserUtils.convertToEcompRole(role));
+ }
+ return ecompRoles;
+ } catch (Exception e) {
+ String response = "OnboardingApiService.getUserRoles failed";
+ logger.error(EELFLoggerDelegate.errorLogger, response, e);
+ throw new PortalAPIException(response, e);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void replaceExistingRoles(SortedSet<Role> roles, User user) {
+ // 1. remove existing roles
+ Set<UserApp> userApps = user.getUserApps();
+ Iterator<UserApp> appsItr = userApps.iterator();
+ while (appsItr.hasNext()) {
+ UserApp tempUserApp = appsItr.next();
+ boolean roleFound = false;
+ for (Role role : roles) {
+ if (tempUserApp.getRole().getId().equals(role.getId())) {
+ roleFound = true;
+ break;
+ }
+ }
+ if (!roleFound)
+ appsItr.remove();
+ }
+ user.setUserApps(userApps);
+ userProfileService.saveUser(user);
+
+ // 2. add new roles
+ user.setRoles(roles);
+ userProfileService.saveUser(user);
+ }
+
+ @Override
+ public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException {
+ WebServiceCallService securityService = AppContextManager.getAppContext().getBean(WebServiceCallService.class);
+ try {
+ String appUser = request.getHeader("username");
+ String password = request.getHeader("password");
+ // System.out.println("username = " + appUser);
+ // System.out.println("password = " + password);
+ boolean flag = securityService.verifyRESTCredential(null, appUser, password);
+ // System.out.println("username = " + appUser);
+ // System.out.println("password = " + password);
+ return flag;
+
+ } catch (Exception e) {
+ String response = "OnboardingApiService.isAppAuthenticated failed";
+ logger.error(EELFLoggerDelegate.errorLogger, response, e);
+ throw new PortalAPIException(response, e);
+ }
+ }
+
+ public String getSessionTimeOuts() throws Exception {
+ return PortalTimeoutHandler.gatherSessionExtensions();
+ }
+
+ public void updateSessionTimeOuts(String sessionMap) throws Exception {
+ PortalTimeoutHandler.updateSessionExtensions(sessionMap);
+ }
+
+ @Override
+ public String getUserId(HttpServletRequest request) throws PortalAPIException {
+ return loginStrategy.getUserId(request);
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.util;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.filter.Filter;
+import ch.qos.logback.core.spi.FilterReply;
+
+/**
+ * Custom Filter class bind with logback.xml
+ * configuration file to strip out certain log messages
+ * coming out of special packages or classes.
+ *
+ */
+public class CustomLoggingFilter extends Filter<ILoggingEvent> {
+
+ /**
+ * Custom Filter is added to strip out the continuous U-EB logging messages.
+ * But make sure we log the ERROR & WARNING Level messages.
+ */
+ @Override
+ public FilterReply decide(ILoggingEvent event) {
+ try {
+ if ((event.getLevel() != Level.ERROR || event.getLevel() != Level.WARN) &&
+ (event.getThreadName().equalsIgnoreCase("UEBConsumerThread")) &&
+ (event.getLoggerName().contains("org.openecomp.nsa") || event.getLoggerName().contains("org.apache.http"))
+ ) {
+ return FilterReply.DENY;
+ } else {
+ return FilterReply.NEUTRAL;
+ }
+ } catch(Exception e) {
+ return FilterReply.NEUTRAL;
+ }
+ }
+}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-public class AdminController {
- @Controller
- @RequestMapping("/")
- public class AngularSinglePageController extends RestrictedBaseController {
-
- @RequestMapping(value = { "/admin" }, method = RequestMethod.GET)
- public ModelAndView view(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- return new ModelAndView("admin", "model", model);
- }
-
- @RequestMapping(value = { "/admin2" }, method = RequestMethod.GET)
- public ModelAndView adminView(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- return new ModelAndView("admin2", "model", model);
- }
-
-
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-@Controller
-@RequestMapping("/")
-public class AngularAdminController extends RestrictedBaseController{
-
- @RequestMapping(value = {"/userProfile" }, method = RequestMethod.GET)
- public ModelAndView view(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
-
- return new ModelAndView("user_profile_list","model", model);
- }
-
- @RequestMapping(value = {"/admin" }, method = RequestMethod.GET)
- public ModelAndView adminView(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
-
- return new ModelAndView(getViewName(),"model", model);
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-/**
- * Controller for welcome view. The view is restricted to authenticated users.
- * The view name defaults to the request name with no suffix, "bootstrap_sample", which
- * resolves to page welcome.jsp.
- */
-@Controller
-@RequestMapping("/")
-public class BootstrapSampleController extends RestrictedBaseController {
- @RequestMapping(value = { "/bootstrap_sample" }, method = RequestMethod.GET)
- public ModelAndView welcome(HttpServletRequest request) {
- final String defaultViewName = null;
- return new ModelAndView(defaultViewName);
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.io.PrintWriter;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.jcs.JCS;
-import org.apache.jcs.admin.CacheRegionInfo;
-import org.apache.jcs.admin.JCSAdminBean;
-import org.apache.jcs.engine.behavior.ICacheElement;
-import org.json.JSONArray;
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
-
-@Controller
-@RequestMapping("/")
-public class CacheAdminController extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CacheAdminController.class);
-
- private JCSAdminBean jcsAdminBean = new JCSAdminBean();
-
- @RequestMapping(value = { "/jcs_admin" }, method = RequestMethod.GET)
- public ModelAndView cacheAdmin(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
-
- model.put("model", getRegions());
-
- return new ModelAndView(getViewName(), model);
- }
-
- @RequestMapping(value = { "/get_regions" }, method = RequestMethod.GET)
- public void getRegions(HttpServletRequest request, HttpServletResponse response) {
- try {
- JsonMessage msg = new JsonMessage(getRegions().toString());
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getRegions failed", e);
- }
- }
-
- @RequestMapping(value = { "/jcs_admin/clearRegion" }, method = RequestMethod.GET)
- public void clearRegion(HttpServletRequest request, HttpServletResponse response) throws Exception {
- String cacheName = (String) request.getParameter("cacheName");
- clearCacheRegion(cacheName);
-
- response.setContentType("application/json");
- PrintWriter out = response.getWriter();
- out.write(getRegions().toString());
- }
-
- @RequestMapping(value = { "/jcs_admin/clearAll" }, method = RequestMethod.GET)
- public void clearAll(HttpServletRequest request, HttpServletResponse response) throws Exception {
- clearAllRegions();
-
- response.setContentType("application/json");
- PrintWriter out = response.getWriter();
- out.write(getRegions().toString());
- }
-
- @RequestMapping(value = { "/jcs_admin/clearItem" }, method = RequestMethod.GET)
- public void clearItem(HttpServletRequest request, HttpServletResponse response) throws Exception {
- String keyName = (String) request.getParameter("keyName");
- String cacheName = (String) request.getParameter("cacheName");
- clearCacheRegionItem(cacheName, keyName);
-
- response.setContentType("application/json");
- PrintWriter out = response.getWriter();
- out.write(getRegions().toString());
- }
-
- @RequestMapping(value = { "/jcs_admin/showItemDetails" }, method = RequestMethod.GET)
- public void showItemDetails(HttpServletRequest request, HttpServletResponse response) throws Exception {
- String cacheName = (String) request.getParameter("cacheName");
- String keyName = (String) request.getParameter("keyName");
- String details = null;
-
- try {
- details = getItemDetails(cacheName, keyName);
- } catch (Exception e) {
- details = "There was an error retrieving the region details. Please try again.";
- logger.error(EELFLoggerDelegate.errorLogger, "showItemDetails failed for cache name " + cacheName, e);
- }
- JSONObject j = new JSONObject(details);
- response.setContentType("application/json");
- // response.setContentType("text/plain");
- PrintWriter out = response.getWriter();
- out.write(j.toString());
- }
-
- @RequestMapping(value = { "/jcs_admin/showRegionDetails" }, method = RequestMethod.GET)
- public void showRegionDetails(HttpServletRequest request, HttpServletResponse response) throws Exception {
- String cacheName = (String) request.getParameter("cacheName");
- String details = null;
- ObjectMapper mapper = new ObjectMapper();
- JSONObject j = null;
- try {
- details = getRegionStats(cacheName);
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(details));
- j = new JSONObject(msg);
-
- } catch (Exception e) {
- details = "There was an error retrieving the region details. Please try again.";
- logger.error(EELFLoggerDelegate.errorLogger, "showRegionDetailed failed for cache name " + cacheName, e);
- }
-
- response.setContentType("application/json");
-
- PrintWriter out = response.getWriter();
- // out.write(details);
- out.write(j.toString());
- }
-
- @SuppressWarnings("unchecked")
- public JSONArray getRegions() {
- LinkedList<CacheRegionInfo> regions = null;
- JSONArray ja = new JSONArray();
- try {
- regions = getJcsAdminBean().buildCacheInfo();
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
- for (CacheRegionInfo cri : regions) {
- if (cri.getCache().getCacheName() != null && !cri.getCache().getCacheName().equals("[object Object]")) {
- JSONObject jo = new JSONObject();
- jo.put("cacheName", cri.getCache().getCacheName());
- jo.put("size", cri.getCache().getSize());
- jo.put("byteCount", cri.getByteCount());
- jo.put("status", cri.getStatus());
- jo.put("hitCountRam", cri.getCache().getHitCountRam());
- jo.put("hitCountAux", cri.getCache().getHitCountAux());
- jo.put("missCountNotFound", cri.getCache().getMissCountNotFound());
- jo.put("missCountExpired", cri.getCache().getMissCountExpired());
- jo.put("items",
- new JSONArray(mapper.writeValueAsString(getRegionItems(cri.getCache().getCacheName()))));
- ja.put(jo);
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getRegions failed", e);
- }
-
- return ja;
- }
-
- private String getRegionStats(String cacheName) throws Exception {
- String stats = "";
-
- JCS cache = JCS.getInstance(cacheName);
- stats = cache.getStats();
-
- return stats;
- }
-
- private String getItemDetails(String cacheName, String keyName) throws Exception {
- String details = "";
-
- JCS cache = JCS.getInstance(cacheName);
- ICacheElement element = cache.getCacheElement(keyName);
-
- if (element != null) {
- ObjectMapper mapper = new ObjectMapper();
- mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
- details = mapper.writeValueAsString(element);
- }
-
- return details;
- }
-
- @SuppressWarnings("rawtypes")
- private List getRegionItems(String cacheName) {
- List items = null;
-
- try {
- items = getJcsAdminBean().buildElementInfo(cacheName);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getRegionItems failed for cache name " + cacheName, e);
- }
- return items;
- }
-
- private void clearAllRegions() {
- try {
- getJcsAdminBean().clearAllRegions();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "clearAllRegions faield", e);
- }
- }
-
- private void clearCacheRegion(String cacheName) {
- try {
- getJcsAdminBean().clearRegion(cacheName);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "clearCacheRegion failed for cache name " + cacheName, e);
- }
- }
-
- private void clearCacheRegionItem(String cacheName, String keyName) {
- try {
- getJcsAdminBean().removeItem(cacheName, keyName);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "clearCacheRegionItem failed for key name " + keyName, e);
- }
- }
-
- public JCSAdminBean getJcsAdminBean() {
- return jcsAdminBean;
- }
-
- public void setJcsAdminBean(JCSAdminBean jcsAdminBean) {
- this.jcsAdminBean = jcsAdminBean;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import org.json.JSONArray;
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.App;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.aspect.AuditLog;
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.rest.FavoritesClient;
-import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
-import org.openecomp.portalsdk.core.service.AppService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-
-@Controller
-@RequestMapping("/")
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@AuditLog
-public class FavoritesController extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FavoritesController.class);
-
- @Autowired
- private AppService appService;
-
- /**
- * Makes the REST API call to Portal Back-end and retrieves Favorite menu
- * items for the currently logged in user.
- *
- * @param request
- * @param response
- */
- @RequestMapping(value = { "/get_favorites" }, method = RequestMethod.GET)
- public void getFavorites(HttpServletRequest request, HttpServletResponse response) {
- String appName = "";
- String requestId = "";
- String appUserName = "";
- String decryptedPwd = "";
-
- try {
- HttpSession session = request.getSession();
- User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
- if (user == null || user.getId() == null) {
- logger.info(EELFLoggerDelegate.errorLogger,
- ("Http request did not contain user info, cannot retrieve favorites."));
-
- response.setContentType("application/json");
- JSONArray jsonResponse = new JSONArray();
- JSONObject error = new JSONObject();
- error.put("error", "Http request did not contain user info, cannot retrieve favorites.");
- jsonResponse.put(error);
- response.getWriter().write(jsonResponse.toString());
- } else {
- logger.info(EELFLoggerDelegate.errorLogger,
- "Retrieving Favorites for the user '" + MDC.get(SystemProperties.MDC_LOGIN_ID) + "'.");
-
- App app = appService.getDefaultApp();
- if (app!=null) {
- appName = app.getName();
- appUserName = app.getUsername();
- try{
- decryptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key));
- } catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: " + e.getMessage());
- }
- } else {
- logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database.");
- appName = SystemProperties.SDK_NAME;
- }
- requestId = MDC.get(MDC_KEY_REQUEST_ID);
-
- String jsonResponse = FavoritesClient.getFavorites(MDC.get(SystemProperties.MDC_LOGIN_ID), appName, requestId, appUserName, decryptedPwd);
-
- logger.debug(EELFLoggerDelegate.debugLogger, "FavoritesMenu response: " + jsonResponse);
-
- response.setContentType("application/json");
- response.getWriter().write(jsonResponse);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred in FavoritesController.getFavorites while performing get_favorites. Details: "
- + e.getMessage(), AlarmSeverityEnum.MINOR);
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.Menu;
-import org.openecomp.portalsdk.core.domain.MenuData;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.FnMenuService;
-import org.openecomp.portalsdk.core.service.FunctionalMenuListService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-/**
- * A controller for Admin to add/edit/delete menu items from FN_MENU.
- */
-
-@Controller
-@RequestMapping("/")
-public class FnMenuController extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnMenuController.class);
-
- @Autowired
- FnMenuService service;
-
- @Autowired
- FunctionalMenuListService functionalMenuListService;
-
- private String viewName;
-
- @RequestMapping(value = { "/admin_fn_menu/get_parent_list" }, method = RequestMethod.GET)
- public void getParentList(HttpServletRequest request, HttpServletResponse response) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- try {
- response.getWriter().write(mapper.writeValueAsString(service.getParentList()));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getParentListFailed", e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- }
- }
-
- @RequestMapping(value = { "/admin_fn_menu/get_function_cd_list" }, method = RequestMethod.GET)
- public void getFunctionCDList(HttpServletRequest request, HttpServletResponse response) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- try {
- response.getWriter().write(mapper.writeValueAsString(functionalMenuListService.getFunctionCDList(request)));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getFunctionCDList", e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- }
-
- }
-
- @RequestMapping(value = { "/admin_fn_menu" }, method = RequestMethod.GET)
- public void getFnMenuList(HttpServletRequest request, HttpServletResponse response) {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- List<MenuData> temp = null;
- List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>();
- List<MenuData> parentList = new ArrayList<>();
-
- try {
- temp = service.getFnMenuItems();
- for (MenuData menu : temp) {
- MenuData parentData = new MenuData();
- parentData.setId(menu.getId());
- parentData.setLabel(menu.getLabel());
- if (menu.getParentMenu() != null) {
- parentData.setParentId(menu.getParentMenu().getId());
- }
- parentData.setAction(menu.getAction());
- parentData.setFunctionCd(menu.getFunctionCd());
- parentData.setImageSrc(menu.getImageSrc());
- parentData.setSortOrder(menu.getSortOrder());
- parentData.setActive(menu.isActive());
- parentData.setServlet(menu.getServlet());
- parentData.setQueryString(menu.getQueryString());
- parentData.setExternalUrl(menu.getExternalUrl());
- parentData.setTarget(menu.getTarget());
- parentData.setMenuSetCode(menu.getMenuSetCode());
- parentData.setSeparator(menu.isSeparator());
- parentData.setImageSrc(menu.getImageSrc());
- parentList.add(parentData);
- List<MenuData> tempList = new ArrayList<MenuData>();
- // int countChildAction = 0;
- /*
- * for(Object o:menu.getChildMenus()){ Menu m = (Menu)o; Menu
- * data = new Menu(); data.setId(m.getId());
- * data.setLabel(m.getLabel()); data.setAction(m.getAction());
- * data.setImageSrc(m.getImageSrc()); tempList.add(data); }
- */
- childItemList.add(tempList);
- }
- model.put("fnMenuItems", parentList);
- // JsonMessage msg = new
- // JsonMessage(mapper.writeValueAsString(parentList),mapper.writeValueAsString(childItemList),"none");
-
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getFnMenuList failed", e);
- }
-
- }
-
- @RequestMapping(value = { "/admin_fn_menu/updateFnMenu" }, method = RequestMethod.POST)
- public ModelAndView updateFnMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- Menu fnMenuItem = mapper.readValue(root.get("availableFnMenuItem").toString(), Menu.class);
-
- service.saveFnMenu(fnMenuItem);
- request.getSession()
- .removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
- request.getSession().removeAttribute(SystemProperties.LEFT_MENU_CHILDREND);
- request.getSession().removeAttribute(SystemProperties.LEFT_MENU_PARENT);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(service.getMenuItem(fnMenuItem.getId()));
-
- out.write(responseString);
-
- return null;
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "updateFnMenu failed", e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- }
- return null;
-
- }
-
- @RequestMapping(value = { "/admin_fn_menu/removeMenuItem" }, method = RequestMethod.POST)
- public ModelAndView removeFnMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- Menu fnMenuItem = mapper.readValue(root.get("fnMenuItem").toString(), Menu.class);
- Menu fnMenuItemRow = service.getMenuItemRow(fnMenuItem.getId());
-
- service.removeMenuItem(fnMenuItemRow);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(service.getMenuItem(fnMenuItem.getId()));
- out.write(responseString);
-
- return null;
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "removeFnMenu failed", e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- }
- return null;
-
- }
-
- public String getViewName() {
- return viewName;
- }
-
- public void setViewName(String viewName) {
- this.viewName = viewName;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
-
-import java.io.IOException;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONArray;
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.App;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.aspect.AuditLog;
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.rest.FunctionalMenuClient;
-import org.openecomp.portalsdk.core.onboarding.ueb.UebException;
-import org.openecomp.portalsdk.core.onboarding.ueb.UebManager;
-import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg;
-import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes;
-import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-import org.openecomp.portalsdk.core.service.AppService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-
-@Controller
-@RequestMapping("/")
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-public class FuncMenuController extends RestrictedBaseController{
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FuncMenuController.class);
-
- @Autowired
- AppService appService;
-
- @AuditLog
- @RequestMapping(value = {"/get_functional_menu" }, method = RequestMethod.GET)
- public void functionalMenu(HttpServletRequest request, HttpServletResponse response) {
-
- User user = UserUtils.getUserSession(request);
- //JSONArray validMenu = new JSONArray("[{\"menuId\":140,\"column\":1,\"text\":\"RT SDK Menu\",\"parentMenuId\":139,\"url\":\"http://www.cnn.com\"},{\"menuId\":139,\"column\":1,\"text\":\"RT Menu\",\"parentMenuId\":11,\"url\":\"\"},{\"menuId\":11,\"column\":1,\"text\":\"Product Design\",\"parentMenuId\":1,\"url\":\"\"},{\"menuId\":1,\"column\":1,\"text\":\"Design\",\"url\":\"\"}]");
-
- try {
- if ( user != null ) {
- String useRestForFunctionalMenu = PortalApiProperties.getProperty(PortalApiConstants.USE_REST_FOR_FUNCTIONAL_MENU);
- String funcMenuJsonString = "";
- if (useRestForFunctionalMenu==null || useRestForFunctionalMenu=="" || useRestForFunctionalMenu.equalsIgnoreCase("false")) {
- logger.info(EELFLoggerDelegate.errorLogger, "Making use of UEB communication and Requesting functional menu for user " + user.getOrgUserId());
- funcMenuJsonString = getFunctionalMenu(user.getOrgUserId());
- } else {
- funcMenuJsonString = getFunctionalMenuViaREST(user.getOrgUserId());
- }
- response.setContentType("application/json");
- response.getWriter().write(funcMenuJsonString);
- } else {
- logger.info(EELFLoggerDelegate.errorLogger, "Http request did not contain user info, cannot retrieve functional menu");
- response.setContentType("application/json");
- JSONArray jsonResponse = new JSONArray();
- JSONObject error = new JSONObject();
- error.put("error","Http request did not contain user info, cannot retrieve functional menu");
- jsonResponse.put(error);
- response.getWriter().write(jsonResponse.toString());
- }
- } catch (Exception e) {
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application/json");
- JSONArray jsonResponse = new JSONArray();
- JSONObject error = new JSONObject();
- try {
- if ( null == e.getMessage() ) {
- error.put("error","No menu data");
- } else {
- error.put("error",e.getMessage());
- }
- jsonResponse.put(error);
- response.getWriter().write(jsonResponse.toString());
- logger.error(EELFLoggerDelegate.errorLogger, "Error getting functional_menu: " + e.getMessage(),AlarmSeverityEnum.MAJOR);
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
-
- }
-
- //--------------------------------------------------------------------------
- // Makes a synchronous call to ECOMP Portal to get the JSON file that
- // contains the contents of the functional menu. The JSON file will be
- // in the payload of the returned UEB message.
- //--------------------------------------------------------------------------
- private String getFunctionalMenu(String userId) throws UebException
- {
- String returnString = null;
- UebMsg funcMenuUebMsg = null;
- UebMsg msg = new UebMsg();
- msg.putMsgType(UebMsgTypes.UEB_MSG_TYPE_GET_FUNC_MENU);
- msg.putUserId(userId);
- funcMenuUebMsg = UebManager.getInstance().requestReply(msg);
- if (funcMenuUebMsg != null) {
- if (funcMenuUebMsg.getPayload().startsWith("Error:")) {
- logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenu received an error in UEB msg = " + funcMenuUebMsg.getPayload());
- } else {
- returnString = funcMenuUebMsg.getPayload();
- }
- }
-
- logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenu response: " + returnString);
-
- return returnString;
- }
-
- private String getFunctionalMenuViaREST(String userId) {
- String appName = "";
- String requestId = "";
- String appUserName = "";
- String decryptedPwd = "";
-
- logger.info(EELFLoggerDelegate.debugLogger, "Making use of REST API communication and Requesting functional menu for user " + userId);
-
- App app = appService.getDefaultApp();
- if (app!=null) {
- appName = app.getName();
- appUserName = app.getUsername();
- try{
- decryptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key));
- } catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: " + e.toString());
- }
- } else {
- logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database.");
- appName = SystemProperties.SDK_NAME;
- }
- requestId = MDC.get(MDC_KEY_REQUEST_ID);
-
- String fnMenu = null;
- try {
- fnMenu = FunctionalMenuClient.getFunctionalMenu(userId, appName, requestId, appUserName, decryptedPwd);
- }catch(Exception ex) {
- fnMenu = "Failed to get functional menu: " + ex.toString();
- }
-
- logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenu response: {}", fnMenu);
-
- return fnMenu;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalsdk.core.controller.UnRestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
-import org.springframework.web.servlet.ModelAndView;
-
-@Controller
-@RequestMapping("/")
-public class LogoutController extends UnRestrictedBaseController{
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LogoutController.class);
-
- private User user;
-
- /**
- * @param request
- * @param response
- * @return modelView
- *
- * globalLogout will invalid the current application session, then redirects to portal logout
- */
- @RequestMapping(value = {"/logout.htm" }, method = RequestMethod.GET)
- public ModelAndView globalLogout(HttpServletRequest request, HttpServletResponse response) {
- ModelAndView modelView = null;
- try{
- chatRoomLogout(request);
- request.getSession().invalidate();
- String portalUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
- String portalDomain = portalUrl.substring(0, portalUrl.lastIndexOf('/'));
- String redirectUrl = portalDomain+"/logout.htm";
- modelView = new ModelAndView("redirect:"+redirectUrl);
- }catch(Exception e){
- logger.error(EELFLoggerDelegate.errorLogger, "Logout Error: " + e.getMessage(),AlarmSeverityEnum.MAJOR);
- }
- return modelView;
- }
-
- /**
- * @param request
- * @param response
- * @return modelView
- *
- * appLogout is a function that will invalid the current session (application logout) and redirects user to Portal.
- */
- @RequestMapping(value = {"/app_logout.htm" }, method = RequestMethod.GET)
- public ModelAndView appLogout(HttpServletRequest request, HttpServletResponse response) {
- ModelAndView modelView = null;
- try{
- chatRoomLogout(request);
- modelView = new ModelAndView("redirect:"+PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL));
- UserUtils.clearUserSession(request);
- request.getSession().invalidate();
- }catch(Exception e){
- logger.error(EELFLoggerDelegate.errorLogger, "Application Logout Error: " + e.getMessage(),AlarmSeverityEnum.MAJOR);
- }
- return modelView;
- }
-
-
- public void chatRoomLogout(HttpServletRequest request){
- request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
- setUser(UserUtils.getUserSession(request));
- // if(getUser()!=null){
- // Long login_IdLong = getUser().getId();
- // String name = getUser().getFirstName();
- // String login_IdStr = Long.toString(login_IdLong);
- // }
- //UserListName.getInstance().delUserName(name);
- //UserListID.getInstance().delUserName(login_IdStr);
- }
-
- public User getUser() {
- return user;
- }
-
- public void setUser(User user) {
- this.user = user;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.jar.Attributes;
-import java.util.jar.Manifest;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-import org.springframework.web.bind.annotation.RestController;
-
-/**
- * This controller responds to a request for the web application manifest,
- * returning a JSON with the information that was created at build time.
- *
- * Manifest entries have names with hyphens, which means Javascript code can't
- * simply use the shorthand object.key; instead use object['key'].
- */
-@RestController
-@RequestMapping("/")
-public class ManifestController extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ManifestController.class);
-
- /**
- * Required to obtain the webapp manifest.
- */
- @Autowired
- private ServletContext context;
-
- /** Path to resource on classpath */
- private final String MANIFEST_RESOURCE_PATH = "/META-INF/MANIFEST.MF";
-
- /**
- * Gets the content of the webapp manifest file META-INF/MANIFEST.MF.
- *
- * @return Attributes object with key-value pairs from the manifest
- * @throws IOException
- */
- private Attributes getWebappManifest() throws IOException {
- // Manifest is formatted as Java-style properties
- InputStream inputStream = context.getResourceAsStream(MANIFEST_RESOURCE_PATH);
- if (inputStream == null)
- throw new IOException("getWebappManifest: failed to get resource at path " + MANIFEST_RESOURCE_PATH);
- Manifest manifest = new Manifest(inputStream);
- inputStream.close();
- return manifest.getMainAttributes();
- }
-
- /**
- * Gets the webapp manifest contents as a JSON object.
- *
- * @param request
- * @return A map of key-value pairs. On success:
- *
- * <pre>
- * {
- * "key1": "value1",
- * "key2": "value2"
- * }
- * </pre>
- *
- * On failure:
- *
- * <pre>
- * { "error": "message" }
- * </pre>
- */
- @RequestMapping(value = { "/manifest" }, method = RequestMethod.GET, produces = "application/json")
- @ResponseBody
- public Map<Object, Object> getManifest(HttpServletRequest request) {
- try {
- Attributes attributes = getWebappManifest();
- return attributes;
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "getManifest failed", ex);
- Map<Object, Object> response = new HashMap<Object, Object>();
- response.put("error", "failed to get manifest: " + ex.toString());
- return response;
- }
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.MenuData;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-import org.openecomp.portalsdk.core.restful.client.SharedContextRestClient;
-import org.openecomp.portalsdk.core.restful.domain.SharedContext;
-import org.openecomp.portalsdk.core.service.FnMenuService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.ModelAttribute;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Controller
-@RequestMapping("/")
-public class MenuListController extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MenuListController.class);
-
- @Autowired
- private FnMenuService fnMenuService;
- @Autowired
- private SharedContextRestClient sharedContextRestClient;
-
- /**
- *
- * Gets Menu items and stores into session.
- *
- * @param request
- * @param response
- */
- @SuppressWarnings("unchecked")
- @RequestMapping(value = { "/get_menu" }, method = RequestMethod.GET)
- public void getMenu(HttpServletRequest request, HttpServletResponse response) {
- logger.debug(EELFLoggerDelegate.debugLogger, "getMenu begins");
- try {
- ObjectMapper mapper = new ObjectMapper();
- Set<MenuData> menuResult = null;
- HttpSession session = request.getSession();
- List<List<MenuData>> childItemList = (List<List<MenuData>>) session
- .getAttribute(SystemProperties.LEFT_MENU_CHILDREND);
- List<MenuData> parentList = (List<MenuData>) session.getAttribute(SystemProperties.LEFT_MENU_PARENT);
- if (parentList == null || childItemList == null || parentList.size() == 0 || childItemList.size() == 0) {
- childItemList = new ArrayList<List<MenuData>>();
- parentList = new ArrayList<MenuData>();
- menuResult = (Set<MenuData>) session
- .getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
- fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult);
- logger.debug(EELFLoggerDelegate.debugLogger, "storing leftmenu items into session");
- session.setAttribute(SystemProperties.LEFT_MENU_PARENT, parentList);
- session.setAttribute(SystemProperties.LEFT_MENU_CHILDREND, childItemList);
- }
- String userName = (String) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(parentList),
- mapper.writeValueAsString(childItemList), userName);
- JSONObject j = new JSONObject(msg);
- response.setContentType("application/json");
- response.getWriter().write(j.toString());
- logger.debug(EELFLoggerDelegate.debugLogger, "getMenu ends");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getMenu failed", e);
- }
- }
-
- /**
- *
- * Gets app name from system.properties file.
- *
- * @param request
- * @param response
- */
- @RequestMapping(value = { "/get_app_name" }, method = RequestMethod.GET)
- public void getAppName(HttpServletRequest request, HttpServletResponse response) {
- logger.debug(EELFLoggerDelegate.debugLogger, "getAppName begins");
- HttpSession session = request.getSession(true);
- try {
- String appName = (String) session
- .getAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME));
- if (appName != null && appName.equals("app_display_name")) {
- appName = "";
- }
- JsonMessage msg = new JsonMessage(appName);
- JSONObject j = new JSONObject(msg);
- response.setContentType("application/json");
- response.getWriter().write(j.toString());
- logger.debug(EELFLoggerDelegate.debugLogger, "getAppName ends");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getAppName failed", e);
- }
- }
-
- /**
- * Apparently unused?
- *
- * @param request
- * @return Map with childItemList and parentList keys, associated values.
- */
- @SuppressWarnings("unchecked")
- @ModelAttribute("menu")
- public Map<String, Object> getLeftMenuJSP(HttpServletRequest request) {
- logger.debug(EELFLoggerDelegate.debugLogger, "getLeftMenuJSP begins");
- ObjectMapper mapper = new ObjectMapper();
- Map<String, Object> model = new HashMap<String, Object>();
- try {
- HttpSession session = request.getSession();
- List<List<MenuData>> childItemList = (List<List<MenuData>>) session
- .getAttribute(SystemProperties.LEFT_MENU_CHILDREND);
- List<MenuData> parentList = (List<MenuData>) session.getAttribute(SystemProperties.LEFT_MENU_PARENT);
- if (parentList == null || childItemList == null) {
- childItemList = new ArrayList<List<MenuData>>();
- parentList = new ArrayList<MenuData>();
- Set<MenuData> menuResult = (Set<MenuData>) session
- .getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
- fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult);
- session.setAttribute(SystemProperties.LEFT_MENU_PARENT, parentList);
- session.setAttribute(SystemProperties.LEFT_MENU_CHILDREND, childItemList);
- }
- model.put("childItemList", mapper.writeValueAsString(childItemList));
- model.put("parentList", mapper.writeValueAsString(parentList));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getLeftMenuJSP failed", e);
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "getLeftMenuJSP ends");
- return model;
- }
-
- /**
- * Answers requests for user information, which is fetched from the shared
- * context at Portal.
- *
- * @param request
- * @param response
- */
- @RequestMapping(value = { "/get_userinfo" }, method = RequestMethod.GET)
- public void getUserInfo(HttpServletRequest request, HttpServletResponse response) {
- logger.debug(EELFLoggerDelegate.debugLogger, "getUserInfo begins");
- try {
- String contextId = null;
- if (request.getCookies() != null) {
- for (Cookie ck : request.getCookies()) {
- if (ck.getName().equalsIgnoreCase("EPService"))
- contextId = ck.getValue();
- }
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "getUserInfo: ContextId is : " + contextId);
- List<SharedContext> sharedContextRes = sharedContextRestClient.getUserContext(contextId);
- logger.debug(EELFLoggerDelegate.debugLogger, "getUserInfo: Shared Context Response is {}",
- sharedContextRes);
- Map<String, Object> model = new HashMap<String, Object>();
- for (SharedContext sharedContext : sharedContextRes) {
- model.put(sharedContext.getCkey(), sharedContext.getCvalue());
- }
- JSONObject j = new JSONObject(model);
- response.setContentType("application/json");
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getUserInfo failed", e);
- }
- }
-
- /**
- * Get User information from app sessions
- *
- * @param request
- * @param response
- */
- @RequestMapping(value = { "/get_topMenuInfo" }, method = RequestMethod.GET)
- public void getTopMenu(HttpServletRequest request, HttpServletResponse response) {
-
- HttpSession session = request.getSession();
- try {
- String userName = (String) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME));
- String firstName = (String) session.getAttribute(SystemProperties.FIRST_NAME);
- String lastName = (String) session.getAttribute(SystemProperties.LAST_NAME);
- User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
- Map<String, String> map = new HashMap<String, String>();
- String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
- String portalDomain = redirectUrl.substring(0, redirectUrl.lastIndexOf('/'));
- String portalUrl = portalDomain + "/process_csp";
- String getAccessUrl = portalDomain + "/get_access";
- String contactUsLink = SystemProperties.getProperty(SystemProperties.CONTACT_US_LINK);
- map.put("portalUrl", portalUrl);
- map.put("contactUsLink", contactUsLink);
- map.put("userName", userName);
- map.put("firstName", firstName);
- map.put("lastName", lastName);
- map.put("userid", user.getOrgUserId());
- map.put("email", user.getEmail());
- map.put("getAccessUrl", getAccessUrl);
- JSONObject j = new JSONObject(map);
- response.setContentType("application/json");
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed to serialize JSON", e);
- }
-
- }
-
- @RequestMapping(value = { "/page_redirect" }, method = RequestMethod.GET)
- public void pageRedirect(HttpServletRequest request, HttpServletResponse response) {
- String pageToURL = null;
- try {
- String pageTo = request.getParameter("page");
- if (pageTo.equals("contact"))
- pageToURL = SystemProperties.getProperty(SystemProperties.CONTACT_US_LINK);
- else if (pageTo.equals("access")) {
- String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
- String portalDomain = redirectUrl.substring(0, redirectUrl.lastIndexOf('/'));
- pageToURL = portalDomain + "/get_access";
- }
- response.getWriter().write(pageToURL);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "pageRedirect failed", e);
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.command.PostSearchBean;
-import org.openecomp.portalsdk.core.command.support.SearchResult;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.Lookup;
-import org.openecomp.portalsdk.core.domain.Profile;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.LdapService;
-import org.openecomp.portalsdk.core.service.PostSearchService;
-import org.openecomp.portalsdk.core.service.ProfileService;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.ModelAttribute;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Controller
-@RequestMapping("/")
-public class PostSearchController extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostSearchController.class);
-
- @SuppressWarnings("rawtypes")
- private static List sortByList = null;
-
- @Autowired
- private PostSearchService postSearchService;
-
- @Autowired
- private LdapService ldapService;
-
- @Autowired
- private ProfileService profileService;
-
- @RequestMapping(value = { "/post_search" }, method = RequestMethod.GET)
- public ModelAndView welcome(HttpServletRequest request,
- @ModelAttribute("postSearchBean") PostSearchBean postSearchBean) {
- Map<String, Object> model = new HashMap<String, Object>();
-
- ObjectMapper mapper = new ObjectMapper();
- try {
- postSearchBean = new PostSearchBean();
- model.put("profileList", mapper.writeValueAsString(postSearchBean.getSearchResult()));
- model.put("postSearchBean", mapper.writeValueAsString(postSearchBean));
- model.put("existingUsers", mapper.writeValueAsString(getExistingUsers()));
- model.put("sortByList", mapper.writeValueAsString(getSortByList()));
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "welcome: failed to write JSON" + ex.getMessage());
- }
-
- return new ModelAndView(getViewName(), model);
- }
-
- @RequestMapping(value = { "/post_search_sample" }, method = RequestMethod.GET)
- public void getPostSearchProfile(HttpServletRequest request, HttpServletResponse response,
- @ModelAttribute("postSearchBean") PostSearchBean postSearchBean) {
- Map<String, Object> model = new HashMap<String, Object>();
-
- ObjectMapper mapper = new ObjectMapper();
- try {
- postSearchBean = new PostSearchBean();
- model.put("profileList", mapper.writeValueAsString(postSearchBean.getSearchResult()));
- model.put("postSearchBean", mapper.writeValueAsString(postSearchBean));
- model.put("existingUsers", mapper.writeValueAsString(getExistingUsers()));
- model.put("sortByList", mapper.writeValueAsString(getSortByList()));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "getPostSearchProfile: failed to write JSON" + ex.getMessage());
- }
-
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- private HashMap getExistingUsers() throws Exception {
- HashMap existingUsers = new HashMap();
-
- // get the list of user ids in the system
- List<Profile> list = profileService.findAll();
-
- if (list != null) {
- Iterator<Profile> i = list.iterator();
- while (i.hasNext()) {
- Profile user = i.next();
- String orgUserId = user.getOrgUserId(); // userid scalar
- Long id = user.getId(); // id scalar
- if (orgUserId != null)
- existingUsers.put(orgUserId, id);
- }
- }
- return existingUsers;
- }
-
- @RequestMapping(value = { "/post_search/search" }, method = RequestMethod.POST)
- public ModelAndView search(HttpServletRequest request, HttpServletResponse response) throws Exception {
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- PostSearchBean postSearchBean = mapper.readValue(root.get("postSearchBean").toString(),
- PostSearchBean.class);
-
- postSearchBean.setSearchResult(loadSearchResultData(request, postSearchBean));
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(postSearchBean);
- JSONObject j = new JSONObject("{postSearchBean: " + responseString + "}");
-
- out.write(j.toString());
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "search: failed to send search result" + ex.getMessage());
- }
-
- return null;
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public static List getSortByList() {
- if (sortByList == null) {
- sortByList = new ArrayList();
- sortByList.add(new Lookup("Last Name", "last_name"));
- sortByList.add(new Lookup("First Name", "first_name"));
- sortByList.add(new Lookup("HRID", "hrid"));
- sortByList.add(new Lookup("SBCID", "sbcid"));
- sortByList.add(new Lookup("Organization", "org_code"));
- sortByList.add(new Lookup("Email", "email"));
- } // if
-
- return sortByList;
- } // getSortByList
-
- private SearchResult loadSearchResultData(HttpServletRequest request, PostSearchBean searchCriteria)
- throws Exception {
- return ldapService.searchPost(searchCriteria.getUser(), searchCriteria.getSortBy1(),
- searchCriteria.getSortBy2(), searchCriteria.getSortBy3(), searchCriteria.getPageNo(),
- searchCriteria.getNewDataSize(), UserUtils.getUserSession(request).getId().intValue());
- }
-
- @RequestMapping(value = { "/post_search/process" }, method = RequestMethod.POST)
- public ModelAndView process(HttpServletRequest request, HttpServletResponse response) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
- JsonNode root = mapper.readTree(request.getReader());
- PostSearchBean postSearch = mapper.readValue(root.get("postSearchBean").toString(), PostSearchBean.class);
- String errorMsg = "{}";
- try{
- postSearchService.process(request, postSearch);
- postSearch.setSearchResult(loadSearchResultData(request, postSearch));
- }catch(Exception e){
- errorMsg=e.getMessage();
- logger.error(EELFLoggerDelegate.errorLogger,"Exception occurred while performing PostSearchController.process. Details:", e);
- }
- logger.info(EELFLoggerDelegate.auditLogger, "Import new user from webphone ");
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- String postSearchString = mapper.writeValueAsString(postSearch);
- JSONObject j = new JSONObject("{postSearchBean: " + postSearchString + ",existingUsers: "
- + mapper.writeValueAsString(getExistingUsers()) + ",errorMsg:"+errorMsg+"}");
-
- out.write(j.toString());
-
- return null;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.UnsupportedEncodingException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.RoleService;
-import org.openecomp.portalsdk.core.service.UserProfileService;
-import org.openecomp.portalsdk.core.service.UserService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Controller
-@RequestMapping("/")
-public class ProfileController extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProfileController.class);
-
- @Autowired
- UserProfileService service;
-
- @Autowired
- UserService userService;
-
- @Autowired
- RoleService roleService;
-
- private String viewName;
-
- @RequestMapping(value = { "/profile" }, method = RequestMethod.GET)
- public ModelAndView profile(HttpServletRequest request, HttpServletResponse response) throws Exception{
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
-
- User profile = null;
- Long profileId = null;
-
- if (request.getRequestURI().indexOf("self_profile.htm") > -1) {
- profile = UserUtils.getUserSession(request);
- profileId = profile.getId();
- } else {
- profileId = Long.parseLong(request.getParameter("profile_id"));
- profile = (User) userService.getUser(String.valueOf(profileId));
- }
-
- try {
- model.put("stateList", mapper.writeValueAsString(getStates()));
- model.put("countries", mapper.writeValueAsString(getCountries()));
- model.put("timeZones", mapper.writeValueAsString(getTimeZones()));
- model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles(user.getOrgUserId())));
- model.put("profile", mapper.writeValueAsString(profile));
- model.put("profileId", mapper.writeValueAsString(profileId));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "profile: failed to write JSON", e);
- }
- return new ModelAndView("profile", "model", model);
- }
-
- @RequestMapping(value = { "/self_profile" }, method = RequestMethod.GET)
- public ModelAndView self_profile(HttpServletRequest request) throws Exception{
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
-
- User profile = null;
- Long profileId = null;
- User user = UserUtils.getUserSession(request);
-
- profile = UserUtils.getUserSession(request);
- try {
- model.put("stateList", mapper.writeValueAsString(getStates()));
- model.put("countries", mapper.writeValueAsString(getCountries()));
- model.put("timeZones", mapper.writeValueAsString(getTimeZones()));
- model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles(user.getOrgUserId())));
- model.put("profile", mapper.writeValueAsString(profile));
- model.put("profileId", mapper.writeValueAsString(profileId));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "self_profile: failed to write JSON" + e.getMessage());
- }
- return new ModelAndView("profile", "model", model);
- }
-
- @RequestMapping(value = { "/get_self_profile" }, method = RequestMethod.GET)
- public void getSelfProfile(HttpServletRequest request, HttpServletResponse response) throws Exception{
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
-
- User profile = null;
- Long profileId = null;
-
- profile = (User) UserUtils.getUserSession(request);
- try {
- model.put("stateList", mapper.writeValueAsString(getStates()));
- model.put("countries", mapper.writeValueAsString(getCountries()));
- model.put("timeZones", mapper.writeValueAsString(getTimeZones()));
- model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles(user.getOrgUserId())));
- model.put("profile", mapper.writeValueAsString(profile));
- model.put("profileId", mapper.writeValueAsString(profileId));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getSelfProfile: failed to write JSON" + e.getMessage());
- }
-
- }
-
- @RequestMapping(value = { "/get_profile" }, method = RequestMethod.GET)
- public void GetUser(HttpServletRequest request, HttpServletResponse response) {
- Map<String, Object> model = new HashMap<String, Object>();
- User user = UserUtils.getUserSession(request);
- ObjectMapper mapper = new ObjectMapper();
- try {
- User profile = null;
- Long profileId = null;
- if (request.getRequestURI().indexOf("self_profile.htm") > -1) {
- profile = UserUtils.getUserSession(request);
- profileId = profile.getId();
- } else {
- profileId = Long.parseLong(request.getParameter("profile_id"));
- profile = (User) userService.getUser(String.valueOf(profileId));
-
- }
- model.put("stateList", mapper.writeValueAsString(getStates()));
- model.put("countries", mapper.writeValueAsString(getCountries()));
- model.put("timeZones", mapper.writeValueAsString(getTimeZones()));
- model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles(user.getOrgUserId())));
- model.put("profile", mapper.writeValueAsString(profile));
- model.put("profileId", mapper.writeValueAsString(profileId));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "GetUser: failed to write JSON" + e.getMessage());
- }
- }
-
- @RequestMapping(value = { "/profile/saveProfile" }, method = RequestMethod.POST)
- public ModelAndView saveProfile(HttpServletRequest request, HttpServletResponse response) {
- logger.info(EELFLoggerDelegate.debugLogger, "ProfileController.save");
- try {
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- User user = mapper.readValue(root.get("profile").toString(), User.class);
-
- String selectedCountry = mapper.readValue(root.get("selectedCountry").toString(), String.class);
- String selectedState = mapper.readValue(root.get("selectedState").toString(), String.class);
- String selectedTimeZone = mapper.readValue(root.get("selectedTimeZone").toString(), String.class);
-
- Long profileId = Long.parseLong(request.getParameter("profile_id"));
-
- User domainUser = (User) userService.getUser(String.valueOf(profileId));
- // user.setRoles(domainUser.getRoles());
- user.setPseudoRoles(domainUser.getPseudoRoles());
- user.setUserApps(domainUser.getUserApps());
- if (!selectedCountry.equals("")) {
- user.setCountry(selectedCountry);
- }
- if (!selectedState.equals("")) {
- user.setState(selectedState);
- }
- if (!selectedTimeZone.equals("")) {
- user.setTimeZoneId(Long.parseLong(selectedTimeZone));
- }
- service.saveUser(user);
- logger.info(EELFLoggerDelegate.auditLogger, "Save user's profile for user " + profileId);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- out.write("" + profileId);
- return null;
- } catch (Exception e) {
- response.setCharacterEncoding("UTF-8");
- try {
- request.setCharacterEncoding("UTF-8");
- } catch (UnsupportedEncodingException e1) {
-
- e1.printStackTrace();
-
- }
- PrintWriter out = null;
- try {
- out = response.getWriter();
- } catch (IOException e1) {
- logger.error(EELFLoggerDelegate.errorLogger, "saveProfile: failed to get writer" + e1.getMessage());
- }
- out.write(e.getMessage());
- return null;
- }
- }
-
- @RequestMapping(value = { "/profile/removeRole" }, method = RequestMethod.POST)
- public ModelAndView removeRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
- logger.info(EELFLoggerDelegate.debugLogger, "ProfileController.save");
- try {
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- Role role = mapper.readValue(root.get("role").toString(), Role.class);
-
- String profileId = request.getParameter("profile_id");
-
- User domainUser = (User) userService.getUser(profileId);
-
- domainUser.removeRole(role.getId());
-
- service.saveUser(domainUser);
- /*If adding new roles on the current logged in user, we need to update the user value in session*/
- if(UserUtils.getUserId(request)==Integer.valueOf(profileId)){
- HttpSession session = request.getSession(true);
- session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), domainUser);
- }
- logger.info(EELFLoggerDelegate.auditLogger, "Remove role " + role.getId() + " from user " + profileId);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
-
- Map<String, Object> model = new HashMap<String, Object>();
- model.put("profile", mapper.writeValueAsString(domainUser));
- JSONObject j = new JSONObject(mapper.writeValueAsString(domainUser));
-
- out.write(j.toString());
-
- return null;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "removeRole" + e.getMessage());
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- return null;
- }
-
- }
-
- @RequestMapping(value = { "/profile/addNewRole" }, method = RequestMethod.POST)
- public ModelAndView addNewRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
- logger.info(EELFLoggerDelegate.debugLogger, "ProfileController.save" );
- try {
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- Role role = mapper.readValue(root.get("role").toString(), Role.class);
- String profileId = request.getParameter("profile_id");
- User domainUser = (User) userService.getUser(profileId);
- domainUser.addRole(role);
- service.saveUser(domainUser);
- /*If removing roles on the current logged in user, we need to update the user value in session*/
- if(UserUtils.getUserId(request)==Integer.valueOf(profileId)){
- HttpSession session = request.getSession(true);
- session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), domainUser);
- }
- logger.info(EELFLoggerDelegate.auditLogger, "Add new role " + role.getName() + " to user " + profileId);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- Map<String, Object> model = new HashMap<String, Object>();
- model.put("profile", mapper.writeValueAsString(domainUser));
- JSONObject j = new JSONObject(mapper.writeValueAsString(domainUser));
-
- out.write(j.toString());
-
- return null;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "addNewRole" + e.getMessage());
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- return null;
- }
-
- }
-
- public String getViewName() {
- return viewName;
- }
-
- public void setViewName(String viewName) {
- this.viewName = viewName;
- }
-
- @SuppressWarnings("rawtypes")
- public List getStates() {
- return AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD");
- }
-
- @SuppressWarnings("rawtypes")
- public List getCountries() {
- return AppUtils.getLookupList("FN_LU_COUNTRY", "COUNTRY_CD", "COUNTRY", null, "COUNTRY");
- }
-
- @SuppressWarnings("rawtypes")
- public List getTimeZones() {
- return AppUtils.getLookupList("FN_LU_TIMEZONE", "TIMEZONE_ID", "TIMEZONE_NAME", null, "TIMEZONE_NAME");
- }
-
- @SuppressWarnings("rawtypes")
- public List getAvailableRoles(String requestedLoginId) throws Exception {
- return roleService.getAvailableRoles(requestedLoginId);
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.MenuData;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.FnMenuService;
-import org.openecomp.portalsdk.core.service.UserProfileService;
-import org.openecomp.portalsdk.core.service.UserService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Controller
-@RequestMapping("/")
-public class ProfileSearchController extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProfileSearchController.class);
-
- @Autowired
- private UserProfileService service;
-
- @Autowired
- UserService userService;
-
- @Autowired
- private FnMenuService fnMenuService;
-
- @RequestMapping(value = { "/profile_search" }, method = RequestMethod.GET)
- public ModelAndView profileSearch(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- List<User> profileList = null;
- logger.info(EELFLoggerDelegate.applicationLogger, "Initiating ProfileSearch in ProfileSearchController");
- try {
- profileList = service.findAll();
- model.putAll(setDashboardData(request));
- model.put("profileList", mapper.writeValueAsString(profileList));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.applicationLogger, "profileSearch failed", e);
- }
- return new ModelAndView(getViewName(), "model", model);
- }
-
- @RequestMapping(value = { "/get_user" }, method = RequestMethod.GET)
- public void getUser(HttpServletRequest request, HttpServletResponse response) {
- logger.info(EELFLoggerDelegate.applicationLogger, "Initiating get_user in ProfileSearchController");
- ObjectMapper mapper = new ObjectMapper();
- List<User> profileList = null;
- try {
- profileList = service.findAll();
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(profileList));
- JSONObject j = new JSONObject(msg);
- response.setContentType("application/json");
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.applicationLogger, "getUser failed", e);
- }
- }
-
- @RequestMapping(value = { "/get_user_pagination" }, method = RequestMethod.GET)
- public void getUserPagination(HttpServletRequest request, HttpServletResponse response) {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- logger.info(EELFLoggerDelegate.applicationLogger, "Initiating get_user_pagination in ProfileSearchController");
- int pageNum = Integer.parseInt(request.getParameter("pageNum"));
- int viewPerPage = Integer.parseInt(request.getParameter("viewPerPage"));
- List<User> profileList = null;
- try {
- profileList = service.findAll();
- model.put("totalPage", (int) Math.ceil((double) profileList.size() / viewPerPage));
- profileList = profileList.subList(
- viewPerPage * (pageNum - 1) < profileList.size() ? viewPerPage * (pageNum - 1) : profileList.size(),
- viewPerPage * pageNum < profileList.size() ? viewPerPage * pageNum : profileList.size());
- model.put("profileList", mapper.writeValueAsString(profileList));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.setContentType("application/json");
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.applicationLogger, "getUserPagination failed", e);
- }
- }
-
- @SuppressWarnings("unchecked")
- private Map<String, Object> setDashboardData(HttpServletRequest request) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- Map<String, Object> model = new HashMap<String, Object>();
- List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>();
- List<MenuData> parentList = new ArrayList<MenuData>();
- logger.info(EELFLoggerDelegate.applicationLogger, "Initiating setDashboardData in ProfileSearchController");
- HttpSession session = request.getSession();
- try {
- Set<MenuData> menuResult = (Set<MenuData>) session
- .getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
- fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.applicationLogger, "setDashboardData failed", e);
- }
- model.put("childItemList", mapper.writeValueAsString(childItemList));
- model.put("parentList", mapper.writeValueAsString(parentList));
- return model;
- }
-
- @RequestMapping(value = { "/profile/toggleProfileActive" }, method = RequestMethod.GET)
- public void toggleProfileActive(HttpServletRequest request, HttpServletResponse response) throws IOException {
- try {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Initiating toggleProfileActive in ProfileSearchController");
- String userId = request.getParameter("profile_id");
- User user = (User) userService.getUser(userId);
- user.setActive(!user.getActive());
- service.saveUser(user);
- logger.info(EELFLoggerDelegate.auditLogger,
- "Change active status for user " + user.getId() + " to " + user.getActive());
- ObjectMapper mapper = new ObjectMapper();
- response.setContentType("application/json");
- PrintWriter out = response.getWriter();
- out.write(mapper.writeValueAsString(user.getActive()));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.applicationLogger, "toggleProfileActive failed", e);
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.aspect.EELFLoggerAdvice;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.RoleService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.ServletRequestUtils;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.type.TypeFactory;
-
-@Controller
-@RequestMapping("/")
-public class RoleController extends RestrictedBaseController {
-
- @Autowired
- RoleService roleService;
-
- private String viewName;
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleController.class);
-
-
- @RequestMapping(value = { "/role" }, method = RequestMethod.GET)
- public ModelAndView role(HttpServletRequest request) throws Exception {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
-
-
- Role role = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
- logger.info("role_id" + role.getId());
- try {
- model.put("availableRoleFunctions", mapper.writeValueAsString(roleService.getRoleFunctions(user.getOrgUserId())));
- model.put("availableRoles", mapper.writeValueAsString(roleService.getAvailableChildRoles(user.getOrgUserId(),role.getId())));
- model.put("role", mapper.writeValueAsString(role));
- } catch (Exception e) {
- logger.error("role: failed", e);
- logger.error(EELFLoggerDelegate.errorLogger, "role failed", e);
- }
- return new ModelAndView(getViewName(), model);
- }
-
- @RequestMapping(value = { "/get_role" }, method = RequestMethod.GET)
- public void getRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
-
- Role role = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
- logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + role.getId());
- try {
- model.put("availableRoleFunctions", mapper.writeValueAsString(roleService.getRoleFunctions(user.getOrgUserId())));
- model.put("availableRoles", mapper.writeValueAsString(roleService.getAvailableChildRoles(user.getOrgUserId(),role.getId())));
- model.put("role", mapper.writeValueAsString(role));
-
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
- }
-
- }
-
- /**
- * Creates a new role or updates an existing role.
- *
- * @param request
- * @param response
- * @return Always returns null.
- * @throws IOException
- * If the write to the result project fails
- */
- @RequestMapping(value = { "/role/saveRole" }, method = RequestMethod.POST)
- public ModelAndView saveRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
- JSONObject j = null;
- User user = UserUtils.getUserSession(request);
- logger.debug(EELFLoggerDelegate.debugLogger, "RoleController.save");
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- Role role = mapper.readValue(root.get("role").toString(), Role.class);
-
- List<Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
- TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
-
- List<RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
- TypeFactory.defaultInstance().constructCollectionType(List.class, RoleFunction.class));
-
- Role domainRole = null;
- if (role.getId() != null) {
- doAuditLog("saveRole: updating existing role {}", role.getId());
- domainRole = roleService.getRole(user.getOrgUserId(),role.getId());
-
- domainRole.setName(role.getName());
- domainRole.setPriority(role.getPriority());
- } else {
- doAuditLog("saveRole: creating new role", role.getName());
- // check for existing role of same name
- List<Role> roles = roleService.getAvailableRoles(user.getOrgUserId());
- for (Role existRole : roles)
- if (existRole.getName().equalsIgnoreCase(role.getName()))
- throw new Exception("role already exists: " + existRole.getName());
-
- domainRole = new Role();
- domainRole.setName(role.getName());
- domainRole.setPriority(role.getPriority());
- if(role.getChildRoles() != null && role.getChildRoles().size() > 0 ){
-// if (role.getChildRoles().size() > 0 ) {
- for (Object childRole : childRoles) {
- domainRole.addChildRole((Role) childRole);
- }
-// }
- }
- if(role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0){
-// if (role.getRoleFunctions().size() > 0) {
- for (Object roleFunction : roleFunctions) {
- domainRole.addRoleFunction((RoleFunction) roleFunction);
- }
-// }
- }
- }
-
- roleService.saveRole(user.getOrgUserId(),domainRole);
-
- String responseString = mapper.writeValueAsString(domainRole);
- j = new JSONObject("{role: " + responseString + "}");
- } catch (Exception e) {
- // Produce JSON error message
- logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
- j = new JSONObject("{error: '" + e.getMessage() + "'}");
- }
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application/json");
- PrintWriter out = response.getWriter();
- out.write(j.toString());
- return null;
- }
-
- @RequestMapping(value = { "/role/removeRoleFunction" }, method = RequestMethod.POST)
- public ModelAndView removeRoleFunction(HttpServletRequest request, HttpServletResponse response) throws Exception {
- User user = UserUtils.getUserSession(request);
- logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction");
- try {
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class);
-
- Role domainRole = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
- doAuditLog("Remove role function {} from role {}", roleFunction.getCode(),
- ServletRequestUtils.getIntParameter(request, "role_id", 0));
-
- domainRole.removeRoleFunction(roleFunction.getCode());
-
- roleService.saveRole(user.getOrgUserId(),domainRole);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application/json");
- String responseString = mapper.writeValueAsString(domainRole);
- JSONObject j = new JSONObject("{role: " + responseString + "}");
- PrintWriter out = response.getWriter();
- out.write(j.toString());
- return null;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
- response.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- return null;
- }
-
- }
-
- @RequestMapping(value = { "/role/addRoleFunction" }, method = RequestMethod.POST)
- public ModelAndView addRoleFunction(HttpServletRequest request, HttpServletResponse response) throws Exception {
- User user = UserUtils.getUserSession(request);
- logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction");
- try {
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class);
-
- Role domainRole = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
-
- domainRole.addRoleFunction(roleFunction);
-
- roleService.saveRole(user.getOrgUserId(),domainRole);
- doAuditLog("Add role function {} to role {}", roleFunction.getCode(),
- ServletRequestUtils.getIntParameter(request, "role_id", 0));
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application/json");
- String responseString = mapper.writeValueAsString(domainRole);
- JSONObject j = new JSONObject("{role: " + responseString + "}");
- PrintWriter out = response.getWriter();
- out.write(j.toString());
- return null;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
- response.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- return null;
- }
-
- }
-
- @RequestMapping(value = { "/role/removeChildRole" }, method = RequestMethod.POST)
- public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
- User user = UserUtils.getUserSession(request);
- logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeChileRole");
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class);
-
- Role domainRole = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
-
- domainRole.removeChildRole(childRole.getId());
- doAuditLog("remove child role {} from role {}", childRole.getId(),
- ServletRequestUtils.getIntParameter(request, "role_id", 0));
-
- roleService.saveRole(user.getOrgUserId(),domainRole);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application/json");
- String responseString = mapper.writeValueAsString(domainRole);
- JSONObject j = new JSONObject("{role: " + responseString + "}");
- PrintWriter out = response.getWriter();
- out.write(j.toString());
- return null;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "removeChildRole failed", e);
- response.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- return null;
- }
-
- }
-
- @RequestMapping(value = { "/role/addChildRole" }, method = RequestMethod.POST)
- public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
- User user = UserUtils.getUserSession(request);
- logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.addChileRole");
- try {
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class);
- long role_id = new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0));
-
- Role domainRole = roleService.getRole(user.getOrgUserId(),role_id );
-
- domainRole.addChildRole(childRole);
-
- roleService.saveRole(user.getOrgUserId(),domainRole);
- doAuditLog("Add child role {} to role {}", childRole.getId(),
- ServletRequestUtils.getIntParameter(request, "role_id", 0));
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application/json");
- String responseString = mapper.writeValueAsString(domainRole);
- JSONObject j = new JSONObject("{role: " + responseString + "}");
- PrintWriter out = response.getWriter();
- out.write(j.toString());
- return null;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "addChildRole failed", e);
- response.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- return null;
- }
-
- }
-
- /**
- * Sets context with begin and end timestamps at current date & time, writes
- * the specified message and parameters to the audit log, then removes the
- * timestamps from context.
- *
- * @param message
- * @param parameters
- */
- private void doAuditLog(String message, Object... parameters) {
- final String currentDateTime = EELFLoggerAdvice.getCurrentDateTimeUTC();
- // Set the MDC with audit properties
- MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, currentDateTime);
- MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, currentDateTime);
- logger.info(EELFLoggerDelegate.auditLogger, message, parameters);
- MDC.remove(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(SystemProperties.AUDITLOG_END_TIMESTAMP);
- }
-
- public String getViewName() {
- return viewName;
- }
-
- public void setViewName(String viewName) {
- this.viewName = viewName;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.RoleService;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Controller
-@RequestMapping("/")
-public class RoleFunctionListController extends RestrictedBaseController {
-
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleFunctionListController.class);
-
- @Autowired
- RoleService service;
-
- private String viewName;
-
- @RequestMapping(value = {"/role_function_list" }, method = RequestMethod.GET)
- public ModelAndView welcome(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
-
-
- try {
- model.put("availableRoleFunctions", mapper.writeValueAsString(service.getRoleFunctions(user.getOrgUserId())));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "welcome failed", e);
- }
-
- return new ModelAndView(getViewName(),model);
- }
-
- @RequestMapping(value = {"/get_role_functions" }, method = RequestMethod.GET)
- public void getRoleFunctionList(HttpServletRequest request,HttpServletResponse response) {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
- try {
- model.put("availableRoleFunctions", mapper.writeValueAsString(service.getRoleFunctions(user.getOrgUserId())));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getROleFunctionList failed", e);
- }
-
- }
-
- @RequestMapping(value = {"/role_function_list/saveRoleFunction" }, method = RequestMethod.POST)
- public void saveRoleFunction(HttpServletRequest request,
- HttpServletResponse response, @RequestBody String roleFunc) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
-
- String restCallStatus = "";
- try {
- String data = roleFunc;
- RoleFunction availableRoleFunction = mapper.readValue(data, RoleFunction.class);
- String code = availableRoleFunction.getCode();
- RoleFunction domainRoleFunction = service.getRoleFunction(user.getOrgUserId(),code);
- domainRoleFunction.setName(availableRoleFunction.getName());
- domainRoleFunction.setCode(code);
- restCallStatus="success";
- service.saveRoleFunction(user.getOrgUserId(),domainRoleFunction);
- } catch (Exception e) {
- restCallStatus="fail";
- logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed", e);
- throw new Exception("failed while Saving RoleFunction");
- }
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(restCallStatus));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- }
-
- @RequestMapping(value = {"/role_function_list/addRoleFunction" }, method = RequestMethod.POST)
- public void addRoleFunction(HttpServletRequest request,
- HttpServletResponse response, @RequestBody String roleFunc) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
-
- String restCallStatus = "";
- boolean canSave=true;
- try {
- String data = roleFunc;
- RoleFunction availableRoleFunction = mapper.readValue(data, RoleFunction.class);
- String code = availableRoleFunction.getCode();
- List<RoleFunction> currentRoleFunction = service.getRoleFunctions(user.getOrgUserId());
- restCallStatus="success";
- for(RoleFunction roleF:currentRoleFunction){
- if(roleF.getCode().equals(code)){
- restCallStatus="code exists";
- canSave=false;
- break;
- }
- }
- if(canSave)
- service.saveRoleFunction(user.getOrgUserId(),availableRoleFunction);
- } catch (Exception e) {
- restCallStatus="fail";
- logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunction failed", e);
- throw new Exception(e.getMessage());
- }
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(restCallStatus));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- }
-
- @RequestMapping(value = {"/role_function_list/removeRoleFunction" }, method = RequestMethod.POST)
- public void removeRoleFunction(HttpServletRequest request,
- HttpServletResponse response, @RequestBody String roleFunc) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
-
- String restCallStatus = "";
- try {
- String data = roleFunc;
-
- RoleFunction availableRoleFunction = mapper.readValue(data, RoleFunction.class);
-
- RoleFunction domainRoleFunction = service.getRoleFunction(user.getOrgUserId(),availableRoleFunction.getCode());
-
- service.deleteRoleFunction(user.getOrgUserId(),domainRoleFunction);
- logger.info(EELFLoggerDelegate.auditLogger, "Remove role function " + domainRoleFunction.getName());
- restCallStatus="success";
- } catch (Exception e) {
- restCallStatus="fail";
- logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
- throw new Exception(e.getMessage());
- }
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(restCallStatus));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- }
-
- public String getViewName() {
- return viewName;
- }
- public void setViewName(String viewName) {
- this.viewName = viewName;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.io.PrintWriter;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.RoleService;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Controller
-@RequestMapping("/")
-public class RoleListController extends RestrictedBaseController {
-
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleListController.class);
- @Autowired
- RoleService service;
-
- private String viewName;
-
- @RequestMapping(value = {"/role_list" }, method = RequestMethod.GET)
- public ModelAndView getRoleList(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
-
-
- try {
- model.put("availableRoles", mapper.writeValueAsString(service.getAvailableRoles(user.getOrgUserId())));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getRoleList failed", e);
- }
-
- return new ModelAndView(getViewName(),model);
- }
-
- @RequestMapping(value = {"/get_roles" }, method = RequestMethod.GET)
- public void getRoles(HttpServletRequest request, HttpServletResponse response) {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
-
-
- try {
- model.put("availableRoles", mapper.writeValueAsString(service.getAvailableRoles(user.getOrgUserId())));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
- }
- }
-
-
- @RequestMapping(value = {"/role_list/toggleRole" }, method = RequestMethod.POST)
- public ModelAndView toggleRole(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- User user = UserUtils.getUserSession(request);
-
-
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- Role role = mapper.readValue(root.get("role").toString(), Role.class);
-
- Role domainRole = service.getRole(user.getOrgUserId(),role.getId());
- //role. toggle active ind
- boolean active = domainRole.getActive();
- domainRole.setActive(!active);
-
- service.saveRole(user.getOrgUserId(),domainRole);
- logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId());
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(service.getAvailableRoles(user.getOrgUserId()));
- JSONObject j = new JSONObject("{availableRoles: "+responseString+"}");
-
- out.write(j.toString());
-
- return null;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- return null;
- }
-
- }
-
- @RequestMapping(value = {"/role_list/removeRole" }, method = RequestMethod.POST)
- public ModelAndView removeRole(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- User user = UserUtils.getUserSession(request);
-
- try {
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- Role role = mapper.readValue(root.get("role").toString(), Role.class);
-
- Role domainRole = service.getRole(user.getOrgUserId(),role.getId());
-
- service.deleteDependcyRoleRecord(user.getOrgUserId(),role.getId());
- service.deleteRole(user.getOrgUserId(),domainRole);
- logger.info(EELFLoggerDelegate.auditLogger, "Remove role " + domainRole.getId());
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
-
- String responseString = mapper.writeValueAsString(service.getAvailableRoles(user.getOrgUserId()));
- JSONObject j = new JSONObject("{availableRoles: "+responseString+"}");
- out.write(j.toString());
-
- return null;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- return null;
- }
-
- }
-
- public String getViewName() {
- return viewName;
- }
- public void setViewName(String viewName) {
- this.viewName = viewName;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalsdk.core.auth.LoginStrategy;
-import org.openecomp.portalsdk.core.controller.UnRestrictedBaseController;
-import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
-import org.openecomp.portalsdk.core.service.LoginService;
-import org.openecomp.portalsdk.core.service.ProfileService;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-@Controller
-@RequestMapping("/")
-public class SDKLoginController extends UnRestrictedBaseController {
- @Autowired
- ProfileService service;
- @Autowired
- private LoginService loginService;
- @Autowired
- private LoginStrategy loginStrategy;
-
- private String viewName;
-
- @RequestMapping(value = { "/login.htm" }, method = RequestMethod.GET)
- public ModelAndView login(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- return new ModelAndView("login", "model", model);
- }
-
- @RequestMapping(value = { "/login_external.htm" }, method = RequestMethod.GET)
- public ModelAndView externalLogin(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- return new ModelAndView("login_external", "model", model);
- }
-
- @RequestMapping(value = { "/login_external" }, method = RequestMethod.POST)
- public ModelAndView doexternalLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
- return loginStrategy.doExternalLogin(request, response);
- }
-
- @RequestMapping(value = { "/doLogin" }, method = RequestMethod.GET)
- public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
- return loginStrategy.doLogin(request, response);
- }
-
- public String getJessionId(HttpServletRequest request) {
- return request.getSession().getId();
- }
-
- protected void initateSessionMgtHandler(HttpServletRequest request) {
- String jSessionId = getJessionId(request);
- PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
- }
-
- public String getViewName() {
- return viewName;
- }
-
- public void setViewName(String viewName) {
- this.viewName = viewName;
- }
-
- public LoginService getLoginService() {
- return loginService;
- }
-
- public void setLoginService(LoginService loginService) {
- this.loginService = loginService;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.net.URLDecoder;
-import java.net.URLEncoder;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
-import org.openecomp.portalsdk.core.auth.LoginStrategy;
-import org.openecomp.portalsdk.core.command.LoginBean;
-import org.openecomp.portalsdk.core.controller.UnRestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.menu.MenuProperties;
-import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-import org.openecomp.portalsdk.core.service.LoginService;
-import org.openecomp.portalsdk.core.service.RoleService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-import org.springframework.web.util.WebUtils;
-
-@Controller
-@RequestMapping("/")
-public class SingleSignOnController extends UnRestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SingleSignOnController.class);
-
- @Autowired
- private LoginService loginService;
-
- @Autowired
- private LoginStrategy loginStrategy;
-
- private String viewName;
- private String welcomeView;
-
- public String getWelcomeView() {
- return welcomeView;
- }
-
- public void setWelcomeView(String welcomeView) {
- this.welcomeView = welcomeView;
- }
-
- @Autowired
- RoleService roleService;
-
- /**
- * Handles requests directed to the single sign-on page by the session
- * timeout interceptor.
- *
- * @param request
- * @return Redirect to an appropriate address
- * @throws Exception
- */
- @RequestMapping(value = { "/single_signon.htm" }, method = RequestMethod.GET)
- public ModelAndView singleSignOnLogin(HttpServletRequest request) throws Exception {
-
- Map<String, String> model = new HashMap<String, String>();
- HashMap<String, String> additionalParamsMap = new HashMap<String, String>();
- LoginBean commandBean = new LoginBean();
-
- // SessionTimeoutInterceptor sets these parameters
- String forwardURL = URLDecoder.decode(request.getParameter("forwardURL"), "UTF-8");
- String redirectToPortal = request.getParameter("redirectToPortal");
-
- if (isLoginCookieExist(request) && redirectToPortal == null) {
- HttpSession session = null;
- session = AppUtils.getSession(request);
- User user = UserUtils.getUserSession(request);
- if (session == null || user == null) {
-
- final String authMech = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM);
- String userId = loginStrategy.getUserId(request);
- commandBean.setUserid(userId);
- commandBean = getLoginService().findUser(commandBean,
- (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY),
- additionalParamsMap);
- List<RoleFunction> roleFunctionList= roleService.getRoleFunctions(userId);
- if (commandBean.getUser() == null) {
- String loginErrorMessage = (commandBean.getLoginErrorMessage() != null)
- ? commandBean.getLoginErrorMessage()
- : SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_NOT_FOUND;
- model.put(LoginStrategy.ERROR_MESSAGE_KEY, SystemProperties.getProperty(loginErrorMessage));
- final String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL)
- + "?noUserError=Yes";
- logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: user is null, redirect URL is {}",
- redirectUrl);
- return new ModelAndView("redirect:" + redirectUrl);
- } else {
- // store the user's information in the session
- String loginMethod;
- if (null == authMech || "".equals(authMech) || "BOTH".equals(authMech)) {
- loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_CSP);
- } else if ("CSP".equals(authMech)) {
- loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_CSP);
- } else {
- loginMethod = SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_WEB_JUNCTION);
- }
- UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
- commandBean.getBusinessDirectMenu(), loginMethod, roleFunctionList);
- initateSessionMgtHandler(request);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "singleSignOnLogin: create new user session for expired user {}; user {} exists in the system",
- userId, commandBean.getUser().getOrgUserId());
- return new ModelAndView("redirect:" + forwardURL);
- }
- } // user is null or session is null
- else {
- // both user and session are non-null.
- logger.info(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: redirecting to the forwardURL {}",
- forwardURL);
- return new ModelAndView("redirect:" + forwardURL);
- }
-
- } else {
- /*
- * Login cookie not found, or redirect-to-portal parameter was
- * found.
- *
- * Redirect the user to the portal with a suitable return URL. The
- * forwardURL parameter that arrives as a parameter is a partial
- * (not absolute) request path for a page in the application. The
- * challenge here is to compute the correct absolute path for the
- * original request so the portal can redirect the user back to the
- * right place. If the application sits behind WebJunction, or if
- * separate FE-BE hosts are used, then the URL yielded by the
- * request has a host name that is not reachable by the user.
- */
- String returnToAppUrl = null;
- if (SystemProperties.containsProperty(SystemProperties.APP_BASE_URL)) {
- // New feature as of 1610, release 3.3.3:
- // application can publish a base URL in system.properties
- String appUrl = SystemProperties.getProperty(SystemProperties.APP_BASE_URL);
- returnToAppUrl = appUrl + (appUrl.endsWith("/") ? "" : "/") + forwardURL;
- logger.debug(EELFLoggerDelegate.debugLogger,
- "singleSignOnLogin: using app base URL {} and redirectURL {}", appUrl, returnToAppUrl);
- } else {
- // Be backward compatible with applications that don't need this
- // feature.
- // This is the controller for the single_signon.htm page, so the
- // replace
- // should always find the specified token.
- returnToAppUrl = ((HttpServletRequest) request).getRequestURL().toString().replace("single_signon.htm",
- forwardURL);
- logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: computed redirectURL {}",
- returnToAppUrl);
- }
- final String encodedReturnToAppUrl = URLEncoder.encode(returnToAppUrl, "UTF-8");
- // Also send the application's UEB key so Portal can block URL
- // reflection attacks.
- final String uebAppKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
- final String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
- final String portalUrl = url.substring(0, url.lastIndexOf('/')) + "/process_csp";
- final String redirectUrl = portalUrl + "?uebAppKey=" + uebAppKey + "&redirectUrl=" + encodedReturnToAppUrl;
- logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: portal-bound redirect URL is {}",
- redirectUrl);
- return new ModelAndView("redirect:" + redirectUrl);
- }
- }
-
- protected void initateSessionMgtHandler(HttpServletRequest request) {
- String portalJSessionId = getPortalJSessionId(request);
- String jSessionId = getJessionId(request);
- PortalTimeoutHandler.sessionCreated(portalJSessionId, jSessionId, AppUtils.getSession(request));
- }
-
- public boolean isLoginCookieExist(HttpServletRequest request) {
- Cookie ep = WebUtils.getCookie(request, LoginStrategy.EP_SERVICE);
- return (ep != null);
- }
-
- public String getPortalJSessionId(HttpServletRequest request) {
- Cookie ep = WebUtils.getCookie(request, LoginStrategy.EP_SERVICE);
- return ep.getValue();
- }
-
- public String getJessionId(HttpServletRequest request) {
- return request.getSession().getId();
- }
-
- public String getViewName() {
- return viewName;
- }
-
- public void setViewName(String viewName) {
- this.viewName = viewName;
- }
-
- public LoginService getLoginService() {
- return loginService;
- }
-
- public void setLoginService(LoginService loginService) {
- this.loginService = loginService;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import org.json.JSONArray;
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.command.UserRowBean;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.UsageUtils;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-@Controller
-@RequestMapping("/")
-public class UsageListController extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UsageListController.class);
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @RequestMapping(value = { "/usage_list" }, method = RequestMethod.GET)
- public ModelAndView usageList(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
-
- HttpSession httpSession = request.getSession();
- HashMap activeUsers = (HashMap) httpSession.getServletContext().getAttribute("activeUsers");
- if (activeUsers.size() == 0) {
- activeUsers.put(httpSession.getId(), httpSession);
- httpSession.getServletContext().setAttribute("activeUsers", activeUsers);
- }
- ArrayList<UserRowBean> rows = UsageUtils.getActiveUsers(activeUsers);
- JSONArray ja = new JSONArray();
- try {
- for (UserRowBean userRowBean : rows) {
- JSONObject jo = new JSONObject();
- jo.put("id", userRowBean.getId());
- jo.put("lastName", userRowBean.getLastName());
- jo.put("email", userRowBean.getEmail());
- jo.put("lastAccess", userRowBean.getLastAccess());
- jo.put("remaining", userRowBean.getRemaining());
- jo.put("sessionId", userRowBean.getSessionId());
- if (!(httpSession.getId().equals(userRowBean.getSessionId()))) {
- jo.put("delete", "yes");
- } else {
- jo.put("delete", "no");
- }
- ja.put(jo);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "usageList failed", e);
- }
-
- model.put("model", ja);
-
- return new ModelAndView(getViewName(), model);
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @RequestMapping(value = { "/get_usage_list" }, method = RequestMethod.GET)
- public void getUsageList(HttpServletRequest request, HttpServletResponse response) {
-
- HttpSession httpSession = request.getSession();
- HashMap activeUsers = (HashMap) httpSession.getServletContext().getAttribute("activeUsers");
- if (activeUsers.size() == 0) {
- activeUsers.put(httpSession.getId(), httpSession);
- httpSession.getServletContext().setAttribute("activeUsers", activeUsers);
- }
- ArrayList<UserRowBean> rows = UsageUtils.getActiveUsers(activeUsers);
- JSONArray ja = new JSONArray();
- try {
- for (UserRowBean userRowBean : rows) {
- JSONObject jo = new JSONObject();
- jo.put("id", userRowBean.getId());
- jo.put("lastName", userRowBean.getLastName());
- jo.put("email", userRowBean.getEmail());
- jo.put("lastAccess", userRowBean.getLastAccess());
- jo.put("remaining", userRowBean.getRemaining());
- jo.put("sessionId", userRowBean.getSessionId());
- if (!(httpSession.getId().equals(userRowBean.getSessionId()))) {
- jo.put("delete", "yes");
- } else {
- jo.put("delete", "no");
- }
- ja.put(jo);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getUsageList failed", e);
- }
- JsonMessage msg;
- try {
- msg = new JsonMessage(ja.toString());
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getUsageList failed to serialize", e);
- }
-
- }
-
- @SuppressWarnings("rawtypes")
- @RequestMapping(value = { "/usage_list/removeSession" }, method = RequestMethod.GET)
- public void removeSession(HttpServletRequest request, HttpServletResponse response) throws Exception {
- HashMap activeUsers = (HashMap) request.getSession().getServletContext().getAttribute("activeUsers");
- UserRowBean data = new UserRowBean();
- data.setSessionId(request.getParameter("deleteSessionId"));
- UsageUtils.getActiveUsersAfterDelete(activeUsers, data);
-
- HttpSession httpSession = request.getSession();
- ArrayList<UserRowBean> rows = UsageUtils.getActiveUsers(activeUsers);
- JSONArray ja = new JSONArray();
- try {
- for (UserRowBean userRowBean : rows) {
- JSONObject jo = new JSONObject();
- jo.put("id", userRowBean.getId());
- jo.put("lastName", userRowBean.getLastName());
- jo.put("email", userRowBean.getEmail());
- jo.put("lastAccess", userRowBean.getLastAccess());
- jo.put("remaining", userRowBean.getRemaining());
- jo.put("sessionId", userRowBean.getSessionId());
- if (!(httpSession.getId().equals(userRowBean.getSessionId()))) {
- jo.put("delete", "yes");
- } else {
- jo.put("delete", "no");
- }
- ja.put(jo);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "removeSession failed", e);
- }
-
- response.setContentType("application/json");
- PrintWriter out = response.getWriter();
- out.write(ja.toString());
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.Profile;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.ProfileService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-/**
- * Controller for user profile view. The view is restricted to authenticated
- * users. The view name resolves to page user_profile.jsp which uses Angular.
- */
-
-@Controller
-@RequestMapping("/")
-public class UserProfileController extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserProfileController.class);
-
- @Autowired
- ProfileService service;
-
- @RequestMapping(value = { "/user_profile" }, method = RequestMethod.GET)
- public ModelAndView userProfile(HttpServletRequest request) throws Exception {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- List<Profile> profileList = service.findAll();
- try {
- model.put("customerInfo", mapper.writeValueAsString(profileList));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "userProfile failed", e);
- }
-
- return new ModelAndView("user_profile", "model", model);
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.core;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-/**
- * Controller for welcome view. The view is restricted to authenticated users.
- * The view name defaults to the request name with no suffix, "welcome", which
- * resolves to page welcome.jsp.
- */
-@Controller
-@RequestMapping("/")
-public class WelcomeController extends RestrictedBaseController {
- @RequestMapping(value = { "/welcome" }, method = RequestMethod.GET)
- public ModelAndView welcome(HttpServletRequest request) {
- final String defaultViewName = null;
- return new ModelAndView(defaultViewName);
- }
-}
+++ /dev/null
-package org.openecomp.portalapp.controller.core;
-
-/**
- * Provides controllers for EPSDK application core functionality such as logging
- * in, managing roles, editing menus, etc.
- */
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-
-/**
- * Controller for a single-page application sample. The view is restricted to
- * authenticated users. The named view resolves to page singlePageSample.html,
- * which uses Angular.
- */
-@Controller
-@RequestMapping("/")
-public class AngularSinglePageController extends RestrictedBaseController {
-
- @RequestMapping(value = { "/singlePageSample" }, method = RequestMethod.GET)
- public ModelAndView view(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- return new ModelAndView("single_page_sample", "model", model);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import java.io.PrintWriter;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.BroadcastMessage;
-import org.openecomp.portalsdk.core.service.BroadcastService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Controller
-@RequestMapping("/")
-public class BroadcastController extends RestrictedBaseController {
-
- @Autowired
- private BroadcastService broadcastService;
-
- @RequestMapping(value = { "/broadcast" }, method = RequestMethod.GET)
- public ModelAndView broadcast(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
-
- try {
- model.put("broadcastMessage", mapper.writeValueAsString(broadcastService.getBroadcastMessage(request)));
- model.put("broadcastSites", mapper.writeValueAsString(referenceData(request).get("broadcastSites")));
- } catch (Exception e) {
- e.printStackTrace();
- }
- return new ModelAndView(getViewName(), model);
- }
-
- @RequestMapping(value = { "/get_broadcast" }, method = RequestMethod.GET)
- public void getBroadcast(HttpServletRequest request, HttpServletResponse response) {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
-
- try {
-
- model.put("broadcastMessage", mapper.writeValueAsString(broadcastService.getBroadcastMessage(request)));
- model.put("broadcastSites", mapper.writeValueAsString(referenceData(request).get("broadcastSites")));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
-
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- protected Map referenceData(HttpServletRequest request) {
- Map lookupData = new HashMap();
-
- if ("true".equals(SystemProperties.getProperty(SystemProperties.CLUSTERED))) {
- lookupData.put("broadcastSites", AppUtils.getLookupList("fn_lu_broadcast_site", "broadcast_site_cd",
- "broadcast_site_descr", "", "broadcast_site_descr"));
- }
-
- return lookupData;
- }
-
- @RequestMapping(value = { "/broadcast/save" }, method = RequestMethod.POST)
- public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
- try {
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- BroadcastMessage broadcastMessage = mapper.readValue(root.get("broadcastMessage").toString(),
- BroadcastMessage.class);
-
- broadcastService.saveBroadcastMessage(broadcastMessage);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(broadcastMessage);
- JSONObject j = new JSONObject("{broadcastMessage: " + responseString + "}");
-
- out.write(j.toString());
-
- return null;
- } catch (Exception e) {
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- return null;
- }
-
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import java.io.PrintWriter;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.BroadcastMessage;
-import org.openecomp.portalsdk.core.service.BroadcastService;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Controller
-@RequestMapping("/")
-public class BroadcastListController extends RestrictedBaseController {
-
- @Autowired
- private BroadcastService broadcastService;
-
- @RequestMapping(value = { "/broadcast_list" }, method = RequestMethod.GET)
- public ModelAndView broadcastList(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
-
- model.put("model", broadcastService.getBcModel(request));
- return new ModelAndView(getViewName(), model);
- }
-
- @RequestMapping(value = { "/get_broadcast_list" }, method = RequestMethod.GET)
- public void getBroadcast(HttpServletRequest request, HttpServletResponse response) {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- try {
- model.put("model", broadcastService.getBcModel(request));
- model.put("messagesList", broadcastService.getBcModel(request).get("messagesList"));
- model.put("messageLocations", broadcastService.getBcModel(request).get("messageLocations"));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
- @RequestMapping(value = { "/broadcast_list/remove" }, method = RequestMethod.POST)
- public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
- try {
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- BroadcastMessage broadcastMessage = mapper.readValue(root.get("broadcastMessage").toString(),
- BroadcastMessage.class);
-
- broadcastService.removeBroadcastMessage(broadcastMessage);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(broadcastMessage);
- JSONObject j = new JSONObject("{broadcastMessage: " + responseString + "}");
-
- out.write(j.toString());
-
- return null;
- } catch (Exception e) {
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- return null;
- }
-
- }
-
- @RequestMapping(value = { "/broadcast_list/toggleActive" }, method = RequestMethod.POST)
- public ModelAndView toggleActive(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
- try {
-
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- BroadcastMessage broadcastMessage = mapper.readValue(root.get("broadcastMessage").toString(),
- BroadcastMessage.class);
-
- broadcastService.saveBroadcastMessage(broadcastMessage);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(broadcastMessage);
- JSONObject j = new JSONObject("{broadcastMessage: " + responseString + "}");
-
- out.write(j.toString());
-
- return null;
- } catch (Exception e) {
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- return null;
- }
-
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-
-/**
- * Controller for a message sequence chart view. The view is restricted to
- * authenticated users. The view name defaults to the request name with no
- * suffix, "callflow", which resolves to page details.jsp. That page is an
- * iframe around page details.html.
- */
-@Controller
-@RequestMapping("/")
-public class CallflowController extends RestrictedBaseController {
-
- @RequestMapping(value = { "/callflow" }, method = RequestMethod.GET)
- public ModelAndView plot() {
- final String defaultViewName = null;
- return new ModelAndView(defaultViewName);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-
-
-/**
- * @author chris zeng
- *
- */
-
-@Controller
-@RequestMapping("/")
-public class CamundaCockpitController extends RestrictedBaseController {
- @SuppressWarnings("rawtypes")
- @RequestMapping(value = {"/get_camunda_cockpit_link" }, method = RequestMethod.GET, produces = "application/json")
- @ResponseBody
- public Map getCamundaCockpitLink(HttpServletRequest request,HttpServletResponse response) {
- Map<String,String> map = new HashMap<String,String>();
- String camundaCockpitUrl = "";
- String camundaCockpitlinkDefined = "false";
- if (SystemProperties.containsProperty("camunda_cockpit_link")){
- camundaCockpitUrl = SystemProperties.getProperty("camunda_cockpit_link");
- camundaCockpitlinkDefined = "true";
- };
- map.put("link_defined", camundaCockpitlinkDefined);
- map.put("camunda_cockpit_link", camundaCockpitUrl);
- return map;
- };
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.UserProfileService;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Controller
-@RequestMapping("/")
-public class CollaborateListController extends RestrictedBaseController{
- @Autowired
- UserProfileService service;
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CollaborateListController.class);
-
- @RequestMapping(value = {"/collaborate_list" }, method = RequestMethod.GET)
- public ModelAndView ProfileSearch(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
-
- List<User> profileList =null;
- try {
- profileList = service.findAllUserWithOnOffline(user.getOrgUserId());
- model.put("profileList", mapper.writeValueAsString(profileList));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Error happened during collaborate list search" + e.getMessage());
-
- }
- return new ModelAndView(getViewName(),"model", model);
- }
-
- @RequestMapping(value = {"/get_collaborate_list" }, method = RequestMethod.GET)
- public void getCollaborateList(HttpServletRequest request,HttpServletResponse response) {
-
- ObjectMapper mapper = new ObjectMapper();
- User user = UserUtils.getUserSession(request);
-
- List<User> profileList =null;
- try {
- profileList = service.findAllUserWithOnOffline(user.getOrgUserId());
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(profileList));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Error happened during get collaborate list" + e.getMessage());
-
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-@Controller
-@RequestMapping("/")
-public class CollaborationController extends RestrictedBaseController{
-
- @RequestMapping(value = {"/collaboration" }, method = RequestMethod.GET)
- public ModelAndView view(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- User user = UserUtils.getUserSession(request);
-
- model.put("name",(user.getFirstName() + " " + (user.getLastName() != null? user.getLastName().substring(0,1): "" )));
- return new ModelAndView(getViewName(),"model", model);
- }
- @RequestMapping(value = {"/openCollaboration" }, method = RequestMethod.GET)
- public ModelAndView openCollaboration(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- User user = UserUtils.getUserSession(request);
-
- model.put("name",(user.getFirstName() + " " + (user.getLastName() != null? user.getLastName().substring(0,1): "" )));
- return new ModelAndView("openCollaboration","model", model);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.UnRestrictedBaseController;
-import org.openecomp.portalsdk.core.service.ProfileService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-
-/**
- * Controller for user profile view. The view is restricted to authenticated
- * users. The view name resolves to page user_profile.jsp which uses Angular.
- */
-
-@Controller
-@RequestMapping("/")
-public class DS2SampleController extends UnRestrictedBaseController {
-
- @Autowired
- ProfileService service;
-
- @RequestMapping(value = { "/ds2_sample" }, method = RequestMethod.GET)
- public ModelAndView ProfileSearch(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- return new ModelAndView("ds2_sample", "model", model);
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import java.io.IOException;
-
-import org.json.JSONObject;
-import org.openecomp.portalapp.model.Result;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.servlet.ModelAndView;
-
-import io.searchbox.client.JestClient;
-import io.searchbox.client.JestClientFactory;
-import io.searchbox.client.config.HttpClientConfig;
-import io.searchbox.core.Search;
-import io.searchbox.core.SearchResult;
-import io.searchbox.core.Suggest;
-import io.searchbox.core.SuggestResult;
-import io.searchbox.params.Parameters;
-
-/**
- * Controller for views that demonstrate Elastic Search features.
- */
-@RestController
-public class ElasticSearchController extends RestrictedBaseController{
-
- @RequestMapping(value = {"/es_search_demo" }, method = RequestMethod.GET)
- public ModelAndView search() {
- return new ModelAndView("es_search_demo");
- }
-
- @RequestMapping(value = {"/es_suggest_demo" }, method = RequestMethod.GET)
- public ModelAndView suggest() {
- return new ModelAndView("es_suggest_demo");
- }
-
- @RequestMapping(value="/es_suggest/{task}",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public ResponseEntity<Result> doSuggest(@PathVariable("task") String task) throws IOException {
- JSONObject obj = new JSONObject(task);
- String searchTerm = obj.getString("data");
- String searchSize = obj.getString("size");
- String searchFuzzy = obj.getString("fuzzy");
- String resultName = obj.getString("resultname");
-
- JestClientFactory factory = new JestClientFactory();
- factory.setHttpClientConfig(new HttpClientConfig
- .Builder("http://todo_elastic_search_server")
- .multiThreaded(true)
- .build());
- JestClient client = factory.getObject();
-
-
- Suggest suggest = new Suggest.Builder("{\n"
- +"\"" + resultName +"\" : {\n"
- +"\"text\" : \""+ searchTerm +"\",\n"
- +"\"completion\" : {\n"
- +"\"field\" : \"suggest\",\n"
- +"\"size\" : " + searchSize + ",\n"
- +"\"fuzzy\" : \"" + searchFuzzy + "\"\n"
- +"}\n"
- +"}\n"
- +"}").addIndex("customer").build();
-
- SuggestResult result = client.execute(suggest);
- System.err.println(result.getJsonObject().toString());
- return new ResponseEntity<Result>(new Result(result.getJsonObject().toString()),HttpStatus.OK);
- }
-
- @RequestMapping(value="/es_search/{task}",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public ResponseEntity<Result> doSearch(@PathVariable("task") String task) throws IOException {
- JSONObject obj = new JSONObject(task);
- String searchTerm = obj.getString("data");
- String searchSize = obj.getString("size");
- // String searchFuzzy = obj.getString("fuzzy");
-
- JestClientFactory factory = new JestClientFactory();
- factory.setHttpClientConfig(new HttpClientConfig
- .Builder("http://todo_elastic_search_server")
- .multiThreaded(true)
- .build());
- JestClient client = factory.getObject();
-
- Search search = new Search.Builder("{\n"
- +"\"query\" : {\n"
- +"\"query_string\" : {\n"
- +"\"query\" : \"name:"+ searchTerm +"\"\n"
- +"}\n"
- +"}\n"
- +"}").addIndex("customer").setParameter(Parameters.SIZE,Integer.valueOf(searchSize)).build();
-
- SearchResult result = client.execute(search);
- System.err.println(result.getJsonObject().toString());
- return new ResponseEntity<Result>(new Result(result.getJsonObject().toString()),HttpStatus.OK);
- }
-
- public ResponseEntity<Result> sendResult(Result result) {
- return new ResponseEntity<Result>(result, HttpStatus.OK);
- }
-
- @Override
- public boolean isRESTfulCall() {
- return true;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.ElementLinkService;
-import org.openecomp.portalsdk.core.service.ElementMapService;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-
-@RestController
-@RequestMapping("/")
-public class ElementModelController extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ElementModelController.class);
-
- @RequestMapping(value = { "/elementMapLayout" }, method = RequestMethod.GET, produces = "text/plain")
- public String layout(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
- String collapseDomains = request.getParameter("collapsedDomains");
- String expandDomains = request.getParameter("expandedDomains");
-
- String contentFileName = request.getParameter("contentFileName");
- String layoutFileName = request.getParameter("layoutFileName");
-
- final String realPath = request.getServletContext().getRealPath("/");
- logger.debug(EELFLoggerDelegate.debugLogger, "layout: servlet context real path: {}", realPath);
-
- ElementMapService eltMapSvc = new ElementMapService();
- String yamlString = eltMapSvc.buildElementMapYaml(
- new String[] { collapseDomains, expandDomains, realPath, contentFileName, layoutFileName });
-
- return yamlString;
- }
-
- @RequestMapping(value = { "/elementMapLink" }, method = RequestMethod.GET, produces = "text/plain")
- public String callflow(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
- String callFlowName = request.getParameter("callFlowName");
- String callFlowStep = request.getParameter("callFlowStep");
-
- final String realPath = request.getServletContext().getRealPath("/");
- logger.debug(EELFLoggerDelegate.debugLogger, "callflow: servlet context real path: {}", realPath);
-
- ElementLinkService eltLinkSvc = new ElementLinkService();
- String yamlString = eltLinkSvc.buildElementLinkYaml(new String[] { realPath, callFlowName, callFlowStep });
-
- return yamlString;
- }
-
- /*
- public ModelAndView callflowAdditional(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
- Map<String, Object> model = new HashMap<String, Object>();
- String callFlowName = request.getParameter("callFlowName");
- String callFlowStep = request.getParameter("callFlowStep");
-
- ElementLinkService main = new ElementLinkService();
- String yamlString = main.main2(new String[] { callFlowName, callFlowStep });
- model.put("output_string", yamlString);
- return new ModelAndView("data_out", "model", model);
- }
- */
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-/**
- * Controller for geographic map view. The view is restricted to authenticated
- * users. The view name defaults to the request name with no suffix,
- * "leafletMap", which resolves to page leafletMap.jsp.
- */
-@Controller
-@RequestMapping("/")
-public class LeafletMapContoller extends RestrictedBaseController {
-
- @RequestMapping(value = { "/leafletMap" }, method = RequestMethod.GET)
- public ModelAndView plot() {
- final String defaultViewName = null;
- return new ModelAndView(defaultViewName);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-/**
- * Controller for a network map view that uses iframes. The view is restricted
- * to authenticated users.
- */
-@Controller
-@RequestMapping("/")
-public class NetMapController extends RestrictedBaseController {
-
- @RequestMapping(value = { "/net_map" }, method = RequestMethod.GET)
- public ModelAndView plot(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- model.put("frame_int", "net_map_int");
- // This view resolves to page frame_insert.jsp
- return new ModelAndView("frame_insert", model);
- }
-
- @RequestMapping(value = { "/net_map_int" }, method = RequestMethod.GET)
- public ModelAndView plot2() {
- // The view name defaults to the request without any suffix.
- final String defaultViewName = null;
- // This view resolves to page net_map.jsp
- return new ModelAndView(defaultViewName);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import java.io.PrintWriter;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.command.PostDroolsBean;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.PostDroolsService;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Controller
-@RequestMapping("/")
-public class PostDroolsController extends RestrictedBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostDroolsController.class);
-
- @Autowired
- private PostDroolsService postDroolsService;
-
- @RequestMapping(value = { "/drools" }, method = RequestMethod.GET)
- public ModelAndView drools(HttpServletRequest request) {
- return new ModelAndView(getViewName());
- }
-
- @RequestMapping(value = { "/getDrools" }, method = RequestMethod.GET)
- public void getDrools(HttpServletRequest request, HttpServletResponse response) {
- // Map<String, Object> model = new HashMap<String, Object>();
-
- ObjectMapper mapper = new ObjectMapper();
- try {
- List<PostDroolsBean> beanList = postDroolsService.fetchDroolBeans();
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(beanList));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getDrools failed", e);
- }
- }
-
- @RequestMapping(value = { "/getDroolDetails" }, method = RequestMethod.GET)
- public void getDroolDetails(HttpServletRequest request, HttpServletResponse response) {
-
- ObjectMapper mapper = new ObjectMapper();
- try {
-
- PostDroolsBean postDroolsBean = new PostDroolsBean();
- String selectedFile = request.getParameter("selectedFile");
- postDroolsBean.setDroolsFile(selectedFile);// sample populated
- // postDroolsBean.setSelectedRules("[\"NJ\",\"NY\",\"KY\"]");
- postDroolsBean.setClassName(postDroolsService.retrieveClass(selectedFile));
-
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(postDroolsBean));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getDroolDetails failed", e);
- }
- }
-
- @RequestMapping(value = { "/post_drools/execute" }, method = RequestMethod.POST)
- public ModelAndView search(HttpServletRequest request, HttpServletResponse response) throws Exception {
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- PostDroolsBean postDroolsBean = mapper.readValue(root.get("postDroolsBean").toString(),
- PostDroolsBean.class);
-
- String resultsString = postDroolsService.execute(postDroolsBean.getDroolsFile(),
- postDroolsBean.getClassName(), postDroolsBean.getSelectedRules());
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- // String responseString = mapper.writeValueAsString(resultsString);
- JSONObject j = new JSONObject("{resultsString: " + resultsString + "}");
-
- out.write(j.toString());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "search failed", e);
- }
-
- return null;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-/**
- * Report dashboard
- *
- */
-
-@Controller
-@RequestMapping("/")
-public class ReportDashboardController extends RestrictedBaseController {
- @RequestMapping(value = {"/report_dashboard" }, method = RequestMethod.GET)
- public ModelAndView adminView(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- return new ModelAndView(getViewName(),"model", model);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.controller.sample;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-/**
- * Controller for a network map view that uses iframes. The view is restricted
- * to authenticated users.
- */
-@Controller
-@RequestMapping("/")
-public class SamplePageController extends RestrictedBaseController {
-
- @RequestMapping(value = { "/samplePage" }, method = RequestMethod.GET)
- public ModelAndView plot(HttpServletRequest request) {
- Map<String, Object> model = new HashMap<String, Object>();
- /*model.put("frame_int", "net_map_int");
- // This view resolves to page frame_insert.jsp
- return new ModelAndView("frame_insert", model);*/
- return new ModelAndView("samplePage", "model", model);
- }
-
-}
+++ /dev/null
-package org.openecomp.portalapp.controller.sample;
-
-/**
- * Provides controllers for EPSDK application sample pages such as call flow etc.
- */
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.model;
-
-public class Result {
- private String result;
-
- public Result(String result) {
- this.result = result;
- }
-
- public String getResult() {
- return result;
- }
-
- public void setResult(String result) {
- this.result = result;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.scheduler;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.quartz.DisallowConcurrentExecution;
-import org.quartz.JobExecutionContext;
-import org.quartz.JobExecutionException;
-import org.quartz.PersistJobDataAfterExecution;
-import org.springframework.scheduling.quartz.QuartzJobBean;
-
-@PersistJobDataAfterExecution
-@DisallowConcurrentExecution
-public class LogJob extends QuartzJobBean {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LogJob.class);
-
- @Override
- protected void executeInternal(JobExecutionContext ctx)
- throws JobExecutionException {
- // JobDataMap dataMap = ctx.getJobDetail().getJobDataMap();
- //int cnt = dataMap.getInt("");
- // JobKey jobKey = ctx.getJobDetail().getKey();
- logger.info(EELFLoggerDelegate.debugLogger, (Runtime.getRuntime().maxMemory() + " " + Runtime.getRuntime().maxMemory()));
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.scheduler;
-
-import java.text.ParseException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.openecomp.portalsdk.core.scheduler.CronRegistry;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.context.annotation.DependsOn;
-import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
-import org.springframework.scheduling.quartz.JobDetailFactoryBean;
-import org.springframework.stereotype.Component;
-
-@Component
-@DependsOn({ "systemProperties" })
-public class LogRegistry extends CronRegistry {
-
- private static final String groupName = "AppGroup";
- private static final String jobName = "LogJob";
- private static final String triggerName = "LogTrigger";
-
- // @Autowired
- // private SystemProperties systemProperties;
-
- // @Bean
- public JobDetailFactoryBean jobDetailFactoryBean() {
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("units", "bytes");
- return jobDetailFactoryBean(groupName, jobName, LogJob.class, map);
- }
-
- // @Bean
- public CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException {
- // "0 * * * * ? *
- return cronTriggerFactoryBean(groupName, triggerName, SystemProperties.getProperty(SystemProperties.LOG_CRON));
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.service;
-
-import java.util.Set;
-
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.User;
-
-/**
- * Defines methods that can be used to extend the features of the user/role
- * provisioning class supplied in EPSDK-Common.
- */
-public interface IAdminAuthExtension {
-
- /**
- * Invoked from OnBoardingApiServiceImpl#pushUser after user was saved. App
- * developers can provide a class with their own logic following this
- * action; for example, updating app's related tables
- *
- * @param user
- * User object sent by Portal
- */
- public void saveUserExtension(User user);
-
- /**
- * Invoked from OnBoardingApiServiceImpl#editUser after user was updated.
- * App developers can provide a class with their own logic following this
- * action; for example, updating app's related tables
- *
- * @param user
- * User object sent by Portal
- */
- public void editUserExtension(User user);
-
- /**
- * Invoked from OnBoardingApiServiceImpl#pushUserRole after user's roles
- * were updated. App developers can provide a class with their own logic
- * following this action; for example, updating app's related tables
- *
- * @param roles
- * Roles object sent by Portal
- * @param user
- * User object sent by Portal
- */
- public void saveUserRoleExtension(Set<Role> roles, User user);
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.service;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.auth.LoginStrategy;
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.domain.UserApp;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.client.AppContextManager;
-import org.openecomp.portalsdk.core.onboarding.crossapi.IPortalRestAPIService;
-import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException;
-import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
-import org.openecomp.portalsdk.core.restful.domain.EcompRole;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-import org.openecomp.portalsdk.core.service.RoleService;
-import org.openecomp.portalsdk.core.service.UserProfileService;
-import org.openecomp.portalsdk.core.service.WebServiceCallService;
-import org.openecomp.portalsdk.core.util.JSONUtil;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.slf4j.MDC;
-import org.springframework.context.ApplicationContext;
-
-/**
- * Implements the REST API interface to answer requests made by Portal app about
- * users and active sessions.
- *
- * Since an instance of this class will be instantiated by the OnBoarding
- * servlet from the ecompFW library, we cannot use Spring injections here. This
- * 'injection' is done indirectly using AppContextManager class.
- *
- * @author Ikram Ikramullah
- *
- */
-public class OnBoardingApiServiceImpl implements IPortalRestAPIService {
-
- private RoleService roleService;
- private UserProfileService userProfileService;
- private IAdminAuthExtension adminAuthExtensionServiceImpl;
-
- private LoginStrategy loginStrategy;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(OnBoardingApiServiceImpl.class);
-
- public OnBoardingApiServiceImpl() {
- // Defend against null-pointer exception during server startup
- // that was caused by a spurious Spring annotation on this class.
- ApplicationContext appContext = AppContextManager.getAppContext();
- if (appContext == null)
- throw new RuntimeException("OnBoardingApiServiceImpl ctor failed to get appContext");
- roleService = appContext.getBean(RoleService.class);
- userProfileService = appContext.getBean(UserProfileService.class);
- loginStrategy = appContext.getBean(LoginStrategy.class);
- // initialize the base class definition for Admin Auth Extension
- adminAuthExtensionServiceImpl = appContext.getBean(IAdminAuthExtension.class);
- }
-
- private void setCurrentAttributes(User user, EcompUser userJson) {
-
- user.setEmail(userJson.getEmail());
- user.setFirstName(userJson.getFirstName());
- user.setHrid(userJson.getHrid());
- user.setJobTitle(userJson.getJobTitle());
- user.setLastName(userJson.getLastName());
- user.setLoginId(userJson.getLoginId());
- user.setOrgManagerUserId(userJson.getOrgManagerUserId());
- user.setMiddleInitial(userJson.getMiddleInitial());
- user.setOrgCode(userJson.getOrgCode());
- user.setOrgId(userJson.getOrgId());
- user.setPhone(userJson.getPhone());
- user.setOrgUserId(userJson.getOrgUserId());
- user.setActive(userJson.isActive());
- // user.setRoles(new TreeSet(userJson.getRoles()));
- }
-
- @Override
- public void pushUser(EcompUser userJson) throws PortalAPIException {
-
- if (logger.isDebugEnabled())
- logger.debug(EELFLoggerDelegate.debugLogger, "pushUser was invoked: {}", userJson);
- User user = new User();
- String response = "";
- try {
- // Set input attributes to the object obout to be saved
- setCurrentAttributes(user, userJson);
- user.setRoles(new TreeSet<Role>());
- user.setUserApps(new TreeSet<UserApp>());
- user.setPseudoRoles(new TreeSet<Role>());
- userProfileService.saveUser(user);
- logger.debug(EELFLoggerDelegate.debugLogger, "push user success.");
-
- // After successful creation, call admin auth extension
- if (adminAuthExtensionServiceImpl != null) {
- try {
- adminAuthExtensionServiceImpl.saveUserExtension(user);
- } catch (Exception ex) {
- logger.error("pushUser: saveUserExtension failed", ex);
- }
- }
-
- response = "push user success.";
- response = JSONUtil.convertResponseToJSON(response);
- } catch (Exception e) {
- response = "OnboardingApiService.pushUser failed";
- logger.error(EELFLoggerDelegate.errorLogger, response, e);
- throw new PortalAPIException(response, e);
- } finally {
- MDC.remove(SystemProperties.MDC_TIMER);
- }
- }
-
- @Override
- public void editUser(String loginId, EcompUser userJson) throws PortalAPIException {
-
- if (logger.isDebugEnabled())
- logger.debug(EELFLoggerDelegate.debugLogger, "OnboardingApi editUser was invoked with loginID {}, JSON {}",
- loginId, userJson);
- User editUser = new User();
- String response = "";
- try {
- setCurrentAttributes(editUser, userJson);
- if (editUser.getOrgUserId() != null) {
- editUser.setLoginId(editUser.getOrgUserId());
- }
- User domainUser = userProfileService.getUserByLoginId(loginId);
- if (domainUser != null)
- domainUser = JSONUtil.mapToDomainUser(domainUser, editUser);
- else
- domainUser = editUser;
- userProfileService.saveUser(domainUser);
- logger.debug(EELFLoggerDelegate.debugLogger, "edit user success.");
-
- // After successful edit, call the admin auth extension
- if (adminAuthExtensionServiceImpl != null) {
- try {
- adminAuthExtensionServiceImpl.editUserExtension(domainUser);
- } catch (Exception ex) {
- logger.error("editUser: editUserExtension failed", ex);
- }
- }
-
- response = "edit user success.";
- response = JSONUtil.convertResponseToJSON(response);
- } catch (Exception e) {
- response = "OnboardingApiService.editUser failed";
- logger.error(EELFLoggerDelegate.errorLogger, response, e);
- throw new PortalAPIException(response, e);
- } finally {
- MDC.remove(SystemProperties.MDC_TIMER);
- }
-
- // return response;
- }
-
- @Override
- public EcompUser getUser(String loginId) throws PortalAPIException {
- try {
- if (logger.isDebugEnabled())
- logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: {}", loginId);
- User user = userProfileService.getUserByLoginId(loginId);
- if (user == null) {
- logger.info(EELFLoggerDelegate.debugLogger, "User + " + loginId + " doesn't exist");
- return null;
- // Unfortunately, Portal is not ready to accept proper error
- // response yet ..
- // commenting throw clauses until portal is ready
- // throw new PortalAPIException("User + " + loginId + " doesn't
- // exist");
- } else
- return UserUtils.convertToEcompUser(user);
- } catch (Exception e) {
- String response = "OnboardingApiService.getUser failed";
- logger.error(EELFLoggerDelegate.errorLogger, response, e);
- return null;
- // Unfortunately, Portal is not ready to accept proper error response
- // yet .. commenting throw clauses until portal is ready
- // throw new PortalAPIException(response, e);
- }
-
- }
-
- @Override
- public List<EcompUser> getUsers() throws PortalAPIException {
- try {
- List<User> users = userProfileService.findAllActive();
- List<EcompUser> ecompUsers = new ArrayList<EcompUser>();
- for (User user : users)
- ecompUsers.add(UserUtils.convertToEcompUser(user));
- return ecompUsers;
- } catch (Exception e) {
- String response = "OnboardingApiService.getUsers failed";
- logger.error(EELFLoggerDelegate.errorLogger, response, e);
- throw new PortalAPIException(response, e);
- }
- }
-
- @Override
- public List<EcompRole> getAvailableRoles(String requestedLoginId) throws PortalAPIException {
- try {
- List<Role> roles = roleService.getActiveRoles(requestedLoginId);
- List<EcompRole> ecompRoles = new ArrayList<EcompRole>();
- for (Role role : roles)
- ecompRoles.add(UserUtils.convertToEcompRole(role));
- return ecompRoles;
- } catch (Exception e) {
- String response = "OnboardingApiService.getAvailableRoles failed";
- logger.error(EELFLoggerDelegate.errorLogger, response, e);
- throw new PortalAPIException(response, e);
- }
- }
-
- @Override
- public void pushUserRole(String loginId, List<EcompRole> rolesJson) throws PortalAPIException {
- String response = "";
- try {
- if (logger.isDebugEnabled())
- logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: {}, roles Json {}", loginId,
- rolesJson);
- User user = userProfileService.getUserByLoginId(loginId);
- /*
- * List<EcompRole> ecompRoles = mapper.readValue(rolesJson,
- * TypeFactory.defaultInstance().constructCollectionType(List.class,
- * EcompRole.class));
- */
- SortedSet<Role> roles = new TreeSet<Role>();
- for (EcompRole role : rolesJson) {
- roles.add(roleService.getRole(loginId,role.getId()));
- }
- // Replace existing roles with new ones
- replaceExistingRoles(roles, user);
-
- logger.debug(EELFLoggerDelegate.debugLogger, "push user role success.");
-
- // After successful creation, call admin auth extension
- if (adminAuthExtensionServiceImpl != null) {
- try {
- adminAuthExtensionServiceImpl.saveUserRoleExtension(roles, user);
- } catch (Exception ex) {
- logger.error("pushUserRole: saveUserRoleExtension failed", ex);
- }
- }
- response = "push user role success.";
- response = JSONUtil.convertResponseToJSON(response);
-
- } catch (Exception e) {
- response = "OnboardingApiService.pushUserRole failed";
- logger.error(EELFLoggerDelegate.errorLogger, response, e);
- throw new PortalAPIException(response, e);
- } finally {
- MDC.remove(SystemProperties.MDC_TIMER);
- }
-
- }
-
- @Override
- public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException {
- if (logger.isDebugEnabled())
- logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: {}", loginId);
- List<EcompRole> ecompRoles = new ArrayList<EcompRole>();
- try {
- User user = userProfileService.getUserByLoginId(loginId);
- SortedSet<Role> currentRoles = null;
- if (user != null) {
- currentRoles = user.getRoles();
- if (currentRoles != null)
- for (Role role : currentRoles)
- ecompRoles.add(UserUtils.convertToEcompRole(role));
- }
- return ecompRoles;
- } catch (Exception e) {
- String response = "OnboardingApiService.getUserRoles failed";
- logger.error(EELFLoggerDelegate.errorLogger, response, e);
- throw new PortalAPIException(response, e);
- }
- }
-
- @SuppressWarnings("unchecked")
- private void replaceExistingRoles(SortedSet<Role> roles, User user) {
- // 1. remove existing roles
- Set<UserApp> userApps = user.getUserApps();
- Iterator<UserApp> appsItr = userApps.iterator();
- while (appsItr.hasNext()) {
- UserApp tempUserApp = appsItr.next();
- boolean roleFound = false;
- for (Role role : roles) {
- if (tempUserApp.getRole().getId().equals(role.getId())) {
- roleFound = true;
- break;
- }
- }
- if (!roleFound)
- appsItr.remove();
- }
- user.setUserApps(userApps);
- userProfileService.saveUser(user);
-
- // 2. add new roles
- user.setRoles(roles);
- userProfileService.saveUser(user);
- }
-
- @Override
- public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException {
- WebServiceCallService securityService = AppContextManager.getAppContext().getBean(WebServiceCallService.class);
- try {
- String appUser = request.getHeader("username");
- String password = request.getHeader("password");
- // System.out.println("username = " + appUser);
- // System.out.println("password = " + password);
- boolean flag = securityService.verifyRESTCredential(null, appUser, password);
- // System.out.println("username = " + appUser);
- // System.out.println("password = " + password);
- return flag;
-
- } catch (Exception e) {
- String response = "OnboardingApiService.isAppAuthenticated failed";
- logger.error(EELFLoggerDelegate.errorLogger, response, e);
- throw new PortalAPIException(response, e);
- }
- }
-
- public String getSessionTimeOuts() throws Exception {
- return PortalTimeoutHandler.gatherSessionExtensions();
- }
-
- public void updateSessionTimeOuts(String sessionMap) throws Exception {
- PortalTimeoutHandler.updateSessionExtensions(sessionMap);
- }
-
- @Override
- public String getUserId(HttpServletRequest request) throws PortalAPIException {
- return loginStrategy.getUserId(request);
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.util;
-
-import ch.qos.logback.classic.Level;
-import ch.qos.logback.classic.spi.ILoggingEvent;
-import ch.qos.logback.core.filter.Filter;
-import ch.qos.logback.core.spi.FilterReply;
-
-/**
- * Custom Filter class bind with logback.xml
- * configuration file to strip out certain log messages
- * coming out of special packages or classes.
- *
- */
-public class CustomLoggingFilter extends Filter<ILoggingEvent> {
-
- /**
- * Custom Filter is added to strip out the continuous U-EB logging messages
- * But make sure we log the ERROR & WARNING Level messages.
- */
- @Override
- public FilterReply decide(ILoggingEvent event) {
- try {
- if ((event.getLevel() != Level.ERROR || event.getLevel() != Level.WARN) &&
- (event.getThreadName().equalsIgnoreCase("UEBConsumerThread")) &&
- (event.getLoggerName().contains("org.openecomp.nsa") || event.getLoggerName().contains("org.apache.http"))
- ) {
- return FilterReply.DENY;
- } else {
- return FilterReply.NEUTRAL;
- }
- } catch(Exception e) {
- return FilterReply.NEUTRAL;
- }
- }
-}
--- /dev/null
+package org.onap.portalapp;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.onap.portalapp.core.MockApplicationContextTestSuite;
+import org.springframework.test.web.servlet.ResultActions;
+import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
+
+public class SanityTest extends MockApplicationContextTestSuite {
+
+ @Test
+ public void testGetAvailableRoles() throws Exception {
+
+ ResultActions ra =getMockMvc().perform(MockMvcRequestBuilders.get("/api/roles"));
+ //Assert.assertEquals(UrlAccessRestrictedException.class,ra.andReturn().getResolvedException().getClass());
+ Assert.assertEquals("application/json",ra.andReturn().getResponse().getContentType());
+ }
+
+
+}
--- /dev/null
+package org.onap.portalapp.controller;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.onap.portalapp.core.MockApplicationContextTestSuite;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.test.web.servlet.ResultActions;
+import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
+import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
+
+
+
+public class CollaborationControllerTest extends MockApplicationContextTestSuite{
+
+ @Test
+ public void testGetAvailableRoles() throws Exception {
+ MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/collaborate_list");
+ User user = new User();
+ user.setId(1l);
+ //user.setOrgUserId("abc");
+ requestBuilder.sessionAttr(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
+
+ ResultActions ra =getMockMvc().perform(requestBuilder);
+ Assert.assertEquals(2,ra.andReturn().getModelAndView().getModelMap().size());
+ }
+
+
+}
--- /dev/null
+package org.onap.portalapp.controller;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.onap.portalapp.core.MockApplicationContextTestSuite;
+import org.springframework.test.web.servlet.ResultActions;
+import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
+
+public class NetMapTest extends MockApplicationContextTestSuite {
+
+ @Test
+ public void testGetNetMap() throws Exception {
+ ResultActions ra =getMockMvc().perform(MockMvcRequestBuilders.get("/net_map"));
+ //Assert.assertEquals(UrlAccessRestrictedException.class,ra.andReturn().getResolvedException().getClass());
+ Assert.assertEquals("net_map_int",ra.andReturn().getModelAndView().getModel().get("frame_int"));
+ }
+
+
+}
--- /dev/null
+package org.onap.portalapp.core;
+
+import java.io.IOException;
+
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.onap.portalsdk.core.conf.AppConfig;
+import org.onap.portalsdk.core.objectcache.AbstractCacheManager;
+import org.onap.portalsdk.core.util.CacheManager;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
+import org.springframework.test.context.web.WebAppConfiguration;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+
+
+
+/**
+ *
+ *
+ *
+ * In order to write a unit test,
+ * 1. inherit this class - See SanityTest.java
+ * 2. place the "war" folder on your test class's classpath
+ * 3. run the test with the following VM argument; This is important because when starting the application from Container, the System Properties file (SystemProperties.java) can have the direct path
+ * but, when running from the Mock Junit container, the path should be prefixed with "classpath" to enable the mock container to search for the file in the classpath
+ * -Dcontainer.classpath="classpath:"
+ *
+ */
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@WebAppConfiguration
+@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = {MockAppConfig.class})
+@ActiveProfiles(value="test")
+public class MockApplicationContextTestSuite {
+
+ @Autowired
+ public WebApplicationContext wac;
+
+ private MockMvc mockMvc;
+
+ @Before
+ public void setup() {
+ if(mockMvc == null) {
+ this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
+
+ }
+ }
+
+ public Object getBean(String name) {
+ return this.wac.getBean(name);
+ }
+
+
+ public MockMvc getMockMvc() {
+ return mockMvc;
+ }
+
+ public void setMockMvc(MockMvc mockMvc) {
+ this.mockMvc = mockMvc;
+ }
+
+ public WebApplicationContext getWebApplicationContext() {
+ return wac;
+ }
+
+
+
+
+}
+
+
+ @Configuration
+ @ComponentScan(basePackages = "org.onap",
+ excludeFilters = {
+ }
+ )
+ @Profile("test")
+ class MockAppConfig extends AppConfig {
+
+ @Bean
+ public SystemProperties systemProperties(){
+ return new MockSystemProperties();
+ }
+
+ @Bean
+ public AbstractCacheManager cacheManager() {
+ return new CacheManager() {
+
+ public void configure() throws IOException {
+
+ }
+ };
+ }
+
+ protected String[] tileDefinitions() {
+ return new String[] {"classpath:/WEB-INF/fusion/defs/definitions.xml", "classpath:/WEB-INF/defs/definitions.xml"};
+ }
+
+ @Override
+ public void addInterceptors(InterceptorRegistry registry) {
+ //registry.addInterceptor(new SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout());
+ //registry.addInterceptor(resourceInterceptor());
+ }
+
+ public static class MockSystemProperties extends SystemProperties {
+
+ public MockSystemProperties() {
+ }
+
+ }
+
+ }
+
+
+
+
--- /dev/null
+package org.onap.portalapp.service;
+
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.onap.portalapp.core.MockApplicationContextTestSuite;
+import org.onap.portalsdk.core.domain.Profile;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.service.ProfileService;
+import org.onap.portalsdk.core.service.UserProfileService;
+import org.springframework.beans.factory.annotation.Autowired;
+
+
+
+
+public class ProfileServiceTest extends MockApplicationContextTestSuite {
+
+ @Autowired
+ ProfileService service;
+
+ @Autowired
+ UserProfileService userProfileService;
+
+ @Test
+ public void testFindAll() throws Exception{
+
+ List<Profile> profiles = service.findAll();
+ Assert.assertTrue(profiles.size() > 0);
+ }
+
+ @Test
+ public void testFindAllActive() {
+
+ List<User> users = userProfileService.findAllActive();
+ List<User> activeUsers = userProfileService.findAllActive();
+ Assert.assertTrue(users.size() - activeUsers.size() >= 0);
+ }
+}
--- /dev/null
+package org.onap.portalapp.workflow.services;
+
+import java.util.Calendar;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.onap.portalapp.core.MockApplicationContextTestSuite;
+import org.onap.portalsdk.workflow.domain.WorkflowSchedule;
+import org.onap.portalsdk.workflow.services.WorkflowScheduleService;
+import org.springframework.beans.factory.annotation.Autowired;
+
+
+
+public class WorkflowScheduleServiceTest extends MockApplicationContextTestSuite {
+
+ @Autowired
+ WorkflowScheduleService service;
+// @Autowired
+// SchedulerFactoryBean schedulerBean;
+
+ @Test
+ public void testFire() {
+
+ // List<WorkflowSchedule> wfs = service.findAll();
+
+ final WorkflowSchedule ws = new WorkflowSchedule();
+ ws.setId(999L);
+ ws.setWorkflowKey("test");
+ ws.setCronDetails("0 38 13 3 5 ? 2016");
+ final Calendar instance = Calendar.getInstance();
+ instance.add(Calendar.YEAR, 3);
+ ws.setEndDateTime(instance.getTime());
+
+ ws.setStartDateTime(Calendar.getInstance().getTime());
+ try{
+ service.saveWorkflowSchedule(ws);
+ Assert.assertTrue(true);
+ } catch(Exception e) {
+ Assert.fail(e.getMessage());
+ }
+
+ }
+
+}
+++ /dev/null
-package org.openecomp.portalapp;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.openecomp.portalapp.core.MockApplicationContextTestSuite;
-import org.springframework.test.web.servlet.ResultActions;
-import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
-
-public class SanityTest extends MockApplicationContextTestSuite {
-
- @Test
- public void testGetAvailableRoles() throws Exception {
-
- ResultActions ra =getMockMvc().perform(MockMvcRequestBuilders.get("/api/roles"));
- //Assert.assertEquals(UrlAccessRestrictedException.class,ra.andReturn().getResolvedException().getClass());
- Assert.assertEquals("application/json",ra.andReturn().getResponse().getContentType());
- }
-
-
-}
+++ /dev/null
-package org.openecomp.portalapp.controller;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.openecomp.portalapp.core.MockApplicationContextTestSuite;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.test.web.servlet.ResultActions;
-import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
-import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
-
-
-
-public class CollaborationControllerTest extends MockApplicationContextTestSuite{
-
- @Test
- public void testGetAvailableRoles() throws Exception {
- MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/collaborate_list");
- User user = new User();
- user.setId(1l);
- //user.setOrgUserId("abc");
- requestBuilder.sessionAttr(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
-
- ResultActions ra =getMockMvc().perform(requestBuilder);
- Assert.assertEquals(2,ra.andReturn().getModelAndView().getModelMap().size());
- }
-
-
-}
+++ /dev/null
-package org.openecomp.portalapp.controller;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.openecomp.portalapp.core.MockApplicationContextTestSuite;
-import org.springframework.test.web.servlet.ResultActions;
-import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
-
-public class NetMapTest extends MockApplicationContextTestSuite {
-
- @Test
- public void testGetNetMap() throws Exception {
- ResultActions ra =getMockMvc().perform(MockMvcRequestBuilders.get("/net_map"));
- //Assert.assertEquals(UrlAccessRestrictedException.class,ra.andReturn().getResolvedException().getClass());
- Assert.assertEquals("net_map_int",ra.andReturn().getModelAndView().getModel().get("frame_int"));
- }
-
-
-}
+++ /dev/null
-package org.openecomp.portalapp.core;
-
-import java.io.IOException;
-
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.openecomp.portalsdk.core.conf.AppConfig;
-import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager;
-import org.openecomp.portalsdk.core.util.CacheManager;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Profile;
-import org.springframework.test.context.ActiveProfiles;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
-import org.springframework.test.context.web.WebAppConfiguration;
-import org.springframework.test.web.servlet.MockMvc;
-import org.springframework.test.web.servlet.setup.MockMvcBuilders;
-import org.springframework.web.context.WebApplicationContext;
-import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
-
-
-
-/**
- *
- *
- *
- * In order to write a unit test,
- * 1. inherit this class - See SanityTest.java
- * 2. place the "war" folder on your test class's classpath
- * 3. run the test with the following VM argument; This is important because when starting the application from Container, the System Properties file (SystemProperties.java) can have the direct path
- * but, when running from the Mock Junit container, the path should be prefixed with "classpath" to enable the mock container to search for the file in the classpath
- * -Dcontainer.classpath="classpath:"
- *
- */
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@WebAppConfiguration
-@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = {MockAppConfig.class})
-@ActiveProfiles(value="test")
-public class MockApplicationContextTestSuite {
-
- @Autowired
- public WebApplicationContext wac;
-
- private MockMvc mockMvc;
-
- @Before
- public void setup() {
- if(mockMvc == null) {
- this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
-
- }
- }
-
- public Object getBean(String name) {
- return this.wac.getBean(name);
- }
-
-
- public MockMvc getMockMvc() {
- return mockMvc;
- }
-
- public void setMockMvc(MockMvc mockMvc) {
- this.mockMvc = mockMvc;
- }
-
- public WebApplicationContext getWebApplicationContext() {
- return wac;
- }
-
-
-
-
-}
-
-
- @Configuration
- @ComponentScan(basePackages = "org.openecomp",
- excludeFilters = {
- }
- )
- @Profile("test")
- class MockAppConfig extends AppConfig {
-
- @Bean
- public SystemProperties systemProperties(){
- return new MockSystemProperties();
- }
-
- @Bean
- public AbstractCacheManager cacheManager() {
- return new CacheManager() {
-
- public void configure() throws IOException {
-
- }
- };
- }
-
- protected String[] tileDefinitions() {
- return new String[] {"classpath:/WEB-INF/fusion/defs/definitions.xml", "classpath:/WEB-INF/defs/definitions.xml"};
- }
-
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- //registry.addInterceptor(new SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout());
- //registry.addInterceptor(resourceInterceptor());
- }
-
- public static class MockSystemProperties extends SystemProperties {
-
- public MockSystemProperties() {
- }
-
- }
-
- }
-
-
-
-
+++ /dev/null
-package org.openecomp.portalapp.service;
-
-import java.util.List;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.openecomp.portalapp.core.MockApplicationContextTestSuite;
-import org.openecomp.portalsdk.core.domain.Profile;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.service.ProfileService;
-import org.openecomp.portalsdk.core.service.UserProfileService;
-import org.springframework.beans.factory.annotation.Autowired;
-
-
-
-
-public class ProfileServiceTest extends MockApplicationContextTestSuite {
-
- @Autowired
- ProfileService service;
-
- @Autowired
- UserProfileService userProfileService;
-
- @Test
- public void testFindAll() throws Exception{
-
- List<Profile> profiles = service.findAll();
- Assert.assertTrue(profiles.size() > 0);
- }
-
- @Test
- public void testFindAllActive() {
-
- List<User> users = userProfileService.findAllActive();
- List<User> activeUsers = userProfileService.findAllActive();
- Assert.assertTrue(users.size() - activeUsers.size() >= 0);
- }
-}
+++ /dev/null
-package org.openecomp.portalapp.workflow.services;
-
-import java.util.Calendar;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.openecomp.portalapp.core.MockApplicationContextTestSuite;
-import org.openecomp.portalsdk.workflow.domain.WorkflowSchedule;
-import org.openecomp.portalsdk.workflow.services.WorkflowScheduleService;
-import org.springframework.beans.factory.annotation.Autowired;
-
-
-
-public class WorkflowScheduleServiceTest extends MockApplicationContextTestSuite {
-
- @Autowired
- WorkflowScheduleService service;
-// @Autowired
-// SchedulerFactoryBean schedulerBean;
-
- @Test
- public void testFire() {
-
- // List<WorkflowSchedule> wfs = service.findAll();
-
- final WorkflowSchedule ws = new WorkflowSchedule();
- ws.setId(999L);
- ws.setWorkflowKey("test");
- ws.setCronDetails("0 38 13 3 5 ? 2016");
- final Calendar instance = Calendar.getInstance();
- instance.add(Calendar.YEAR, 3);
- ws.setEndDateTime(instance.getTime());
-
- ws.setStartDateTime(Calendar.getInstance().getTime());
- try{
- service.saveWorkflowSchedule(ws);
- Assert.assertTrue(true);
- } catch(Exception e) {
- Assert.fail(e.getMessage());
- }
-
- }
-
-}
## Release Notes
-Version 1.3.0
+Version 1.4.0, <?day> <?month> 2017
+- PORTAL-19 Rename Java package base to org.onap
+- PORTAL-42 Use OParent as parent POM
+- PORTAL-72 Address Sonar Scan code issues
+- PORTAL-79 remove unwanted SDK left menu under Report-sample dashboard
+- PORTAL-90 Use approved ONAP license text
+* Put new entries here *
+
+Version 1.3.0, 28 August 2017
- PORTAL-17 removing eye.js and utils.js
- PORTAL-19 Renaming the Group Id in the POM file to org.onap.portal.sdk
- PORTAL-34 Restore required properties in fusion.properties file
INSERT INTO fn_menu (MENU_ID, LABEL, PARENT_ID, SORT_ORDER, ACTION, FUNCTION_CD, ACTIVE_YN, SERVLET, QUERY_STRING, EXTERNAL_URL, TARGET, MENU_SET_CD, SEPARATOR_YN, IMAGE_SRC) VALUES (10, 'Admin', 1, 110, 'role_list.htm', 'menu_admin', 'Y', NULL, NULL, NULL, NULL, 'APP', 'N', 'icon-content-star');
INSERT INTO fn_menu (MENU_ID, LABEL, PARENT_ID, SORT_ORDER, ACTION, FUNCTION_CD, ACTIVE_YN, SERVLET, QUERY_STRING, EXTERNAL_URL, TARGET, MENU_SET_CD, SEPARATOR_YN, IMAGE_SRC) VALUES (84, 'All Reports', 8, 50, 'report', 'menu_reports', 'Y', NULL, NULL, NULL, NULL, 'APP', 'N', '/static/fusion/images/reports.png');
INSERT INTO fn_menu (MENU_ID, LABEL, PARENT_ID, SORT_ORDER, ACTION, FUNCTION_CD, ACTIVE_YN, SERVLET, QUERY_STRING, EXTERNAL_URL, TARGET, MENU_SET_CD, SEPARATOR_YN, IMAGE_SRC) values (87, 'Create Reports', 8, 120, 'report#/report_wizard', 'menu_reports', 'Y', NULL, 'r_action=report.create', NULL, NULL, 'APP', 'N', NULL);
-INSERT INTO fn_menu (MENU_ID, LABEL, PARENT_ID, SORT_ORDER, ACTION, FUNCTION_CD, ACTIVE_YN, SERVLET, QUERY_STRING, EXTERNAL_URL, TARGET, MENU_SET_CD, SEPARATOR_YN, IMAGE_SRC) values (88, 'Sample Dashboard', 8, 130, 'report_dashboard', 'menu_reports', 'Y', NULL, NULL, NULL, NULL, 'APP', 'N', NULL);
+INSERT INTO fn_menu (MENU_ID, LABEL, PARENT_ID, SORT_ORDER, ACTION, FUNCTION_CD, ACTIVE_YN, SERVLET, QUERY_STRING, EXTERNAL_URL, TARGET, MENU_SET_CD, SEPARATOR_YN, IMAGE_SRC) values (88, 'Sample Dashboard', 8, 130, 'report_dashboard', 'menu_reports', 'N', NULL, NULL, NULL, NULL, 'APP', 'N', NULL);
INSERT INTO fn_menu (MENU_ID, LABEL, PARENT_ID, SORT_ORDER, ACTION, FUNCTION_CD, ACTIVE_YN, SERVLET, QUERY_STRING, EXTERNAL_URL, TARGET, MENU_SET_CD, SEPARATOR_YN, IMAGE_SRC) VALUES (89, 'Import', 8, 140, 'report#/report_import', 'menu_reports', 'N', null, null, null, null, 'APP', 'N', null);
INSERT INTO fn_menu (MENU_ID, LABEL, PARENT_ID, SORT_ORDER, ACTION, FUNCTION_CD, ACTIVE_YN, SERVLET, QUERY_STRING, EXTERNAL_URL, TARGET, MENU_SET_CD, SEPARATOR_YN, IMAGE_SRC) VALUES (94, 'Self', 9, 40,'userProfile#/self_profile', 'menu_profile', 'Y', NULL, NULL, NULL, NULL, 'APP', 'N', '/static/fusion/images/profile.png');
INSERT INTO fn_menu (MENU_ID, LABEL, PARENT_ID, SORT_ORDER, ACTION, FUNCTION_CD, ACTIVE_YN, SERVLET, QUERY_STRING, EXTERNAL_URL, TARGET, MENU_SET_CD, SEPARATOR_YN, IMAGE_SRC) VALUES (101, 'Roles', 10, 20, 'admin#/admin', 'menu_admin', 'Y', NULL, NULL, NULL, NULL, 'APP', 'N', '/static/fusion/images/users.png');
This is NOT the Portal - but it is developed and supported by the Portal team. -->
<groupId>org.onap.portal.sdk</groupId>
<artifactId>epsdk-app-os</artifactId>
- <version>1.3.0-SNAPSHOT</version>
+ <version>1.4.0-SNAPSHOT</version>
<packaging>war</packaging>
- <name>ECOMP SDK Webapp for OpenSource</name>
- <description>ECOMP SDK Web Application for public release</description>
+ <name>ONAP Portal SDK Webapp for OpenSource</name>
+ <description>ONAP Portal SDK Web Application for public release</description>
+
+ <!-- OParent provides license audit, code audit, distribution management,
+ etc. But jenkins build fails, so comment out for now.
+ <parent>
+ <groupId>org.onap.oparent</groupId>
+ <artifactId>oparent</artifactId>
+ <version>0.1.0</version>
+ <relativePath/>
+ </parent>
+ -->
<properties>
<encoding>UTF-8</encoding>
- <epsdk.version>1.3.0-SNAPSHOT</epsdk.version>
+ <epsdk.version>1.4.0-SNAPSHOT</epsdk.version>
<springframework.version>4.2.0.RELEASE</springframework.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<!-- Skip assembling the zip; assemble via mvn -Dskipassembly=false .. -->
<skipassembly>true</skipassembly>
<!-- Tests usually require some setup that maven cannot do, so skip. -->
<skiptests>true</skiptests>
- <nexusproxy>https://nexus.onap.org</nexusproxy>
- <snapshotNexusPath>content/repositories/snapshots/</snapshotNexusPath>
- <releaseNexusPath>content/repositories/releases/</releaseNexusPath>
</properties>
<repositories>
<repository>
- <id>ecomp-releases</id>
- <name>OpenECOMP - Release Repository</name>
- <url>${nexusproxy}/${releaseNexusPath}</url>
+ <id>onap-releases</id>
+ <name>ONAP - Release Repository</name>
+ <url>https://nexus.onap.org/content/repositories/releases</url>
+ </repository>
+ <repository>
+ <id>onap-staging</id>
+ <name>ONAP - Staging Repository</name>
+ <url>https://nexus.onap.org/content/repositories/staging</url>
</repository>
<repository>
- <id>ecomp-snapshots</id>
- <name>OpenECOMP - Snapshot Repository</name>
- <url>${nexusproxy}/${snapshotNexusPath}</url>
+ <id>onap-snapshots</id>
+ <name>ONAP - Snapshot Repository</name>
+ <url>https://nexus.onap.org/content/repositories/snapshots</url>
</repository>
<repository>
- <id>ecomp-public</id>
- <name>ecomp onap public Repository</name>
+ <id>onap-public</id>
+ <name>ONAP public Repository</name>
<url>https://nexus.onap.org/content/groups/public</url>
</repository>
</repositories>
+ <pluginRepositories>
+ <pluginRepository>
+ <id>releases</id>
+ <name>ONAP - Release Repository</name>
+ <url>https://nexus.onap.org/content/repositories/releases</url>
+ </pluginRepository>
+ <pluginRepository>
+ <id>staging</id>
+ <name>ONAP - Staging Repository</name>
+ <url>https://nexus.onap.org/content/repositories/staging</url>
+ </pluginRepository>
+ <pluginRepository>
+ <id>snapshots</id>
+ <name>ONAP - Snapshot Repository</name>
+ <url>https://nexus.onap.org/content/repositories/snapshots</url>
+ </pluginRepository>
+ </pluginRepositories>
<profiles>
<!-- disable doclint, a new feature in Java 8, when generating javadoc -->
<!-- The war file name carries no version number -->
<finalName>${project.artifactId}</finalName>
+ <pluginManagement>
+ <plugins>
+ <!-- Silence Eclipse/m2e complaints about checkstyle plugin brought in by OParent -->
+ <plugin>
+ <groupId>org.eclipse.m2e</groupId>
+ <artifactId>lifecycle-mapping</artifactId>
+ <version>1.0.0</version>
+ <configuration>
+ <lifecycleMappingMetadata>
+ <pluginExecutions>
+ <pluginExecution>
+ <pluginExecutionFilter>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <versionRange>2.17,)</versionRange>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </pluginExecutionFilter>
+ <action>
+ <ignore />
+ </action>
+ </pluginExecution>
+ </pluginExecutions>
+ </lifecycleMappingMetadata>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+
<plugins>
<!-- Compile to Java 1.8 class output format -->
<plugin>
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.conf;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onap.portalapp.login.LoginStrategyImpl;
+import org.onap.portalapp.scheduler.RegistryAdapter;
+import org.onap.portalsdk.core.auth.LoginStrategy;
+import org.onap.portalsdk.core.conf.AppConfig;
+import org.onap.portalsdk.core.conf.Configurable;
+import org.onap.portalsdk.core.objectcache.AbstractCacheManager;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.util.CacheManager;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+import org.springframework.context.annotation.Profile;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.scheduling.annotation.EnableAsync;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.scheduling.quartz.SchedulerFactoryBean;
+import org.springframework.web.servlet.ViewResolver;
+import org.springframework.web.servlet.config.annotation.EnableWebMvc;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
+
+/**
+ * ONAP Portal SDK sample application. Extends core AppConfig class to
+ * reuse interceptors, view resolvers and other features defined there.
+ */
+@Configuration
+@EnableWebMvc
+@ComponentScan(basePackages = "org.onap")
+@PropertySource(value = { "${container.classpath:}/WEB-INF/conf/app/test.properties" }, ignoreResourceNotFound = true)
+@Profile("src")
+@EnableAsync
+@EnableScheduling
+public class ExternalAppConfig extends AppConfig implements Configurable {
+
+ private RegistryAdapter schedulerRegistryAdapter;
+
+ @Configuration
+ @Import(SystemProperties.class)
+ static class InnerConfiguration {
+ }
+
+ /**
+ * @see org.onap.portalsdk.core.conf.AppConfig#viewResolver()
+ */
+ public ViewResolver viewResolver() {
+ return super.viewResolver();
+ }
+
+ /**
+ * @see org.onap.portalsdk.core.conf.AppConfig#addResourceHandlers(ResourceHandlerRegistry)
+ *
+ * @param registry
+ */
+ public void addResourceHandlers(ResourceHandlerRegistry registry) {
+ super.addResourceHandlers(registry);
+ }
+
+ /**
+ * @see org.onap.portalsdk.core.conf.AppConfig#dataAccessService()
+ */
+ public DataAccessService dataAccessService() {
+ // Echo the JDBC URL to assist developers when starting the app.
+ System.out.println("ExternalAppConfig: " + SystemProperties.DB_CONNECTIONURL + " is "
+ + SystemProperties.getProperty(SystemProperties.DB_CONNECTIONURL));
+ return super.dataAccessService();
+ }
+
+ /**
+ * Creates a new list with a single entry that is the external app
+ * definitions.xml path.
+ *
+ * @return List of String, size 1
+ */
+ public List<String> addTileDefinitions() {
+ List<String> definitions = new ArrayList<String>();
+ definitions.add("/WEB-INF/defs/definitions.xml");
+ return definitions;
+ }
+
+ /**
+ * Adds request interceptors to the specified registry by calling
+ * {@link AppConfig#addInterceptors(InterceptorRegistry)}, but excludes
+ * certain paths from the session timeout interceptor.
+ */
+ @Override
+ public void addInterceptors(InterceptorRegistry registry) {
+ super.setExcludeUrlPathsForSessionTimeout("/login_external", "*/login_external.htm", "login", "/login.htm",
+ "/api*", "/single_signon.htm", "/single_signon");
+ super.addInterceptors(registry);
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link CacheManager} class.
+ *
+ * @return New instance of {@link CacheManager}
+ */
+ @Bean
+ public AbstractCacheManager cacheManager() {
+ return new CacheManager();
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
+ * populates it with triggers.
+ *
+ * @return New instance of {@link SchedulerFactoryBean}
+ * @throws Exception
+ */
+ // @Bean // ANNOTATION COMMENTED OUT
+ // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION
+ public SchedulerFactoryBean schedulerFactoryBean() throws Exception {
+ SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
+ scheduler.setTriggers(schedulerRegistryAdapter.getTriggers());
+ scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties"));
+ scheduler.setDataSource(dataSource());
+ return scheduler;
+ }
+
+ /**
+ * Sets the scheduler registry adapter.
+ *
+ * @param schedulerRegistryAdapter
+ */
+ @Autowired
+ public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) {
+ this.schedulerRegistryAdapter = schedulerRegistryAdapter;
+ }
+
+ @Bean
+ public LoginStrategy loginStrategy() {
+
+ return new LoginStrategyImpl();
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.conf;
+
+import org.onap.portalsdk.core.conf.AppInitializer;
+
+public class ExternalAppInitializer extends AppInitializer {
+
+ @Override
+ protected Class<?>[] getRootConfigClasses() {
+ return super.getRootConfigClasses();
+ }
+
+ @Override
+ protected Class<?>[] getServletConfigClasses() {
+ Class<?> appConfigClass = ExternalAppConfig.class;
+ // Show something on stdout to indicate the app is starting.
+ System.out.println("ExternalAppInitializer: servlet configuration class is " + appConfigClass.getName());
+ return new Class[] { appConfigClass };
+ }
+
+ /*
+ * URL request will direct to the Spring dispatcher for processing
+ */
+ @Override
+ protected String[] getServletMappings() {
+ return super.getServletMappings();
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.conf;
+
+import org.onap.portalsdk.core.conf.HibernateMappingLocatable;
+import org.springframework.context.annotation.Profile;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+import org.springframework.stereotype.Component;
+
+@Component
+@Profile("src")
+public class HibernateMappingLocations implements HibernateMappingLocatable {
+
+ @Override
+ public Resource[] getMappingLocations() {
+ return new Resource[] { new ClassPathResource("../fusion/orm/Fusion.hbm.xml"),
+ new ClassPathResource("../fusion/orm/Workflow.hbm.xml"),
+ new ClassPathResource("../fusion/orm/RNoteBookIntegration.hbm.xml") };
+ }
+
+ @Override
+ public String[] getPackagesToScan() {
+ return new String[] { "org.onap" };
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.lm;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.ServletContext;
+
+import org.onap.portalsdk.core.lm.FusionLicenseManager;
+import org.springframework.stereotype.Component;
+
+/*
+ * Please note that this class is not being used; its a dummy stub to have a qualifying bean for the interface.
+ */
+
+@Component
+public class FusionLicenseManagerImpl implements FusionLicenseManager {
+
+ @Override
+ public void initKeyStoreParam() {
+
+ }
+
+ @Override
+ public void initCipherParam() {
+
+ }
+
+ @Override
+ public void initLicenseParam() {
+
+ }
+
+ @Override
+ public void doInitWork() {
+
+ }
+
+ @Override
+ public int installLicense() {
+ return 0;
+ }
+
+ @Override
+ public synchronized int verifyLicense(ServletContext context) {
+ return 0;
+ }
+
+ @Override
+ public void generateLicense(Map<String, String> clientInfoMap, List<String> ipAddressList) throws Exception {
+
+ }
+
+ @Override
+ public String nvl(String s) {
+ return null;
+ }
+
+ @Override
+ public Date getExpiredDate() {
+ return null;
+ }
+
+ @Override
+ public void setExpiredDate(Date expiredDate) {
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.lm;
+
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+
+import org.onap.portalsdk.core.lm.LicenseableClass;
+
+/*
+ * Please note that this class is not being used; its a dummy stub to have a qualifying bean for the interface.
+ */
+
+public class LicenseableClassImpl implements LicenseableClass {
+
+ public String getApplicationName() {
+ return "";
+ }
+
+ public InputStream getPublicKeystoreAsInputStream() throws FileNotFoundException {
+ return null;
+ }
+
+ public String getAlias() {
+ return "";
+ }
+
+ public String getKeyPasswd() {
+ return "";
+ }
+
+ public String getPublicKeystorePassword() {
+ return "";
+ }
+
+ public String getCipherParamPassword() {
+ return "";
+ }
+
+ @SuppressWarnings("rawtypes")
+ public Class getClassToLicense() {
+ return this.getClass();
+ }
+}
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.portalapp.login;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.portalsdk.core.auth.LoginStrategy;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.web.servlet.ModelAndView;
+
+/**
+ * Implements basic single-signon login strategy for open-source applications
+ * when users start at Portal. Extracts an encrypted user ID sent by Portal.
+ */
+public class LoginStrategyImpl extends LoginStrategy {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginStrategyImpl.class);
+
+ /**
+ * login for open source is same as external login in the non-open-source
+ * version.
+ */
+ @Override
+ public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ return doExternalLogin(request, response);
+ }
+
+ @Override
+ public String getUserId(HttpServletRequest request) throws PortalAPIException {
+ // Check ECOMP Portal cookie
+ Cookie ep = getCookie(request, EP_SERVICE);
+ if (ep == null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getUserId: no EP_SERVICE cookie, returning null");
+ return null;
+ }
+
+ String userid = null;
+ try {
+ userid = getUserIdFromCookie(request);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getUserId failed", e);
+ }
+ return userid;
+ }
+
+ /**
+ * Searches the request for the user-ID cookie and decrypts the value using a
+ * key configured in properties
+ *
+ * @param request
+ * HttpServletRequest
+ * @return User ID
+ * @throws Exception
+ * On any failure
+ */
+ private String getUserIdFromCookie(HttpServletRequest request) throws Exception {
+ String userId = "";
+ Cookie userIdCookie = getCookie(request, USER_ID);
+ if (userIdCookie != null) {
+ final String cookieValue = userIdCookie.getValue();
+ if (!SystemProperties.containsProperty(SystemProperties.Decryption_Key))
+ throw new Exception("Failed to find property " + SystemProperties.Decryption_Key);
+ final String decryptionKey = SystemProperties.getProperty(SystemProperties.Decryption_Key);
+ userId = CipherUtil.decrypt(cookieValue, decryptionKey);
+ logger.debug(EELFLoggerDelegate.debugLogger, "getUserIdFromCookie: decrypted as {}", userId);
+ }
+ return userId;
+ }
+
+ /**
+ * Searches the request for the named cookie.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param cookieName
+ * Name of desired cookie
+ * @return Cookie if found; otherwise null.
+ */
+ private Cookie getCookie(HttpServletRequest request, String cookieName) {
+ Cookie[] cookies = request.getCookies();
+ if (cookies != null)
+ for (Cookie cookie : cookies)
+ if (cookie.getName().equals(cookieName))
+ return cookie;
+ return null;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.scheduler;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onap.portalapp.scheduler.LogRegistry;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.scheduler.Registerable;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.quartz.Trigger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.DependsOn;
+import org.springframework.stereotype.Component;
+
+@Component
+@DependsOn({ "logRegistry", "systemProperties" })
+public class Register implements Registerable {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Register.class);
+
+ private List<Trigger> scheduleTriggers = new ArrayList<Trigger>();
+ Trigger trigger[] = new Trigger[1];
+
+ @Autowired
+ private LogRegistry logRegistry;
+
+ @Override
+ public Trigger[] getTriggers() {
+ return getScheduleTriggers().toArray(trigger);
+ }
+
+ @Override
+ public void registerTriggers() {
+ // if the property value is not available; the cron will not be added
+ // and can be ignored. its safe to ignore the exceptions
+ try {
+ if (SystemProperties.getProperty(SystemProperties.LOG_CRON) != null)
+ getScheduleTriggers().add(logRegistry.getTrigger());
+ } catch (IllegalStateException ies) {
+ logger.info(EELFLoggerDelegate.debugLogger, ("Log Cron not available"));
+ }
+
+ }
+
+ public List<Trigger> getScheduleTriggers() {
+ return scheduleTriggers;
+ }
+
+ public void setScheduleTriggers(List<Trigger> scheduleTriggers) {
+ this.scheduleTriggers = scheduleTriggers;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.scheduler;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.onap.portalsdk.core.scheduler.Registerable;
+import org.onap.portalsdk.workflow.services.WorkflowScheduleService;
+import org.quartz.Trigger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.quartz.SchedulerFactoryBean;
+import org.springframework.stereotype.Component;
+
+@Component
+public class RegistryAdapter {
+
+ @Autowired
+ private Registerable registry;
+
+ @Autowired
+ private WorkflowScheduleService workflowScheduleService;
+
+ private SchedulerFactoryBean schedulerBean;
+
+ Trigger trigger[] = new Trigger[1];
+
+ public Trigger[] getTriggers() {
+
+ registry.registerTriggers();
+
+ List<Trigger> allTriggers = new ArrayList<Trigger>();
+
+ List<Trigger> coreTriggers = addCoreTriggers();
+ final Trigger[] extTriggerArray = registry.getTriggers();
+
+ allTriggers.addAll(Arrays.asList(extTriggerArray));
+ allTriggers.addAll(coreTriggers);
+
+ return allTriggers.toArray(trigger);
+ }
+
+ public List<Trigger> addCoreTriggers() {
+ // On startup of the application after crash recovery, invoke workflow
+ // schedule trigger
+ List<Trigger> triggers = getWorkflowScheduleService().triggerWorkflowScheduling();
+ return triggers;
+ }
+
+ public void setSchedulerBean(SchedulerFactoryBean _schedulerBean) {
+ schedulerBean = _schedulerBean;
+ }
+
+ public SchedulerFactoryBean getSchedulerBean() {
+ return schedulerBean;
+ }
+
+ public Registerable getRegistry() {
+ return registry;
+ }
+
+ public void setRegistry(Registerable registry) {
+ this.registry = registry;
+ }
+
+ public WorkflowScheduleService getWorkflowScheduleService() {
+ return workflowScheduleService;
+ }
+
+ public void setWorkflowScheduleService(WorkflowScheduleService workflowScheduleService) {
+ this.workflowScheduleService = workflowScheduleService;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalapp.service;
+
+import java.util.Set;
+
+import org.onap.portalapp.service.IAdminAuthExtension;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+
+@Service("adminAuthExtension")
+@Transactional
+/**
+ * Provides empty implementations of the methods in IAdminAuthExtension.
+ */
+public class AdminAuthExtension implements IAdminAuthExtension {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminAuthExtension.class);
+
+ public void saveUserExtension(User user) {
+ logger.debug("saveUserExtension");
+ }
+
+ public void editUserExtension(User user) {
+ logger.debug("editUserExtension");
+ }
+
+ public void saveUserRoleExtension(Set<Role> roles, User user) {
+ logger.debug("saveUserRoleExtension");
+ }
+
+}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.conf;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.openecomp.portalapp.login.LoginStrategyImpl;
-import org.openecomp.portalapp.scheduler.RegistryAdapter;
-import org.openecomp.portalsdk.core.auth.LoginStrategy;
-import org.openecomp.portalsdk.core.conf.AppConfig;
-import org.openecomp.portalsdk.core.conf.Configurable;
-import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.CacheManager;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Import;
-import org.springframework.context.annotation.Profile;
-import org.springframework.context.annotation.PropertySource;
-import org.springframework.scheduling.annotation.EnableAsync;
-import org.springframework.scheduling.annotation.EnableScheduling;
-import org.springframework.scheduling.quartz.SchedulerFactoryBean;
-import org.springframework.web.servlet.ViewResolver;
-import org.springframework.web.servlet.config.annotation.EnableWebMvc;
-import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
-import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
-
-/**
- * ECOMP Portal SDK sample application. ECOMP Portal SDK core AppConfig class to
- * reuse interceptors, view resolvers and other features defined there.
- */
-@Configuration
-@EnableWebMvc
-@ComponentScan(basePackages = "org.openecomp")
-@PropertySource(value = { "${container.classpath:}/WEB-INF/conf/app/test.properties" }, ignoreResourceNotFound = true)
-@Profile("src")
-@EnableAsync
-@EnableScheduling
-public class ExternalAppConfig extends AppConfig implements Configurable {
-
- private RegistryAdapter schedulerRegistryAdapter;
-
- @Configuration
- @Import(SystemProperties.class)
- static class InnerConfiguration {
- }
-
- /**
- * @see org.openecomp.portalsdk.core.conf.AppConfig#viewResolver()
- */
- public ViewResolver viewResolver() {
- return super.viewResolver();
- }
-
- /**
- * @see org.openecomp.portalsdk.core.conf.AppConfig#addResourceHandlers(ResourceHandlerRegistry)
- *
- * @param registry
- */
- public void addResourceHandlers(ResourceHandlerRegistry registry) {
- super.addResourceHandlers(registry);
- }
-
- /**
- * @see org.openecomp.portalsdk.core.conf.AppConfig#dataAccessService()
- */
- public DataAccessService dataAccessService() {
- // Echo the JDBC URL to assist developers when starting the app.
- System.out.println("ExternalAppConfig: " + SystemProperties.DB_CONNECTIONURL + " is "
- + SystemProperties.getProperty(SystemProperties.DB_CONNECTIONURL));
- return super.dataAccessService();
- }
-
- /**
- * Creates a new list with a single entry that is the external app
- * definitions.xml path.
- *
- * @return List of String, size 1
- */
- public List<String> addTileDefinitions() {
- List<String> definitions = new ArrayList<String>();
- definitions.add("/WEB-INF/defs/definitions.xml");
- return definitions;
- }
-
- /**
- * Adds request interceptors to the specified registry by calling
- * {@link AppConfig#addInterceptors(InterceptorRegistry)}, but excludes
- * certain paths from the session timeout interceptor.
- */
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- super.setExcludeUrlPathsForSessionTimeout("/login_external", "*/login_external.htm", "login", "/login.htm",
- "/api*", "/single_signon.htm", "/single_signon");
- super.addInterceptors(registry);
- }
-
- /**
- * Creates and returns a new instance of a {@link CacheManager} class.
- *
- * @return New instance of {@link CacheManager}
- */
- @Bean
- public AbstractCacheManager cacheManager() {
- return new CacheManager();
- }
-
- /**
- * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
- * populates it with triggers.
- *
- * @return New instance of {@link SchedulerFactoryBean}
- * @throws Exception
- */
- // @Bean // ANNOTATION COMMENTED OUT
- // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION
- public SchedulerFactoryBean schedulerFactoryBean() throws Exception {
- SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
- scheduler.setTriggers(schedulerRegistryAdapter.getTriggers());
- scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties"));
- scheduler.setDataSource(dataSource());
- return scheduler;
- }
-
- /**
- * Sets the scheduler registry adapter.
- *
- * @param schedulerRegistryAdapter
- */
- @Autowired
- public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) {
- this.schedulerRegistryAdapter = schedulerRegistryAdapter;
- }
-
- @Bean
- public LoginStrategy loginStrategy() {
-
- return new LoginStrategyImpl();
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.conf;
-
-import org.openecomp.portalsdk.core.conf.AppInitializer;
-
-public class ExternalAppInitializer extends AppInitializer {
-
- @Override
- protected Class<?>[] getRootConfigClasses() {
- return super.getRootConfigClasses();
- }
-
- @Override
- protected Class<?>[] getServletConfigClasses() {
- Class<?> appConfigClass = ExternalAppConfig.class;
- // Show something on stdout to indicate the app is starting.
- System.out.println("ExternalAppInitializer: servlet configuration class is " + appConfigClass.getName());
- return new Class[] { appConfigClass };
- }
-
- /*
- * URL request will direct to the Spring dispatcher for processing
- */
- @Override
- protected String[] getServletMappings() {
- return super.getServletMappings();
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.conf;
-
-import org.springframework.context.annotation.Profile;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.core.io.Resource;
-import org.springframework.stereotype.Component;
-
-import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable;
-
-@Component
-@Profile("src")
-public class HibernateMappingLocations implements HibernateMappingLocatable {
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalsdk.core.conf.HibernateMappingLocatable#
- * getMappingLocations()
- */
- @Override
- public Resource[] getMappingLocations() {
- return new Resource[] { new ClassPathResource("../fusion/orm/Fusion.hbm.xml"),
- new ClassPathResource("../fusion/orm/Workflow.hbm.xml"),
- new ClassPathResource("../fusion/orm/RNoteBookIntegration.hbm.xml") };
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalsdk.core.conf.HibernateMappingLocatable#
- * getPackagesToScan()
- */
- @Override
- public String[] getPackagesToScan() {
- return new String[] { "org.openecomp" };
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.lm;
-
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.ServletContext;
-
-import org.openecomp.portalsdk.core.lm.FusionLicenseManager;
-import org.springframework.stereotype.Component;
-
-/*
- * Please note that this class is not being used; its a dummy stub to have a qualifying bean for the interface.
- */
-
-@Component
-public class FusionLicenseManagerImpl implements FusionLicenseManager {
-
- @Override
- public void initKeyStoreParam() {
-
- }
-
- @Override
- public void initCipherParam() {
-
- }
-
- @Override
- public void initLicenseParam() {
-
- }
-
- @Override
- public void doInitWork() {
-
- }
-
- @Override
- public int installLicense() {
- return 0;
- }
-
- @Override
- public synchronized int verifyLicense(ServletContext context) {
- return 0;
- }
-
- @Override
- public void generateLicense(Map<String, String> clientInfoMap, List<String> ipAddressList) throws Exception {
-
- }
-
- @Override
- public String nvl(String s) {
- return null;
- }
-
- @Override
- public Date getExpiredDate() {
- return null;
- }
-
- @Override
- public void setExpiredDate(Date expiredDate) {
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.lm;
-
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-
-import org.openecomp.portalsdk.core.lm.LicenseableClass;
-
-/*
- * Please note that this class is not being used; its a dummy stub to have a qualifying bean for the interface.
- */
-
-public class LicenseableClassImpl implements LicenseableClass {
-
- public String getApplicationName() {
- return "";
- }
-
- public InputStream getPublicKeystoreAsInputStream() throws FileNotFoundException {
- return null;
- }
-
- public String getAlias() {
- return "";
- }
-
- public String getKeyPasswd() {
- return "";
- }
-
- public String getPublicKeystorePassword() {
- return "";
- }
-
- public String getCipherParamPassword() {
- return "";
- }
-
- @SuppressWarnings("rawtypes")
- public Class getClassToLicense() {
- return this.getClass();
- }
-}
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.login;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalsdk.core.auth.LoginStrategy;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException;
-import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.web.servlet.ModelAndView;
-
-/**
- * Implements basic single-signon login strategy for open-source applications
- * when users start at Portal. Extracts an encrypted user ID sent by Portal.
- */
-public class LoginStrategyImpl extends LoginStrategy {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginStrategyImpl.class);
-
- /**
- * login for open source is same as external login in the non-open-source
- * version.
- */
- @Override
- public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
- return doExternalLogin(request, response);
- }
-
- @Override
- public String getUserId(HttpServletRequest request) throws PortalAPIException {
- // Check ECOMP Portal cookie
- Cookie ep = getCookie(request, EP_SERVICE);
- if (ep == null) {
- logger.debug(EELFLoggerDelegate.debugLogger, "getUserId: no EP_SERVICE cookie, returning null");
- return null;
- }
-
- String userid = null;
- try {
- userid = getUserIdFromCookie(request);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getUserId failed", e);
- }
- return userid;
- }
-
- /**
- * Searches the request for the user-ID cookie and decrypts the value using a
- * key configured in properties
- *
- * @param request
- * HttpServletRequest
- * @return User ID
- * @throws Exception
- * On any failure
- */
- private String getUserIdFromCookie(HttpServletRequest request) throws Exception {
- String userId = "";
- Cookie userIdCookie = getCookie(request, USER_ID);
- if (userIdCookie != null) {
- final String cookieValue = userIdCookie.getValue();
- if (!SystemProperties.containsProperty(SystemProperties.Decryption_Key))
- throw new Exception("Failed to find property " + SystemProperties.Decryption_Key);
- final String decryptionKey = SystemProperties.getProperty(SystemProperties.Decryption_Key);
- userId = CipherUtil.decrypt(cookieValue, decryptionKey);
- logger.debug(EELFLoggerDelegate.debugLogger, "getUserIdFromCookie: decrypted as {}", userId);
- }
- return userId;
- }
-
- /**
- * Searches the request for the named cookie.
- *
- * @param request
- * HttpServletRequest
- * @param cookieName
- * Name of desired cookie
- * @return Cookie if found; otherwise null.
- */
- private Cookie getCookie(HttpServletRequest request, String cookieName) {
- Cookie[] cookies = request.getCookies();
- if (cookies != null)
- for (Cookie cookie : cookies)
- if (cookie.getName().equals(cookieName))
- return cookie;
- return null;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.scheduler;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.scheduler.Registerable;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.quartz.Trigger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.DependsOn;
-import org.springframework.stereotype.Component;
-
-@Component
-@DependsOn({ "logRegistry", "systemProperties" })
-public class Register implements Registerable {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Register.class);
-
- private List<Trigger> scheduleTriggers = new ArrayList<Trigger>();
- Trigger trigger[] = new Trigger[1];
-
- @Autowired
- private LogRegistry logRegistry;
-
- @Override
- public Trigger[] getTriggers() {
- return getScheduleTriggers().toArray(trigger);
- }
-
- @Override
- public void registerTriggers() {
- // if the property value is not available; the cron will not be added
- // and can be ignored. its safe to ignore the exceptions
- try {
- if (SystemProperties.getProperty(SystemProperties.LOG_CRON) != null)
- getScheduleTriggers().add(logRegistry.getTrigger());
- } catch (IllegalStateException ies) {
- logger.info(EELFLoggerDelegate.debugLogger, ("Log Cron not available"));
- }
-
- }
-
- public List<Trigger> getScheduleTriggers() {
- return scheduleTriggers;
- }
-
- public void setScheduleTriggers(List<Trigger> scheduleTriggers) {
- this.scheduleTriggers = scheduleTriggers;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.scheduler;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.openecomp.portalsdk.core.scheduler.Registerable;
-import org.openecomp.portalsdk.workflow.services.WorkflowScheduleService;
-import org.quartz.Trigger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.scheduling.quartz.SchedulerFactoryBean;
-import org.springframework.stereotype.Component;
-
-@Component
-public class RegistryAdapter {
-
- @Autowired
- private Registerable registry;
-
- @Autowired
- private WorkflowScheduleService workflowScheduleService;
-
- private SchedulerFactoryBean schedulerBean;
-
- Trigger trigger[] = new Trigger[1];
-
- public Trigger[] getTriggers() {
-
- registry.registerTriggers();
-
- List<Trigger> allTriggers = new ArrayList<Trigger>();
-
- List<Trigger> coreTriggers = addCoreTriggers();
- final Trigger[] extTriggerArray = registry.getTriggers();
-
- allTriggers.addAll(Arrays.asList(extTriggerArray));
- allTriggers.addAll(coreTriggers);
-
- return allTriggers.toArray(trigger);
- }
-
- public List<Trigger> addCoreTriggers() {
- // On startup of the application after crash recovery, invoke workflow
- // schedule trigger
- List<Trigger> triggers = getWorkflowScheduleService().triggerWorkflowScheduling();
- return triggers;
- }
-
- public void setSchedulerBean(SchedulerFactoryBean _schedulerBean) {
- schedulerBean = _schedulerBean;
- }
-
- public SchedulerFactoryBean getSchedulerBean() {
- return schedulerBean;
- }
-
- public Registerable getRegistry() {
- return registry;
- }
-
- public void setRegistry(Registerable registry) {
- this.registry = registry;
- }
-
- public WorkflowScheduleService getWorkflowScheduleService() {
- return workflowScheduleService;
- }
-
- public void setWorkflowScheduleService(WorkflowScheduleService workflowScheduleService) {
- this.workflowScheduleService = workflowScheduleService;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.portalapp.service;
-
-import java.util.Set;
-
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-
-@Service("adminAuthExtension")
-@Transactional
-/**
- * Provides empty implementations of the methods in IAdminAuthExtension.
- */
-public class AdminAuthExtension implements IAdminAuthExtension {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminAuthExtension.class);
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.service.IAdminAuthExtension#saveUserExtension(org.openecomp.portalsdk.core.domain.User)
- */
- public void saveUserExtension(User user) {
- logger.debug("saveUserExtension");
- }
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.service.IAdminAuthExtension#editUserExtension(org.openecomp.portalsdk.core.domain.User)
- */
- public void editUserExtension(User user) {
- logger.debug("editUserExtension");
- }
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.service.IAdminAuthExtension#saveUserRoleExtension(java.util.Set, org.openecomp.portalsdk.core.domain.User)
- */
- public void saveUserRoleExtension(Set<Role> roles, User user) {
- logger.debug("saveUserRoleExtension");
- }
-
-}
<?xml version="1.0" encoding="UTF-8"?>
<!--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
-->
<configuration scan="true" scanPeriod="3 seconds" debug="true">
<!--
- Logback files for the ECOMP Portal SDK Application "epsdk-app-os"
+ Logback files for the ONAP Portal SDK Application "epsdk-app-os"
are created in directory ${catalina.base}/logs/epsdk_app_os;
e.g., apache-tomcat-8.0.35/logs/epsdk_app_os/application.log
-->
<encoder>
<pattern>${applicationLoggerPattern}</pattern>
</encoder>
- <filter class="org.openecomp.portalapp.util.CustomLoggingFilter" />
+ <filter class="org.onap.portalapp.util.CustomLoggingFilter" />
</appender>
<appender name="asyncEELF" class="ch.qos.logback.classic.AsyncAppender">
###
-# ================================================================================
-# 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.
+# ============LICENSE_START==========================================
+# ONAP Portal SDK
+# ===================================================================
+# Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+# ===================================================================
+#
+# Unless otherwise specified, all software contained herein is licensed
+# under the Apache License, Version 2.0 (the “License”);
+# you may not use this software except in compliance with the License.
# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
+#
+# 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.
-# ================================================================================
+#
+# Unless otherwise specified, all documentation contained herein is licensed
+# under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+# you may not use this documentation except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://creativecommons.org/licenses/by/4.0/
+#
+# Unless required by applicable law or agreed to in writing, documentation
+# 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.
+#
+# ============LICENSE_END============================================
+#
+# ECOMP is a trademark and service mark of AT&T Intellectual Property.
###
# Properties read by ECOMP Framework library, ecompFW.jar
##########################################################################
# Name of java class that implements the OnBoardingApiService interface.
-portal.api.impl.class = org.openecomp.portalapp.service.OnBoardingApiServiceImpl
+portal.api.impl.class = org.onap.portalapp.service.OnBoardingApiServiceImpl
# URL of the Portal where this app is onboarded
ecomp_redirect_url = https://portal.openecomp.org/ecompportal/process_csp
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ page isELIgnored="false"%>
-<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties"%>
-<%@ page import="org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties"%>
-<%@ page import="org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants"%>
-<%@ page import="org.openecomp.portalsdk.core.domain.MenuData"%>
+<%@ page import="org.onap.portalsdk.core.util.SystemProperties"%>
+<%@ page import="org.onap.portalsdk.core.onboarding.util.PortalApiProperties"%>
+<%@ page import="org.onap.portalsdk.core.onboarding.util.PortalApiConstants"%>
+<%@ page import="org.onap.portalsdk.core.domain.MenuData"%>
<link rel="stylesheet" type="text/css" href="app/fusion/external/ebz/ebz_header/header.css">
<link rel="stylesheet" type="text/css" href="app/fusion/external/ebz/ebz_header/portal_ebz_header.css">
<link rel="stylesheet" type="text/css" href="app/fusion/external/ebz/sandbox/styles/style.css" >
<?xml version="1.0"?>
<!--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
-<hibernate-mapping package="org.openecomp.portalsdk.rnotebookintegration.domain">
+<hibernate-mapping package="org.onap.portalsdk.rnotebookintegration.domain">
<!-- RNotebookIntegration mapping details -->
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
-<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties"%>
+<%@ page import="org.onap.portalsdk.core.util.SystemProperties"%>
<!DOCTYPE html>
<%
// Name is defined by app; do not throw if missing
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
-<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties"%>
+<%@ page import="org.onap.portalsdk.core.util.SystemProperties"%>
<!DOCTYPE html>
<%
// Name is defined by app; do not throw if missing
<th>User ID</th>
<th>Manager User ID</th>
<th>Edit</th>
- <th>Active?</th>
+ <th ng-show="(isAppCentralized=='false')">Active?</th>
</tr>
</thead>
<tbody type="body" ng-repeat="rowData in tableData">
<!-- Include an edit image with respective redirection -->
<td><a href="#/profile/{{rowData.id}}" class="icon-misc-pen"
style="color: #888; font-size: 20px;"></a></td>
- <td>
+ <td ng-show="(isAppCentralized=='false')">
<div class="form-row">
<label class="btn-switch-label" tabindex="0" role="option">
<input type="checkbox" b2b-switches
<div ng-show="showLoader" class="span loader-container">
<i class="icon-primary-spinner" role="img" aria-label="Please wait while we load your content"></i>
</div>
- <div ng-hide="showLoader" >
- <h3 class="heading-small">Please edit the profile details below:</h3>
+ <div ng-hide="showLoader" >
+ <h3 class="heading-small" ng-show="isAppCentralized=='true'" style="color:red;">Please use Portal for access management</h3>
+ <h3 class="heading-small" ng-show="isAppCentralized=='false'">Please edit the profile details below:</h3>
<div class="row-nowrap">
<div class="span12">
<div class="form-row">
<label for="textinputID-2a">*First Name</label>
<div class="field-group">
- <input id="textinputID-2a" b2b-reset="" class="span12" type="text" data-ng-model="profile.lastName">
+ <input id="textinputID-2a" b2b-reset="" class="span12" type="text" data-ng-model="profile.firstName" ng-disabled="(isAppCentralized == 'true')">
</div>
</div>
</div>
<div class="form-row">
<label for="textinputID-3a">*Last Name</label>
<div class="field-group">
- <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.firstName">
+ <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.lastName" ng-disabled="(isAppCentralized == 'true')">
</div>
</div>
</div>
<div class="form-row">
<label for="textinputID-3a">*Phone</label>
<div class="field-group">
- <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.phone">
+ <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.phone" ng-disabled="(isAppCentralized == 'true')">
</div>
</div>
</div>
<div class="form-row">
<label for="textinputID-3a">Fax</label>
<div class="field-group">
- <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.fax">
+ <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.fax" ng-disabled="(isAppCentralized == 'true')">
</div>
</div>
</div>
<div class="form-row">
<label for="textinputID-2a">Cellular</label>
<div class="field-group">
- <input id="textinputID-2a" b2b-reset="" class="span12" type="text" data-ng-model="profile.cellular">
+ <input id="textinputID-2a" b2b-reset="" class="span12" type="text" data-ng-model="profile.cellular" ng-disabled="(isAppCentralized == 'true')">
</div>
</div>
</div>
<div class="form-row">
<label for="textinputID-3a">*Email</label>
<div class="field-group">
- <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.email">
+ <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.email" ng-disabled="(isAppCentralized == 'true')">
</div>
</div>
</div>
<div class="form-row">
<label for="textinputID-3a">Address 1</label>
<div class="field-group">
- <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.address1">
+ <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.address1" ng-disabled="(isAppCentralized == 'true')">
</div>
</div>
</div>
<div class="form-row">
<label for="textinputID-3a">Address 2</label>
<div class="field-group">
- <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.address2">
+ <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.address2" ng-disabled="(isAppCentralized == 'true')">
</div>
</div>
</div>
<div class="form-row">
<label for="textinputID-2a">City</label>
<div class="field-group">
- <input id="textinputID-2a" b2b-reset="" class="span12" type="text" data-ng-model="profile.city">
+ <input id="textinputID-2a" b2b-reset="" class="span12" type="text" data-ng-model="profile.city" ng-disabled="(isAppCentralized == 'true')">
</div>
</div>
</div>
<div class="span12">
<div class="form-row">
<label for="textinputID-3a">State</label>
- <select name="dropdown1" b2b-dropdown ng-model="stateList.selected.value">
+ <select name="dropdown1" b2b-dropdown ng-model="stateList.selected.value" ng-disabled="(isAppCentralized == 'true')">
<option b2b-dropdown-list option-repeat="d in stateList.options" value="{{d.value}}" init-value="{{stateList.selected.title}}">{{d.title}}</option>
</select>
</div>
<div class="form-row">
<label for="textinputID-3a">Zip Code</label>
<div class="field-group">
- <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.zipCode">
+ <input id="textinputID-3a" b2b-reset="" class="span12" type="text" data-ng-model="profile.zipCode" ng-disabled="(isAppCentralized == 'true')">
</div>
</div>
</div>
<div class="span12">
<div class="form-row">
<label for="textinputID-3a">Country</label>
- <select name="dropdown1" b2b-dropdown ng-model="selectedCountry.value">
+ <select name="dropdown1" b2b-dropdown ng-model="selectedCountry.value" ng-disabled="(isAppCentralized == 'true')">
<option b2b-dropdown-list option-repeat="d in countries" value="{{d.value}}" init-value="{{selectedCountry.title}}">{{d.title}}</option>
</select>
</div>
<div class="span3">
<div class="form-row">
<label for="textinputID-3a">Time Zone</label>
- <select name="dropdown1" b2b-dropdown ng-model="selectedTimeZone.value">
+ <select name="dropdown1" b2b-dropdown ng-model="selectedTimeZone.value" ng-disabled="(isAppCentralized == 'true')">
<option b2b-dropdown-list option-repeat="d in timeZones" value="{{d.value}}" init-value="{{selectedTimeZone.title}}">{{d.title}}</option>
</select>
</div>
</div>
<div>
- <button class="btn btn-alt btn-small" type="button" ng-click="saveProfile()">Save</button>
+ <button class="btn btn-alt btn-small" type="button" ng-click="saveProfile()" ng-show="(isAppCentralized=='false')">Save</button>
</div>
<br>
- <div>
+ <div ng-show="(isAppCentralized=='false')">
Role
<a ng-click="addNewRoleFunctionModalPopup(role.roleFunctions,role.name, role);" class="icon-primary-accordion-plus" size="small"></a>
</div>
<thead>
<tr>
<th>Name</th>
- <th>Delete</th>
+ <th ng-show="(isAppCentralized=='false')">Delete</th>
</tr>
</thead>
<tbody type="body" ng-repeat="rowData in profile.roles">
<tr>
<td ng-bind="rowData['name']"></td>
- <td>
+ <td ng-show="(isAppCentralized=='false')">
<div style="font-size: 20px;">
<a href="javascript:void(0)" ng-click="removeRole(rowData);" class="icon-misc-trash"></a>
</div>
### ONAP Distributions
-Version 1.3.0
+Version 1.4.0
+- PORTAL-19 Rename Java package base to org.onap
+- PORTAL-42 Use OParent as parent POM
+- PORTAL-72 Address Sonar Scan code issues
+- PORTAL-90 Use approved ONAP license text
+* Put new entries here *
+
+Version 1.3.0, 28 August 2017
- Portal-17 removing eye.js and utils.js - rework
- Portal-19 Renaming the Group Id in the POM file to org.onap.portal.sdk
- Portal-21 Increased Role name size in UI
<parent>
<groupId>org.onap.portal.sdk</groupId>
<artifactId>epsdk-project</artifactId>
- <version>1.3.0-SNAPSHOT</version>
+ <version>1.4.0-SNAPSHOT</version>
</parent>
<!-- GroupId is inherited from parent -->
<artifactId>epsdk-app-overlay</artifactId>
<!-- Version is inherited from parent -->
<packaging>war</packaging>
- <name>ECOMP Portal SDK Webapp Overlay Files</name>
- <description>ECOMP Portal SDK Web Application overlay project</description>
+ <name>ONAP Portal SDK Webapp Overlay Files</name>
+ <description>ONAP Portal SDK Web Application overlay project</description>
<url>https://wiki.onap.org/display/DW/Portal</url>
- <properties>
- <encoding>UTF-8</encoding>
- </properties>
+ <!-- properties inherited from parent -->
+
+ <!-- repositories inherited from parent -->
<build>
<plugins>
-package org.openecomp.portalsdk.core.drools;
+package org.onap.portalsdk.core.drools;
rule "Drools NJ"
###
-# ================================================================================
-# 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.
+# ============LICENSE_START==========================================
+# ONAP Portal SDK
+# ===================================================================
+# Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+# ===================================================================
+#
+# Unless otherwise specified, all software contained herein is licensed
+# under the Apache License, Version 2.0 (the “License”);
+# you may not use this software except in compliance with the License.
# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
+#
+# 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.
-# ================================================================================
+#
+# Unless otherwise specified, all documentation contained herein is licensed
+# under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+# you may not use this documentation except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://creativecommons.org/licenses/by/4.0/
+#
+# Unless required by applicable law or agreed to in writing, documentation
+# 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.
+#
+# ============LICENSE_END============================================
+#
+# ECOMP is a trademark and service mark of AT&T Intellectual Property.
###
# Direct the proprietary logger used by com.mchange.c3p0 to use slf4j
-package org.openecomp.portalsdk.core.drools;
+package org.onap.portalsdk.core.drools;
global String age
rule "Default"
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
-<%@ page import="org.openecomp.portalsdk.core.web.support.UserUtils" %>
-<%@ page import="org.openecomp.portalsdk.core.web.support.ControllerProperties" %>
-<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties" %>
+<%@ page import="org.onap.portalsdk.core.web.support.UserUtils" %>
+<%@ page import="org.onap.portalsdk.core.web.support.ControllerProperties" %>
+<%@ page import="org.onap.portalsdk.core.util.SystemProperties" %>
<%-- <%@ include file="/WEB-INF/fusion/jsp/include.jsp" %> --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<%@ page import="java.util.*" %>
<%@ page import="com.fasterxml.jackson.databind.ObjectMapper" %>
<%@ page import="org.json.JSONObject" %>
<%@ page import="java.io.StringWriter" %>
-<%@ page import="org.openecomp.portalsdk.core.web.support.ControllerProperties" %>
+<%@ page import="org.onap.portalsdk.core.web.support.ControllerProperties" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
${model.output_string}
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ page isELIgnored="false"%>
-<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties"%>
-<%@ page import="org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties"%>
-<%@ page import="org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants"%>
-<%@ page import="org.openecomp.portalsdk.core.domain.MenuData"%>
+<%@ page import="org.onap.portalsdk.core.util.SystemProperties"%>
+<%@ page import="org.onap.portalsdk.core.onboarding.util.PortalApiProperties"%>
+<%@ page import="org.onap.portalsdk.core.onboarding.util.PortalApiConstants"%>
+<%@ page import="org.onap.portalsdk.core.domain.MenuData"%>
<link rel="stylesheet" type="text/css" href="app/fusion/external/ebz/ebz_header/header.css">
<link rel="stylesheet" type="text/css" href="app/fusion/external/ebz/ebz_header/portal_ebz_header.css">
<link rel="stylesheet" type="text/css" href="app/fusion/external/ebz/sandbox/styles/style.css" >
<!--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
-->
<script type="text/ng-template" id="loginSnippet.html">
<div style="line-height: normal; right: 167px; min-height: 200px; height: auto; width: auto; " ng-controller="loginSnippetCtrl" >
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!DOCTYPE html>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!DOCTYPE html>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<!-- <link rel="stylesheet" type="text/css" href="app/fusion/elasticsearch/styles/styles.css" > -->
<script>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<!-- <link rel="stylesheet" type="text/css" href="app/fusion/elasticsearch/styles/styles.css" > -->
<script>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<iframe id="frame_insert" src="${frame_int}"></iframe>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
-<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties" %>
-<%@ page import="org.openecomp.portalsdk.core.web.support.AppUtils" %>
+<%@ page import="org.onap.portalsdk.core.util.SystemProperties" %>
+<%@ page import="org.onap.portalsdk.core.web.support.AppUtils" %>
<%@ page import="java.util.LinkedHashMap" %>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<head>
<meta charset="utf-8">
<!--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
-->
<script type="text/ng-template" id="modal_informative.html">
<!--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
-->
<script type="text/ng-template" id="role_functions_popup.html">
<!--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
-->
<script type="text/ng-template" id="edit_role_function_popup.html">
<div class="modal__informative font-showcase" style="width:400px;">
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<?xml version="1.0"?>
<!--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
-<hibernate-mapping package="org.openecomp.portalsdk.core.domain">
+<hibernate-mapping package="org.onap.portalsdk.core.domain">
<!-- User class mapping details -->
<class name="User" table="FN_USER">
<set name="userApps" table="FN_USER_ROLE" lazy="false" sort="natural" inverse="true" cascade="all-delete-orphan">
<key column="user_id"/>
- <one-to-many class="org.openecomp.portalsdk.core.domain.UserApp" />
+ <one-to-many class="org.onap.portalsdk.core.domain.UserApp" />
</set>
<set name="pseudoRoles" table="FN_USER_PSEUDO_ROLE" lazy="false" sort="natural">
<key column="user_id"/>
- <many-to-many column="pseudo_role_id" class="org.openecomp.portalsdk.core.domain.Role" />
+ <many-to-many column="pseudo_role_id" class="org.onap.portalsdk.core.domain.Role" />
</set>
</class>
<key-property name="userId" type="long">
<column name="user_id" precision="11" scale="0" />
</key-property>
- <key-many-to-one name="app" class="org.openecomp.portalsdk.core.domain.App" column="app_id" />
- <key-many-to-one name="role" class="org.openecomp.portalsdk.core.domain.Role" column="role_id" />
+ <key-many-to-one name="app" class="org.onap.portalsdk.core.domain.App" column="app_id" />
+ <key-many-to-one name="role" class="org.onap.portalsdk.core.domain.Role" column="role_id" />
</composite-id>
<property name="priority" type="java.lang.Short">
<column name="priority" precision="4" scale="0" />
<set name="roleFunctions" table="FN_ROLE_FUNCTION" lazy="false" sort="natural">
<key column="role_id"/>
- <many-to-many column="function_cd" class="org.openecomp.portalsdk.core.domain.RoleFunction"/>
+ <many-to-many column="function_cd" class="org.onap.portalsdk.core.domain.RoleFunction"/>
</set>
<set name="childRoles" table="FN_ROLE_COMPOSITE" lazy="false" sort="natural">
<key column="parent_role_id"/>
- <many-to-many column="child_role_id" class="org.openecomp.portalsdk.core.domain.Role"/>
+ <many-to-many column="child_role_id" class="org.onap.portalsdk.core.domain.Role"/>
</set>
<set name="parentRoles" table="FN_ROLE_COMPOSITE" lazy="false" sort="natural">
<key column="child_role_id"/>
- <many-to-many column="parent_role_id" class="org.openecomp.portalsdk.core.domain.Role"/>
+ <many-to-many column="parent_role_id" class="org.onap.portalsdk.core.domain.Role"/>
</set>
</class>
<property name="siteCd" column="broadcast_site_cd" />
</class>
- <class name="org.openecomp.portalsdk.analytics.model.base.ReportUserRole" table="cr_report_access">
+ <class name="org.onap.portalsdk.analytics.model.base.ReportUserRole" table="cr_report_access">
<composite-id>
<key-property name="repId" column="rep_id" />
<key-property name="orderNo" column="order_no" />
<!-- Lookup (id/value bean) class mapping details -->
<class name="Lookup">
- <composite-id name="nameValueId" class="org.openecomp.portalsdk.core.domain.support.NameValueId">
+ <composite-id name="nameValueId" class="org.onap.portalsdk.core.domain.support.NameValueId">
<key-property name="val"/>
<key-property name="lab" />
</composite-id>
</class>
<class name="UrlsAccessible" table="V_URL_ACCESS">
- <composite-id name="urlsAccessibleKey" class="org.openecomp.portalsdk.core.domain.UrlsAccessibleKey">
+ <composite-id name="urlsAccessibleKey" class="org.onap.portalsdk.core.domain.UrlsAccessibleKey">
<key-property name="url" column="url"/>
<key-property name="functionCd" column="function_cd"/>
</composite-id>
<?xml version="1.0"?>
<!--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
-<hibernate-mapping package="org.openecomp.portalsdk.workflow.domain">
+<hibernate-mapping package="org.onap.portalsdk.workflow.domain">
<!-- WorkflowSchedule mapping details -->
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
${errMsg}
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<!DOCTYPE html>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
-<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties" %>
+<%@ page import="org.onap.portalsdk.core.util.SystemProperties" %>
<c:set var="title" value="Login" />
<c:set var="isMobileEnabled"
value="<%=(SystemProperties.getProperty(SystemProperties.MOBILE_ENABLE)!= null && SystemProperties.getProperty(SystemProperties.MOBILE_ENABLE).trim().equals(\"true\"))%>" />
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<!DOCTYPE html>
<html>
var message = msg;
$scope.cancel();
if(message.role){
- $rootScope.$broadcast('updateRoleFunctions',{data:message.role});
+ $rootScope.$broadcast('updateRoleFunctions',{data:message.role,removedRoleFunc: roleFunction.name});
}else{
$modal.open({
templateUrl: 'app/fusion/scripts/DS2-modal/error_modal.html',
// updating role functions on roles page after deletion of a role function
$rootScope.$on('updateRoleFunctions',function(e,d){
$scope.role = d.data;
+ if (typeof d.removedRoleFunc != 'undefined' && d.removedRoleFunc!=''){
+ for(var i=0;i<$scope.ociavailableRoleFunctions.length;i++){
+ if($scope.ociavailableRoleFunctions[i].name==d.removedRoleFunc)
+ $scope.ociavailableRoleFunctions[i].selected=false;
+ }
+ }
})
$scope.roleFnInit();
templateUrl: 'app/fusion/scripts/DS2-view-models/ds2-admin/modals/role-functions-modal.html',
controller: ModalInstanceCtrl,
sizeClass: 'modal-large',
- windowClass:"modal-docked",
resolve: {
items: function () {
var message = {
$scope.contactUsUrl;
$scope.getAccessUrl;
$scope.menuItems = [];
+ $scope.isAppCentralized;
$scope.showHeader = ($cookieStore.get("show_app_header") == undefined ? true : $cookies.get("show_app_header") );
$scope.userFirstName = res.firstName;
$scope.redirectUrl = res.portalUrl;
$scope.getAccessUrl = res.getAccessUrl;
+ $scope.isAppCentralized = res.isAppCentralized;
});
}
</div>
</div>
- <div class="b2b-modal-body" tabindex="0" aria-label="Modal header text content" role="region">
- <table class="striped">
- <thead>
- <tr>
- <th></th>
- <th>Role Function</th>
- </tr>
- </thead>
- <tbody type="body" ng-repeat="roleFunction in msg.availableRoleFunctions">
- <tr>
- <td>
- <label class="btn-switch-label" tabindex="0" role="option">
- <input ng-click="activateRoleConfirmPopUp(roleFunction.selected,roleFunction);" type="checkbox" b2b-switches ng-model="roleFunction.selected" size-class="modal-small modal-alert">
- </label>
- </td>
- <td>{{roleFunction.name}}</td>
- </tr>
- </tbody>
- </table>
+ <div class="b2b-modal-body" tabindex="0" aria-label="Modal header text content" role="region" >
+ <div id="role-double-popup">
+ <table class="striped" >
+ <thead>
+ <tr>
+ <th></th>
+ <th>Role Function</th>
+ </tr>
+ </thead>
+ <tbody type="body" ng-repeat="roleFunction in msg.availableRoleFunctions">
+ <tr>
+ <td>
+ <label class="btn-switch-label" tabindex="0" role="option">
+ <input ng-click="activateRoleConfirmPopUp(roleFunction.selected,roleFunction);" type="checkbox" b2b-switches ng-model="roleFunction.selected" size-class="modal-small modal-alert">
+ </label>
+ </td>
+ <td>{{roleFunction.name}}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
</div>
<div class="b2b-modal-footer">
#role-popup-footer{
height:100px;
}
+
+#role-double-popup{
+ max-height:300px;
+ overflow:auto;
+ display:block
+}
\ No newline at end of file
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
-# ECOMP Portal SDK Core
+# ONAP Portal SDK Core
## Overview
-This is the Maven project for the ECOMP Portal SDK Core library,
+This is the Maven project for the ONAP Portal SDK Core library,
which is distributed as epsdk-core-N.N.N.jar. This library
requires Hibernate and Spring, and provides many features
such as data access, session management, logging, on-boarding
### ONAP Distributions
-Version 1.3.0
-- [Portal-19] Renaming the Group Id in the POM file to org.onap.portal.sdk
+Version 1.4.0
+- PORTAL-19 Rename Java package base to org.onap
+- PORTAL-42 Use OParent as parent POM
+- PORTAL-72 Address Sonar Scan code issues
+- PORTAL-90 Use approved ONAP license text
+* Put new entries here *
+
+Version 1.3.0, 28 August 2017
+- Portal-19 Renaming the Group Id in the POM file to org.onap.portal.sdk
Version 1.1.0
-- [Portal-7] Improvements added as part of the rebasing process
+- Portal-7 Improvements added as part of the rebasing process
Version 1.0.0
- Initial release
<parent>
<groupId>org.onap.portal.sdk</groupId>
<artifactId>epsdk-project</artifactId>
- <version>1.3.0-SNAPSHOT</version>
+ <version>1.4.0-SNAPSHOT</version>
</parent>
<!-- GroupId is inherited from parent -->
<artifactId>epsdk-core</artifactId>
<!-- Version is inherited from parent -->
<packaging>jar</packaging>
- <name>ECOMP Portal SDK Core</name>
+ <name>ONAP Portal SDK Core</name>
<description>Core SDK library with controllers, interceptors, utilities, etc.</description>
<url>https://wiki.onap.org/display/DW/Portal</url>
<container.classpath>classpath:</container.classpath>
</systemPropertyVariables>
</configuration>
-
- </plugin>
-
- <!--
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>license-maven-plugin</artifactId>
- <version>1.10</version>
- <configuration>
- <encoding>UTF-8</encoding>
- <licenseName>my_license</licenseName>
- <licenseResolver>${project.baseUri}/license</licenseResolver>
- <inceptionYear>2017</inceptionYear>
- <organizationName>AT&T Intellectual Property</organizationName>
- <projectName>eCOMP Portal SDK</projectName>
- <addJavaLicenseAfterPackage>false</addJavaLicenseAfterPackage>
- <processStartTag>================================================================================</processStartTag>
- <sectionDelimiter>================================================================================</sectionDelimiter>
- <processEndTag>================================================================================</processEndTag>
- <roots>
- <root>src/main</root>
- <root>src/test</root>
- </roots>
- <excludes>
- <exclude>*.png</exclude>
- <exclude>*.drl</exclude>
- <exclude>*.gif</exclude>
- <exclude>*.jpeg</exclude>
- <exclude>*.jpg</exclude>
- <exclude>*.bmp</exclude>
- <exclude>*.ico</exclude>
- <exclude>*.svg</exclude>
- </excludes>
- </configuration>
- <executions>
- <execution>
- <id>first</id>
- <goals>
- <goal>update-file-header</goal>
- </goals>
- <phase>process-sources</phase>
- </execution>
- </executions>
</plugin>
- -->
</plugins>
</build>
</exclusion>
</exclusions>
</dependency>
-<!-- <dependency>
- <groupId>com.att.nsa</groupId>
- <artifactId>highlandParkCore</artifactId>
- <version>0.3.2</version>
- <exclusions>
- <exclusion>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- </exclusion>
- </exclusions>
- </dependency> -->
-
</dependencies>
</project>
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core;
+
+/**
+ * <p>
+ * Title: FusionObject
+ * </p>
+ *
+ * <p>
+ * Description: This interface is implemented by all top-level support classes
+ * of each package in FUSION. This allows all top-level support classes to have
+ * some commonality for easier maintenance.
+ * </p>
+ *
+ * <p>
+ * Copyright: Copyright (c) 2007
+ * </p>
+ *
+ * @version 1.1
+ */
+public interface FusionObject {
+
+ public class Parameters {
+ // HashMap parameters passed to the Service and Dao tiers
+ public static final String PARAM_USERID = "userId";
+ public static final String PARAM_HTTP_REQUEST = "request";
+ public static final String PARAM_FILTERS = "filters";
+ public static final String PARAM_CLIENT_DEVICE = "client_device";
+ // Request parameters passed in the Web tier
+ public static final String REQUEST_PARAM_DISPLAY_SUCCESS_MESSAGE = "display_success_message";
+ }
+
+ /**
+ * <p>
+ * Title: FusionObject.Utilities
+ * </p>
+ *
+ * <p>
+ * Description: Inner class that has some utility functions available for
+ * any class that implements it.
+ * </p>
+ *
+ * <p>
+ * Copyright: Copyright (c) 2007
+ * </p>
+ *
+ * @version 1.1
+ */
+ public class Utilities {
+ /**
+ * nvl - replaces a string value with an empty string if null.
+ *
+ * @param s
+ * String - the string value that needs to be checked
+ * @return String - returns the original string value if not null.
+ * Otherwise an empty string ("") is returned.
+ */
+ public static String nvl(String s) {
+ return (s == null) ? "" : s;
+ }
+
+ /**
+ * nvl - replaces a string value with a default value if null.
+ *
+ * @param s
+ * String - the string value that needs to be checked
+ * @param sDefault
+ * String - the default value
+ * @return String - returns the original string value if not null.
+ * Otherwise the default value is returned.
+ */
+ public static String nvl(String s, String sDefault) {
+ return nvl(s).equals("") ? sDefault : s;
+ }
+
+ /**
+ * Tests the specified string for nullity.
+ *
+ * @param a
+ * String to test for nullity.
+ * @return True if the specified string is null, empty or the 4-character
+ * sequence "null" (ignoring case); otherwise false.
+ */
+ public static boolean isNull(String a) {
+ if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null"))
+ return true;
+ else
+ return false;
+ }
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.auth;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.onap.portalsdk.core.command.LoginBean;
+import org.onap.portalsdk.core.domain.RoleFunction;
+import org.onap.portalsdk.core.menu.MenuProperties;
+import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
+import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
+import org.onap.portalsdk.core.service.LoginService;
+import org.onap.portalsdk.core.service.RoleService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.AppUtils;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.servlet.ModelAndView;
+import org.springframework.web.util.WebUtils;
+
+public abstract class LoginStrategy {
+
+ public static final String DEFAULT_SUCCESS_VIEW = "welcome";
+ public static final String DEFAULT_FAILURE_VIEW = "login";
+ private static final String JSESSIONID = "JSESSIONID";
+
+ public static final String EP_SERVICE = "EPService";
+ public static final String USER_ID = "UserId";
+ public static final String ERROR_MESSAGE_KEY = "error";
+
+ @Autowired
+ private LoginService loginService;
+
+ @Autowired
+ RoleService roleService;
+
+ public abstract ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception;
+
+ public abstract String getUserId(HttpServletRequest request) throws PortalAPIException;
+
+ public ModelAndView doExternalLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
+
+ invalidateExistingSession(request);
+
+ Map<String, String> model = new HashMap<String, String>();
+ LoginBean commandBean = new LoginBean();
+ String loginId = request.getParameter("loginId");
+ String password = request.getParameter("password");
+ commandBean.setLoginId(loginId);
+ commandBean.setLoginPwd(password);
+ HashMap additionalParamsMap = new HashMap();
+
+ // Get the client device type and pass it into LoginService for audit
+ // logging.
+ /**
+ * ClientDeviceType clientDevice = (ClientDeviceType)request.getAttribut
+ * (SystemProperties.getProperty(SystemProperties.CLIENT_DEVICE_ATTRIBUTE_NAME));
+ * additionalParamsMap.put(Parameters.PARAM_CLIENT_DEVICE,
+ * clientDevice);
+ **/
+ commandBean = loginService.findUser(commandBean,
+ (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), additionalParamsMap);
+ List<RoleFunction> roleFunctionList= roleService.getRoleFunctions(loginId);
+
+
+
+ if (commandBean.getUser() == null) {
+ String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage()
+ : "login.error.external.invalid";
+ model.put("error", loginErrorMessage);
+
+ String[] errorCodes = new String[1];
+ errorCodes[0] = loginErrorMessage;
+
+ return new ModelAndView("login_external", "model", model);
+
+ } else {
+ // store the currently logged in user's information in the session
+ UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
+ commandBean.getBusinessDirectMenu(),
+ SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_BACKDOOR), roleFunctionList);
+ initateSessionMgtHandler(request);
+
+ // user has been authenticated, now take them to the welcome page
+ // return new ModelAndView("redirect:/profile_search");
+ return new ModelAndView("redirect:welcome.htm");
+
+ }
+ }
+
+ protected void invalidateExistingSession(HttpServletRequest request){
+ request.getSession().invalidate();
+ }
+
+ protected String getJessionId(HttpServletRequest request) {
+ Cookie ep = WebUtils.getCookie(request, JSESSIONID);
+ if (ep == null) {
+ return request.getSession().getId();
+ }
+ return ep.getValue();
+
+ }
+
+ protected void initateSessionMgtHandler(HttpServletRequest request) {
+ String jSessionId = getJessionId(request);
+ PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
+ }
+
+ public LoginService getLoginService() {
+ return loginService;
+ }
+
+ public void setLoginService(LoginService loginService) {
+ this.loginService = loginService;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.command;
+
+import java.util.Set;
+
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.domain.support.FusionCommand;
+
+public class LoginBean extends FusionCommand {
+
+ private String loginId;
+ private String loginPwd;
+ private String hrid;
+ private String userid;
+ private String siteAccess;
+ private String loginErrorMessage;
+
+ private User user;
+ @SuppressWarnings("rawtypes")
+ private Set menu;
+ @SuppressWarnings("rawtypes")
+ private Set businessDirectMenu;
+
+ /**
+ * getLoginId
+ *
+ * @return String
+ */
+ public String getLoginId() {
+ return loginId;
+ }
+
+ /**
+ * getLoginPwd
+ *
+ * @return String
+ */
+ public String getLoginPwd() {
+ return loginPwd;
+ }
+
+ /**
+ * getMenu
+ *
+ * @return Set
+ */
+ @SuppressWarnings("rawtypes")
+ public Set getMenu() {
+ return menu;
+ }
+
+ /**
+ * getUser
+ *
+ * @return User
+ */
+ public User getUser() {
+ return user;
+ }
+
+ /**
+ * getHrid
+ *
+ * @return String
+ */
+ public String getHrid() {
+ return hrid;
+ }
+
+ /**
+ * getSiteAccess
+ *
+ * @return String
+ */
+ public String getSiteAccess() {
+ return siteAccess;
+ }
+
+ /**
+ * getBusinessDirectMenu
+ *
+ * @return Set
+ */
+ @SuppressWarnings("rawtypes")
+ public Set getBusinessDirectMenu() {
+ return businessDirectMenu;
+ }
+
+ /**
+ * getLoginErrorMessage
+ *
+ * @return String
+ */
+ public String getLoginErrorMessage() {
+ return loginErrorMessage;
+ }
+
+ /**
+ * setLoginId
+ *
+ * @param loginId String
+ */
+ public void setLoginId(String loginId) {
+ this.loginId = loginId;
+ }
+
+ /**
+ * setLoginPwd
+ *
+ * @param loginPwd String
+ */
+ public void setLoginPwd(String loginPwd) {
+ this.loginPwd = loginPwd;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public void setMenu(Set menu) {
+ this.menu = menu;
+ }
+
+ /**
+ * setUser
+ *
+ * @param user User
+ */
+ public void setUser(User user) {
+ this.user = user;
+ }
+
+ /**
+ * setHrid
+ *
+ * @param hrid String
+ */
+ public void setHrid(String hrid) {
+ this.hrid = hrid;
+ }
+
+ /**
+ * setSiteAccess
+ *
+ * @param siteAccess String
+ */
+ public void setSiteAccess(String siteAccess) {
+ this.siteAccess = siteAccess;
+ }
+
+ /**
+ * setBusinessDirectMenu
+ *
+ * @param businessDirectMenu Set
+ */
+ @SuppressWarnings("rawtypes")
+ public void setBusinessDirectMenu(Set businessDirectMenu) {
+ this.businessDirectMenu = businessDirectMenu;
+ }
+
+ /**
+ * setLoginErrorMessage
+ *
+ * @param loginErrorMessage String
+ */
+ public void setLoginErrorMessage(String loginErrorMessage) {
+ this.loginErrorMessage = loginErrorMessage;
+ }
+
+ public String getUserid() {
+ return userid;
+ }
+
+ public void setUserid(String userid) {
+ this.userid = userid;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.command;
+
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+
+@JsonSerialize
+public class PostDroolsBean {
+
+ private String droolsFile;
+ private String className;
+ private String selectedRules;
+
+ public String getDroolsFile() {
+ return droolsFile;
+ }
+ public void setDroolsFile(String droolsFile) {
+ this.droolsFile = droolsFile;
+ }
+ public String getSelectedRules() {
+ return selectedRules;
+ }
+ public void setSelectedRules(String selectedRules) {
+ this.selectedRules = selectedRules;
+ }
+ public String getClassName() {
+ return className;
+ }
+ public void setClassName(String className) {
+ this.className = className;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.command;
+
+import java.util.List;
+
+import org.onap.portalsdk.core.command.support.SearchBase;
+import org.onap.portalsdk.core.domain.User;
+
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+
+@JsonSerialize
+public class PostSearchBean extends SearchBase {
+
+ private User user = null;
+ private User userOrig = null;
+ private String[] selected;
+ private String[] postHrid;
+ private String[] postOrgUserId;
+ private String[] postFirstName;
+ private String[] postLastName;
+ private String[] postOrgCode;
+ private String[] postPhone;
+ private String[] postEmail;
+ private String[] postAddress1;
+ private String[] postAddress2;
+ private String[] postCity;
+ private String[] postState;
+ private String[] postZipCode;
+ private String[] postLocationClli;
+ private String[] postBusinessCountryCode;
+ private String[] postBusinessCountryName;
+ private String[] postDepartment;
+ private String[] postDepartmentName;
+ private String[] postBusinessUnit;
+ private String[] postBusinessUnitName;
+ private String[] postJobTitle;
+ private String[] postOrgManagerUserId;
+ private String[] postCommandChain;
+ private String[] postCompanyCode;
+ private String[] postCompany;
+ private String[] postCostCenter;
+ private String[] postSiloStatus;
+ private String[] postFinancialLocCode;
+
+
+ @SuppressWarnings("rawtypes")
+ public PostSearchBean() {
+ this(null);
+ } // PostSearchBean
+
+ @SuppressWarnings("rawtypes")
+ public PostSearchBean(List items) {
+ super(items);
+
+ user = new User();
+ userOrig = new User();
+
+ setSortBy1("");
+ setSortBy1Orig("");
+
+ //setSortByList(...);
+ } // PostSearchBean
+
+
+ public String getFirstName() { return user.getFirstName(); }
+ public String getLastName() { return user.getLastName(); }
+ public String getHrid() { return user.getHrid(); }
+ public String getOrgUserId() { return user.getOrgUserId(); }
+ public String getOrgCode() { return user.getOrgCode(); }
+ public String getEmail() { return user.getEmail(); }
+ public String getOrgManagerUserId() { return user.getOrgManagerUserId(); }
+
+ public String getFirstNameOrig() { return user.getFirstName(); }
+ public String getLastNameOrig() { return user.getLastName(); }
+ public String getHridOrig() { return user.getHrid(); }
+ public String getOrgUserIdOrig() { return user.getOrgUserId(); }
+ public String getOrgCodeOrig() { return user.getOrgCode(); }
+ public String getEmailOrig() { return user.getEmail(); }
+ public String getOrgManagerUserIdOrig() { return user.getOrgManagerUserId(); }
+
+
+ public User getUser() { return user; }
+
+ public String[] getPostEmail() {
+ return postEmail;
+ }
+
+ public String[] getPostFirstName() {
+ return postFirstName;
+ }
+
+ public String[] getPostHrid() {
+ return postHrid;
+ }
+
+ public String[] getPostLastName() {
+ return postLastName;
+ }
+
+ public String[] getPostOrgCode() {
+ return postOrgCode;
+ }
+
+ public String[] getPostPhone() {
+ return postPhone;
+ }
+
+ public String[] getPostOrgUserId() {
+ return postOrgUserId;
+ }
+
+ public String[] getSelected() {
+ return selected;
+ }
+
+ public String[] getPostAddress1() {
+ return postAddress1;
+ }
+
+ public String[] getPostBusinessCountryCode() {
+ return postBusinessCountryCode;
+ }
+
+ public String[] getPostCity() {
+ return postCity;
+ }
+
+ public String[] getPostCommandChain() {
+ return postCommandChain;
+ }
+
+ public String[] getPostCompany() {
+ return postCompany;
+ }
+
+ public String[] getPostCompanyCode() {
+ return postCompanyCode;
+ }
+
+ public String[] getPostDepartment() {
+ return postDepartment;
+ }
+
+ public String[] getPostDepartmentName() {
+ return postDepartmentName;
+ }
+
+ public String[] getPostBusinessCountryName() {
+ return postBusinessCountryName;
+ }
+
+ public String[] getPostJobTitle() {
+ return postJobTitle;
+ }
+
+ public String[] getPostLocationClli() {
+ return postLocationClli;
+ }
+
+ public String[] getPostOrgManagerUserId() {
+ return postOrgManagerUserId;
+ }
+
+ public String[] getPostState() {
+ return postState;
+ }
+
+ public String[] getPostZipCode() {
+ return postZipCode;
+ }
+
+ public void setFirstName(String value) { user.setFirstName(value); }
+ public void setLastName(String value) { user.setLastName(value); }
+ public void setHrid(String value) { user.setHrid(value); }
+ public void setOrgUserId(String value) { user.setOrgUserId(value); }
+ public void setOrgCode(String value) { user.setOrgCode(value); }
+ public void setEmail(String value) { user.setEmail(value); }
+ public void setOrgManagerUserId(String value) { user.setOrgManagerUserId(value); }
+
+ public void setFirstNameOrig(String value) { userOrig.setFirstName(value); }
+ public void setLastNameOrig(String value) { userOrig.setLastName(value); }
+ public void setHridOrig(String value) { userOrig.setHrid(value); }
+ public void setOrgUserIdOrig(String value) { userOrig.setOrgUserId(value); }
+ public void setOrgCodeOrig(String value) { userOrig.setOrgCode(value); }
+ public void setEmailOrig(String value) { userOrig.setEmail(value); }
+ public void setOrgManagerUserIdOrig(String value) { userOrig.setOrgManagerUserId(value); }
+
+ public void setUser(User value) { this.user = value; }
+
+ public void setPostEmail(String[] postEmail) {
+ this.postEmail = postEmail;
+ }
+
+ public void setPostFirstName(String[] postFirstName) {
+ this.postFirstName = postFirstName;
+ }
+
+ public void setPostHrid(String[] postHrid) {
+ this.postHrid = postHrid;
+ }
+
+ public void setPostLastName(String[] postLastName) {
+ this.postLastName = postLastName;
+ }
+
+ public void setPostOrgCode(String[] postOrgCode) {
+ this.postOrgCode = postOrgCode;
+ }
+
+ public void setPostPhone(String[] postPhone) {
+ this.postPhone = postPhone;
+ }
+
+ public void setPostOrgUserId(String[] postOrgUserId) {
+ this.postOrgUserId = postOrgUserId;
+ }
+
+ public void setSelected(String[] selected) {
+ this.selected = selected;
+ }
+
+ public void setPostAddress1(String[] postAddress1) {
+ this.postAddress1 = postAddress1;
+ }
+
+ public void setPostBusinessCountryCode(String[] postBusinessCountryCode) {
+ this.postBusinessCountryCode = postBusinessCountryCode;
+ }
+
+ public void setPostCity(String[] postCity) {
+ this.postCity = postCity;
+ }
+
+ public void setPostCommandChain(String[] postCommandChain) {
+ this.postCommandChain = postCommandChain;
+ }
+
+ public void setPostCompany(String[] postCompany) {
+ this.postCompany = postCompany;
+ }
+
+ public void setPostCompanyCode(String[] postCompanyCode) {
+ this.postCompanyCode = postCompanyCode;
+ }
+
+ public void setPostDepartment(String[] postDepartment) {
+ this.postDepartment = postDepartment;
+ }
+
+ public void setPostDepartmentName(String[] postDepartmentName) {
+ this.postDepartmentName = postDepartmentName;
+ }
+
+ public void setPostBusinessCountryName(String[] postBusinessCountryName) {
+ this.postBusinessCountryName = postBusinessCountryName;
+ }
+
+ public void setPostJobTitle(String[] postJobTitle) {
+ this.postJobTitle = postJobTitle;
+ }
+
+ public void setPostLocationClli(String[] postLocationClli) {
+ this.postLocationClli = postLocationClli;
+ }
+
+ public void setPostOrgManagerUserId(String[] postOrgManagerUserId) {
+ this.postOrgManagerUserId = postOrgManagerUserId;
+ }
+
+ public void setPostState(String[] postState) {
+ this.postState = postState;
+ }
+
+ public void setPostZipCode(String[] postZipCode) {
+ this.postZipCode = postZipCode;
+ }
+
+ public String[] getPostAddress2() {
+ return postAddress2;
+ }
+
+ public void setPostAddress2(String[] postAddress2) {
+ this.postAddress2 = postAddress2;
+ }
+
+ public User getUserOrig() {
+ return userOrig;
+ }
+
+ public void setUserOrig(User userOrig) {
+ this.userOrig = userOrig;
+ }
+
+ public String[] getPostBusinessUnit() {
+ return postBusinessUnit;
+ }
+
+ public void setPostBusinessUnit(String[] postBusinessUnit) {
+ this.postBusinessUnit = postBusinessUnit;
+ }
+
+ public String[] getPostBusinessUnitName() {
+ return postBusinessUnitName;
+ }
+
+ public void setPostBusinessUnitName(String[] postBusinessUnitName) {
+ this.postBusinessUnitName = postBusinessUnitName;
+ }
+
+ public String[] getPostCostCenter() {
+ return postCostCenter;
+ }
+
+ public void setPostCostCenter(String[] postCostCenter) {
+ this.postCostCenter = postCostCenter;
+ }
+
+ public String[] getPostSiloStatus() {
+ return postSiloStatus;
+ }
+
+ public void setPostSiloStatus(String[] postSiloStatus) {
+ this.postSiloStatus = postSiloStatus;
+ }
+
+ public String[] getPostFinancialLocCode() {
+ return postFinancialLocCode;
+ }
+
+ public void setPostFinancialLocCode(String[] postFinancialLocCode) {
+ this.postFinancialLocCode = postFinancialLocCode;
+ }
+
+ public void resetSearch() {
+ super.resetSearch();
+ setUser(new User());
+ } // resetSearch
+
+
+ public boolean isCriteriaUpdated() {
+ if(user==null&&userOrig==null)
+ return false;
+ else if(user==null||userOrig==null)
+ return true;
+ else
+ return (! (
+ Utilities.nvl(user.getFirstName()).equals(Utilities.nvl(userOrig.getFirstName()))&&
+ Utilities.nvl(user.getLastName()).equals(Utilities.nvl(userOrig.getLastName()))&&
+ //Utilities.nvl(user.getHrid()).equals(Utilities.nvl(userOrig.getHrid()))&&
+ Utilities.nvl(user.getOrgUserId()).equals(Utilities.nvl(userOrig.getOrgUserId()))&&
+ Utilities.nvl(user.getOrgCode()).equals(Utilities.nvl(userOrig.getOrgCode()))&&
+ Utilities.nvl(user.getEmail()).equals(Utilities.nvl(userOrig.getEmail()))&&
+ Utilities.nvl(user.getOrgManagerUserId()).equals(Utilities.nvl(userOrig.getOrgManagerUserId()))&&
+ true));
+ } // isCriteriaUpdated
+
+} // PostSearchBean
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.command;
+
+import org.onap.portalsdk.core.domain.User;
+
+public class UserRowBean extends User {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -2724597119083972190L;
+ private String sessionId;
+ private String lastAccess;
+ private String remaining;
+ private String loginTime;
+ private String LastLoginTime;
+
+
+ public String getLastAccess(){
+ return this.lastAccess;
+ }
+
+
+ public void setLastAccess(String lastAccess){
+ this.lastAccess = lastAccess;
+ }
+
+
+ public String getRemaining(){
+ return this.remaining;
+ }
+
+
+ public void setRemaining(String remaining){
+ this.remaining = remaining;
+ }
+
+
+ public String getSessionId() {
+ return sessionId;
+ }
+
+
+ public void setSessionId(String sessionId) {
+ this.sessionId = sessionId;
+ }
+
+
+ public String getLoginTime() {
+ return loginTime;
+ }
+
+
+ public void setLoginTime(String loginTime) {
+ this.loginTime = loginTime;
+ }
+
+
+ public String getLastLoginTime() {
+ return LastLoginTime;
+ }
+
+
+ public void setLastLoginTime(String lastLoginTime) {
+ LastLoginTime = lastLoginTime;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.command.support;
+
+import java.util.*;
+
+import org.onap.portalsdk.core.domain.support.FusionCommand;
+
+public abstract class SearchBase extends FusionCommand {
+
+ public static String SORT_BY_MODIFIER_DESC = "D";
+ public static String SORT_BY_MODIFIER_ASC = "A";
+ public static String SORT_BY_MODIFIER_DESC_IMAGE_NAME = "sort_desc.gif";
+ public static String SORT_BY_MODIFIER_ASC_IMAGE_NAME = "sort_asc.gif";
+
+
+ private String sortBy1 = null;
+ private String sortBy2 = null;
+ private String sortBy3 = null;
+
+ private String sortBy1Orig = null;
+ private String sortBy2Orig = null;
+ private String sortBy3Orig = null;
+
+ private String sortByModifier1 = null;
+ private String sortByModifier2 = null;
+ private String sortByModifier3 = null;
+
+ private String sortByModifier1Orig = null;
+ private String sortByModifier2Orig = null;
+ private String sortByModifier3Orig = null;
+
+ private String accessType = "WRITE"; //null;
+
+ private String submitAction = "";
+ private String masterId = "";
+ private String detailId = "";
+
+ private String showResult = "Y";
+
+ private SearchResult searchResult = null;
+ private boolean sortingUpdated;
+
+ @SuppressWarnings("rawtypes")
+ public SearchBase(List items) {
+ searchResult = (items == null) ? (new SearchResult()) : (new SearchResult(items));
+ } // SearchBase
+
+
+ public String getSortBy1() {
+ return sortBy1;
+ }
+
+ public String getSortBy2() {
+ return sortBy2;
+ }
+
+ public String getSortBy3() {
+ return sortBy3;
+ }
+
+ public String getSortBy1Orig() {
+ return sortBy1;
+ }
+
+ public String getSortBy2Orig() {
+ return sortBy2;
+ }
+
+ public String getSortBy3Orig() {
+ return sortBy3;
+ }
+
+ public String getAccessType() {
+ return accessType;
+ }
+
+ public String getSubmitAction() {
+ return submitAction;
+ }
+
+ public String getMasterId() {
+ return masterId;
+ }
+
+ public String getDetailId() {
+ return detailId;
+ }
+
+ public String getShowResult() {
+ return showResult;
+ }
+
+ //public ArrayList getSortByList() { return sortByList; }
+
+ public SearchResult getSearchResult() {
+ return searchResult;
+ }
+
+ public String getSortByModifier1() {
+ return sortByModifier1;
+ }
+
+ public String getSortByModifier1Orig() {
+ return sortByModifier1;
+ }
+
+ public String getSortByModifier2() {
+ return sortByModifier2;
+ }
+
+ public String getSortByModifier2Orig() {
+ return sortByModifier2;
+ }
+
+ public String getSortByModifier3() {
+ return sortByModifier3;
+ }
+
+ public String getSortByModifier3Orig() {
+ return sortByModifier3;
+ }
+
+ public int getPageNo() {
+ return (isCriteriaUpdated() || isSortingUpdated()) ? 0 : getSearchResult().getPageNo();
+ }
+
+ public int getPageSize() {
+ return getSearchResult().getPageSize();
+ }
+
+ public int getDataSize() {
+ return getSearchResult().getDataSize();
+ }
+
+ public int getNewDataSize() {
+ return isCriteriaUpdated() ? -1 : getDataSize();
+ }
+
+
+ public void setSortBy1(String sortBy1) {
+ this.sortBy1 = sortBy1;
+ }
+
+ public void setSortBy2(String sortBy2) {
+ this.sortBy2 = sortBy2;
+ }
+
+ public void setSortBy3(String sortBy3) {
+ this.sortBy3 = sortBy3;
+ }
+
+ public void setSortBy1Orig(String sortBy1Orig) {
+ this.sortBy1Orig = sortBy1Orig;
+ }
+
+ public void setSortBy2Orig(String sortBy2Orig) {
+ this.sortBy2Orig = sortBy2Orig;
+ }
+
+ public void setSortBy3Orig(String sortBy3Orig) {
+ this.sortBy3Orig = sortBy3Orig;
+ }
+
+ public void setAccessType(String accessType) {
+ this.accessType = accessType;
+ }
+
+ public void setSubmitAction(String submitAction) {
+ this.submitAction = submitAction;
+ }
+
+ public void setMasterId(String masterId) {
+ this.masterId = masterId;
+ }
+
+ public void setDetailId(String detailId) {
+ this.detailId = detailId;
+ }
+
+ public void setShowResult(String showResult) {
+ this.showResult = showResult;
+ }
+
+ public void setSearchResult(SearchResult searchResult) {
+ this.searchResult = searchResult;
+ }
+
+ public void setSortByModifier1(String sortByModifier1) {
+ this.sortByModifier1 = sortByModifier1;
+ }
+
+ public void setSortByModifier1Orig(String sortByModifier1Orig) {
+ this.sortByModifier1Orig = sortByModifier1Orig;
+ }
+
+ public void setSortByModifier2(String sortByModifier2) {
+ this.sortByModifier2 = sortByModifier2;
+ }
+
+ public void setSortByModifier2Orig(String sortByModifier2Orig) {
+ this.sortByModifier2Orig = sortByModifier2Orig;
+ }
+
+ public void setSortByModifier3(String sortByModifier3) {
+ this.sortByModifier3 = sortByModifier3;
+ }
+
+ public void setSortByModifier3Orig(String sortByModifier3Orig) {
+ this.sortByModifier3Orig = sortByModifier3Orig;
+ }
+
+ public void setSortingUpdated(boolean sortingUpdated) {
+ this.sortingUpdated = sortingUpdated;
+ }
+
+ public void setPageNo(int pageNo) {
+ getSearchResult().setPageNo(pageNo);
+ }
+
+ public void setPageSize(int pageSize) {
+ getSearchResult().setPageSize(pageSize);
+ }
+
+ public void setDataSize(int dataSize) {
+ getSearchResult().setDataSize(dataSize);
+ }
+
+
+ public void resetSearch() {
+ setSortBy1(null);
+ setSortBy2(null);
+ setSortBy3(null);
+ setSortByModifier1(SearchBase.SORT_BY_MODIFIER_ASC);
+ setSortByModifier2(SearchBase.SORT_BY_MODIFIER_ASC);
+ setSortByModifier3(SearchBase.SORT_BY_MODIFIER_ASC);
+ setPageNo(0);
+ setDataSize( -1);
+ } // resetSearch
+
+
+ public abstract boolean isCriteriaUpdated();
+
+ public boolean isSortingUpdated() {
+ return (!(Utilities.nvl(sortBy1).equals(Utilities.nvl(sortBy1Orig)) &&
+ Utilities.nvl(sortBy2).equals(Utilities.nvl(sortBy2Orig)) &&
+ Utilities.nvl(sortBy3).equals(Utilities.nvl(sortBy3Orig)) &&
+ Utilities.nvl(sortByModifier1).equals(Utilities.nvl(sortByModifier1Orig)) &&
+ Utilities.nvl(sortByModifier2).equals(Utilities.nvl(sortByModifier2Orig)) &&
+ Utilities.nvl(sortByModifier3).equals(Utilities.nvl(sortByModifier3Orig))));
+ } // isSortingUpdated
+
+} // SearchBase
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.command.support;
+
+import java.util.*;
+
+@SuppressWarnings("rawtypes")
+public class SearchResult extends ArrayList implements java.io.Serializable {
+ /**
+ *
+ */
+ private static final long serialVersionUID = -451947878984459011L;
+ private int pageNo = 0;
+ private int pageSize = 50;
+ private int dataSize = -1;
+
+ private String accessType = null;
+
+ //private boolean empty = true; // Overrides collections [isEmpty] with searchResult present/not present logic
+
+
+ public SearchResult() {}
+
+ @SuppressWarnings("unchecked")
+ public SearchResult(List items) {
+ super(items);
+ } // SearchResult
+
+ /*public SearchResult(boolean empty) {
+ this();
+ this.empty = empty;
+ } // SearchResult*/
+
+
+ public int getPageNo() { return pageNo; }
+ public int getPageSize() { return pageSize; }
+ public int getDataSize() { return dataSize; }
+
+ public int getSize() { return size(); } // for Struts bean property access
+ //public boolean isEmpty() { return empty; }
+
+ public String getAccessType() { return accessType; }
+
+ public void setPageNo(int pageNo) { this.pageNo=pageNo; }
+ public void setPageSize(int pageSize) { this.dataSize=pageSize; }
+ public void setDataSize(int dataSize) { this.dataSize=dataSize; }
+
+ public void setAccessType(String accessType) { this.accessType = accessType; }
+
+} // SearchResult
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.conf;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.sql.DataSource;
+
+import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
+import org.onap.portalsdk.core.interceptor.SessionTimeoutInterceptor;
+import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.onap.portalsdk.core.logging.format.AppMessagesEnum;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.menu.MenuBuilder;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.service.DataAccessServiceImpl;
+import org.onap.portalsdk.core.service.LocalAccessCondition;
+import org.onap.portalsdk.core.service.RestApiRequestBuilder;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.AppUtils;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.web.servlet.ViewResolver;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
+import org.springframework.web.servlet.view.InternalResourceViewResolver;
+import org.springframework.web.servlet.view.JstlView;
+import org.springframework.web.servlet.view.UrlBasedViewResolver;
+import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
+import org.springframework.web.servlet.view.tiles3.TilesView;
+
+import com.mchange.v2.c3p0.ComboPooledDataSource;
+
+/**
+ * Configures Spring features in the ONAP Portal SDK including request
+ * interceptors and view resolvers. Application should subclass and override
+ * methods as needed.
+ */
+public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, ApplicationContextAware {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppConfig.class);
+
+ private final List<String> tileDefinitions = new ArrayList<String>();
+ protected ApplicationContext appApplicationContext = null;
+
+ public AppConfig() {
+ // loads all default fields and marks logging
+ // has been started for each log file type.
+ initGlobalLocalContext();
+ }
+
+ /**
+ * Creates and returns a new instance of a secondary (order=2)
+ * {@link ViewResolver} that finds files by adding prefix "/WEB-INF/jsp/"
+ * and suffix ".jsp" to the base view name.
+ *
+ * @return New instance of {@link ViewResolver}.
+ */
+ @Bean
+ public ViewResolver viewResolver() {
+ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
+ viewResolver.setViewClass(JstlView.class);
+ viewResolver.setPrefix("/WEB-INF/jsp/");
+ viewResolver.setSuffix(".jsp");
+ viewResolver.setOrder(2);
+ return viewResolver;
+ }
+
+ /**
+ * Loads all the default logging fields into the global MDC context and
+ * marks each log file type that logging has been started.
+ */
+ private void initGlobalLocalContext() {
+ logger.init();
+ }
+
+ /*
+ * Any requests from the url pattern /static/**, Spring will look for the
+ * resources from the /static/ Same as <mvc:resources mapping="/static/**"
+ * location="/static/"/> in xml
+ */
+ @Override
+ public void addResourceHandlers(ResourceHandlerRegistry registry) {
+ // registry.addResourceHandler("/static/**").addResourceLocations("/static/");
+ registry.addResourceHandler("/**").addResourceLocations("/");
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link DataAccessService} class.
+ *
+ * @return New instance of {@link DataAccessService}.
+ */
+ @Bean
+ public DataAccessService dataAccessService() {
+ return new DataAccessServiceImpl();
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link SystemProperties} class.
+ *
+ * @return New instance of {@link SystemProperties}.
+ */
+ @Bean
+ public SystemProperties systemProperties() {
+ return new SystemProperties();
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link MenuBuilder} class.
+ *
+ * @return New instance of {@link MenuBuilder}.
+ */
+ @Bean
+ public MenuBuilder menuBuilder() {
+ return new MenuBuilder();
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link UserUtils} class.
+ *
+ * @return New instance of {@link UserUtils}.
+ */
+ @Bean
+ public UserUtils userUtil()
+ {
+ return new UserUtils();
+ }
+
+ /**
+ * Creates and returns a new instance of an {@link AppUtils} class.
+ *
+ * @return New instance of {@link AppUtils}.
+ */
+ @Bean
+ public AppUtils appUtils() {
+ return new AppUtils();
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link TilesConfigurer} class.
+ *
+ * @return New instance of {@link TilesConfigurer}.
+ */
+ @Bean
+ public TilesConfigurer tilesConfigurer() {
+ TilesConfigurer tilesConfigurer = new TilesConfigurer();
+ tilesConfigurer.setDefinitions(tileDefinitions());
+ tilesConfigurer.setCheckRefresh(true);
+ return tilesConfigurer;
+ }
+
+ /**
+ *
+ * Creates the Application Data Source.
+ *
+ * @return DataSource Object
+ * @throws Exception
+ * on failure to create data source object
+ */
+ @Bean
+ public DataSource dataSource() throws Exception {
+
+ systemProperties();
+
+ ComboPooledDataSource dataSource = new ComboPooledDataSource();
+ try {
+ dataSource.setDriverClass(SystemProperties.getProperty(SystemProperties.DB_DRIVER));
+ dataSource.setJdbcUrl(SystemProperties.getProperty(SystemProperties.DB_CONNECTIONURL));
+ dataSource.setUser(SystemProperties.getProperty(SystemProperties.DB_USERNAME));
+ String password = SystemProperties.getProperty(SystemProperties.DB_PASSWORD);
+ if (SystemProperties.containsProperty(SystemProperties.DB_ENCRYPT_FLAG)) {
+ String encryptFlag = SystemProperties.getProperty(SystemProperties.DB_ENCRYPT_FLAG);
+ if (encryptFlag != null && encryptFlag.equalsIgnoreCase("true")) {
+ password = CipherUtil.decrypt(password);
+ }
+ }
+ dataSource.setPassword(password);
+ dataSource
+ .setMinPoolSize(Integer.parseInt(SystemProperties.getProperty(SystemProperties.DB_MIN_POOL_SIZE)));
+ dataSource
+ .setMaxPoolSize(Integer.parseInt(SystemProperties.getProperty(SystemProperties.DB_MAX_POOL_SIZE)));
+ dataSource.setIdleConnectionTestPeriod(
+ Integer.parseInt(SystemProperties.getProperty(SystemProperties.IDLE_CONNECTION_TEST_PERIOD)));
+ dataSource.setTestConnectionOnCheckout(getConnectionOnCheckout());
+ dataSource.setPreferredTestQuery(getPreferredTestQuery());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Error initializing database, verify database settings in properties file: "
+ + UserUtils.getStackTrace(e),
+ AlarmSeverityEnum.CRITICAL);
+ logger.error(EELFLoggerDelegate.debugLogger,
+ "Error initializing database, verify database settings in properties file: "
+ + UserUtils.getStackTrace(e),
+ AlarmSeverityEnum.CRITICAL);
+ // Raise an alarm that opening a connection to the database failed.
+ logger.logEcompError(AppMessagesEnum.BeDaoSystemError);
+ throw e;
+ }
+ return dataSource;
+ }
+
+ /**
+ * Gets the value of the property
+ * {@link SystemProperties#PREFERRED_TEST_QUERY}; defaults to "Select 1" if
+ * the property is not defined.
+ *
+ * @return String value that is a SQL query
+ */
+ private String getPreferredTestQuery() {
+ // Use simple default
+ String preferredTestQueryStr = "SELECT 1";
+ if (SystemProperties.containsProperty(SystemProperties.PREFERRED_TEST_QUERY)) {
+ preferredTestQueryStr = SystemProperties.getProperty(SystemProperties.PREFERRED_TEST_QUERY);
+ logger.debug(EELFLoggerDelegate.debugLogger, "getPreferredTestQuery: property key {} value is {}",
+ SystemProperties.PREFERRED_TEST_QUERY, preferredTestQueryStr);
+ } else {
+ logger.info(EELFLoggerDelegate.errorLogger,
+ "getPreferredTestQuery: property key {} not found, using default value {}",
+ SystemProperties.PREFERRED_TEST_QUERY, preferredTestQueryStr);
+ }
+ return preferredTestQueryStr;
+ }
+
+ /**
+ * Gets the value of the property
+ * {@link SystemProperties#TEST_CONNECTION_ON_CHECKOUT}; defaults to true if
+ * the property is not defined.
+ *
+ * @return Boolean value
+ */
+ private Boolean getConnectionOnCheckout() {
+ // Default to true, always test connection
+ boolean testConnectionOnCheckout = true;
+ if (SystemProperties.containsProperty(SystemProperties.TEST_CONNECTION_ON_CHECKOUT)) {
+ testConnectionOnCheckout = Boolean
+ .valueOf(SystemProperties.getProperty(SystemProperties.TEST_CONNECTION_ON_CHECKOUT));
+ logger.debug(EELFLoggerDelegate.debugLogger, "getConnectionOnCheckout: property key {} value is {}",
+ SystemProperties.TEST_CONNECTION_ON_CHECKOUT, testConnectionOnCheckout);
+ } else {
+ logger.info(EELFLoggerDelegate.errorLogger,
+ "getConnectionOnCheckout: property key {} not found, using default value {}",
+ SystemProperties.TEST_CONNECTION_ON_CHECKOUT, testConnectionOnCheckout);
+ }
+ return testConnectionOnCheckout;
+ }
+
+ /*
+ * TODO: Check whether it is appropriate to extend the list of tile
+ * definitions at every invocation.
+ */
+ protected String[] tileDefinitions() {
+ tileDefinitions.add("/WEB-INF/fusion/defs/definitions.xml");
+ tileDefinitions.addAll(addTileDefinitions());
+
+ return tileDefinitions.toArray(new String[0]);
+ }
+
+ /**
+ * Creates and returns a new empty list. This method should be overridden by
+ * child classes.
+ *
+ * @return An empty list.
+ */
+ public List<String> addTileDefinitions() {
+ return new ArrayList<String>();
+ }
+
+ /**
+ * Creates and returns a new instance of a primary (order=1)
+ * {@link UrlBasedViewResolver} that finds files using the contents of
+ * definitions.xml files.
+ *
+ * @return New instance of {@link UrlBasedViewResolver}
+ */
+ @Bean
+ public UrlBasedViewResolver tileViewResolver() {
+ UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
+ viewResolver.setViewClass(TilesView.class);
+ viewResolver.setOrder(1);
+ return viewResolver;
+ }
+
+ /**
+ * Adds new instances of the following interceptors to the specified
+ * interceptor registry: {@link SessionTimeoutInterceptor},
+ * {@link ResourceInterceptor}
+ */
+ @Override
+ public void addInterceptors(InterceptorRegistry registry) {
+ registry.addInterceptor(new SessionTimeoutInterceptor())
+ .excludePathPatterns(getExcludeUrlPathsForSessionTimeout());
+ registry.addInterceptor(resourceInterceptor());
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link ResourceInterceptor}.
+ *
+ * @return New instance of {@link ResourceInterceptor}
+ */
+ @Bean
+ public ResourceInterceptor resourceInterceptor() {
+ return new ResourceInterceptor();
+ }
+
+ private String[] excludeUrlPathsForSessionTimeout = {};
+
+ /**
+ * Gets the array of Strings that are paths excluded for session timeout.
+ *
+ * @return Array of String
+ */
+ public String[] getExcludeUrlPathsForSessionTimeout() {
+ return excludeUrlPathsForSessionTimeout;
+ }
+
+ /**
+ * Sets the array of Strings that are paths excluded for session timeout.
+ *
+ * @param excludeUrlPathsForSessionTimeout
+ * Paths to exclude
+ */
+ public void setExcludeUrlPathsForSessionTimeout(final String... excludeUrlPathsForSessionTimeout) {
+ this.excludeUrlPathsForSessionTimeout = excludeUrlPathsForSessionTimeout;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.springframework.context.ApplicationContextAware#setApplicationContext
+ * (org.springframework.context.ApplicationContext)
+ */
+ @Override
+ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
+ appApplicationContext = applicationContext;
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.conf;
+
+import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.core.env.ConfigurableEnvironment;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
+
+public abstract class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppInitializer.class);
+
+ private final String activeProfile = "src";
+
+ @Override
+ protected WebApplicationContext createServletApplicationContext() {
+ WebApplicationContext context = super.createServletApplicationContext();
+
+ try {
+
+ ((ConfigurableEnvironment) context.getEnvironment()).setActiveProfiles(activeProfile);
+ } catch (Exception e) {
+
+ logger.error(EELFLoggerDelegate.errorLogger, "Unable to set the active profile" + e.getMessage(),AlarmSeverityEnum.MAJOR);
+ throw e;
+
+ }
+
+ return context;
+ }
+
+ @Override
+ protected Class<?>[] getRootConfigClasses() {
+ return null;
+ }
+
+ @Override
+ protected Class<?>[] getServletConfigClasses() {
+
+ return new Class[] { AppConfig.class };
+ }
+
+ /*
+ * URL request will direct to the Spring dispatcher for processing
+ */
+ @Override
+ protected String[] getServletMappings() {
+ return new String[] { "/" };
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.conf;
+
+import java.util.List;
+
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.springframework.web.servlet.ViewResolver;
+import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
+
+public interface Configurable {
+
+ public ViewResolver viewResolver();
+
+ public void addResourceHandlers(ResourceHandlerRegistry registry) ;
+
+ public DataAccessService dataAccessService();
+
+ public List<String> addTileDefinitions();
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.conf;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.sql.DataSource;
+
+import org.hibernate.SessionFactory;
+import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.orm.hibernate4.HibernateTransactionManager;
+import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+import com.mchange.v2.c3p0.ComboPooledDataSource;
+
+@Configuration
+@EnableTransactionManagement
+public class HibernateConfiguration {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HibernateConfiguration.class);
+
+ @Autowired
+ private HibernateMappingLocatable hbMappingLocatable;
+
+ @Autowired
+ private DataSource dataSource;
+
+ @Bean
+ public LocalSessionFactoryBean sessionFactory() {
+ LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
+ sessionFactory.setDataSource(dataSource);
+ sessionFactory.setPackagesToScan(hbMappingLocatable.getPackagesToScan());
+ sessionFactory.setHibernateProperties(getHibernateProperties());
+ sessionFactory.setMappingLocations(hbMappingLocatable.getMappingLocations());
+ return sessionFactory;
+ }
+
+ /**
+ * Builds a properties object with Hibernate properties in te system.properties file.
+ *
+ * @return Properties object
+ */
+ private Properties getHibernateProperties() {
+ Properties properties = new Properties();
+ properties.put("hibernate.dialect", SystemProperties.getProperty(SystemProperties.HB_DIALECT));
+ properties.put("hibernate.show_sql", SystemProperties.getProperty(SystemProperties.HB_SHOW_SQL));
+ return properties;
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Bean
+ public Map dataSourceMap() throws Exception {
+ Connection conn = null;
+ Statement stmt = null;
+ ResultSet rs = null;
+ Map<String, ComboPooledDataSource> dataSourceMap = new HashMap<String, ComboPooledDataSource>();
+ try {
+ conn = dataSource.getConnection();
+ stmt = conn.createStatement();
+ String sql = "SELECT schema_id,datasource_type,connection_url,user_name,password,driver_class,min_pool_size,max_pool_size,idle_connection_test_period FROM schema_info";
+ rs = stmt.executeQuery(sql);
+ while (rs.next()) {
+ ComboPooledDataSource dataSource = new ComboPooledDataSource();
+ dataSource.setDriverClass(rs.getString("driver_class"));
+ dataSource.setJdbcUrl(rs.getString("connection_url"));
+ dataSource.setUser(rs.getString("user_name"));
+ dataSource.setPassword(rs.getString("password"));
+ dataSource.setMinPoolSize(rs.getInt("min_pool_size"));
+ dataSource.setMaxPoolSize(rs.getInt("max_pool_size"));
+ dataSource.setIdleConnectionTestPeriod(rs.getInt("idle_connection_test_period"));
+ dataSourceMap.put(rs.getString("schema_id"), dataSource);
+ }
+ rs.close();
+ rs = null;
+ stmt.close();
+ stmt = null;
+ conn.close();
+ conn = null;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Error initializing database, verify database settings in properties file: " + e.getMessage(),
+ AlarmSeverityEnum.CRITICAL);
+ e.printStackTrace();
+ dataSourceMap = null;
+ throw e;
+ } finally {
+ try {
+ if (rs != null)
+ rs.close();
+ if (stmt != null)
+ stmt.close();
+ if (conn != null)
+ conn.close();
+ } catch (SQLException se2) {
+ }
+ try {
+ if (conn != null)
+ conn.close();
+ } catch (SQLException se) {
+ se.printStackTrace();
+ }
+ }
+
+ return dataSourceMap;
+ }
+
+ @Bean
+ @Autowired
+ public HibernateTransactionManager transactionManager(SessionFactory s) {
+ HibernateTransactionManager txManager = new HibernateTransactionManager();
+ txManager.setSessionFactory(s);
+ return txManager;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.conf;
+
+import org.springframework.core.io.Resource;
+
+/**
+ * Defines methods used by developers to supply Hibernate configuration.
+ */
+public interface HibernateMappingLocatable {
+
+ /**
+ * Gets Hibernate mapping locations.
+ *
+ * @return Array of Resource objects (usually ClassPathResource that's a
+ * file) which contain Hibernate mapping information.
+ */
+ public Resource [] getMappingLocations();
+
+ /**
+ * Gets package names.
+ *
+ * @return Array of Java package names to scan for classes with Hibernate annotations.
+ */
+ public String [] getPackagesToScan();
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.controller;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalsdk.core.domain.MenuData;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.interfaces.SecurityInterface;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.menu.MenuBuilder;
+import org.onap.portalsdk.core.service.AppService;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.service.FnMenuService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.ModelAttribute;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+public abstract class FusionBaseController implements SecurityInterface{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FusionBaseController.class);
+
+ @Override
+ public boolean isAccessible() {
+ return true;
+ }
+
+ public boolean isRESTfulCall(){
+ return true;
+ }
+ @Autowired
+ private FnMenuService fnMenuService;
+
+ @Autowired
+ private MenuBuilder menuBuilder;
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @Autowired
+ AppService appService;
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @ModelAttribute("menu")
+ public Map<String, Object> getMenu(HttpServletRequest request) {
+ HttpSession session = null;
+ Map<String, Object> model = new HashMap<String, Object>();
+ try {
+ try {
+ String appName = appService.getDefaultAppName();
+ if (appName==null || appName=="") {
+ appName = SystemProperties.SDK_NAME;
+ }
+ logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, appName);
+ } catch (Exception e) {
+ }
+
+ session = request.getSession();
+ User user = UserUtils.getUserSession(request);
+ if(session!=null && user!=null){
+ Set<MenuData> menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
+ if(menuResult==null){
+ Set appMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME),dataAccessService);
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME), MenuBuilder.filterMenu(appMenu, request));
+ menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
+ }
+ model = setMenu(menuResult);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
+ }
+ return model;
+ }
+
+ public Map<String, Object> setMenu(Set<MenuData> menuResult) throws Exception{
+ ObjectMapper mapper = new ObjectMapper();
+ List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>();;
+ List<MenuData> parentList = new ArrayList<MenuData>();;
+ Map<String, Object> model = new HashMap<String, Object>();
+ try{
+ fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
+ }
+ model.put("childItemList", mapper.writeValueAsString(childItemList));
+ model.put("parentList", mapper.writeValueAsString(parentList));
+ return model;
+ }
+
+ public MenuBuilder getMenuBuilder() {
+ return menuBuilder;
+ }
+
+ public void setMenuBuilder(MenuBuilder menuBuilder) {
+ this.menuBuilder = menuBuilder;
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.controller;
+
+public class RestrictedBaseController extends FusionBaseController{
+
+ protected String viewName;
+ private String exceptionView;
+ @Override
+ public boolean isAccessible() {
+ return false;
+ }
+ @Override
+ public boolean isRESTfulCall(){
+ return false;
+ }
+ protected String getViewName() {
+ return viewName;
+ }
+ protected void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+ public String getExceptionView() {
+ return (exceptionView == null) ? "runtime_error_handler" : exceptionView;
+ }
+
+ public void setExceptionView(String exceptionView) {
+ this.exceptionView = exceptionView;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.controller;
+
+public class RestrictedRESTfulBaseController extends FusionBaseController{
+
+ protected String viewName;
+ private String exceptionView;
+ @Override
+ public boolean isAccessible() {
+ return false;
+ }
+ @Override
+ public boolean isRESTfulCall(){
+ return true;
+ }
+ protected String getViewName() {
+ return viewName;
+ }
+ protected void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+ public String getExceptionView() {
+ return (exceptionView == null) ? "runtime_error_handler" : exceptionView;
+ }
+
+ public void setExceptionView(String exceptionView) {
+ this.exceptionView = exceptionView;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.controller;
+
+public class UnRestrictedBaseController extends FusionBaseController{
+ protected String viewName;
+
+ @Override
+ public boolean isAccessible() {
+ return true;
+ }
+ @Override
+ public boolean isRESTfulCall(){
+ return false;
+ }
+ protected String getViewName() {
+ return viewName;
+ }
+
+ protected void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.dao;
+import java.io.Serializable;
+import java.lang.reflect.ParameterizedType;
+
+import org.hibernate.Criteria;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+public abstract class AbstractDao<PK extends Serializable, T> {
+
+ private final Class<T> persistentClass;
+
+ @SuppressWarnings("unchecked")
+ public AbstractDao(){
+ this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
+ }
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ protected Session getSession(){
+ return sessionFactory.getCurrentSession();
+ }
+
+ @SuppressWarnings("unchecked")
+ public T getByKey(PK key) {
+ return (T) getSession().get(persistentClass, key);
+ }
+
+ public void persist(T entity) {
+ getSession().persist(entity);
+ }
+
+ public void delete(T entity) {
+ getSession().delete(entity);
+ }
+
+ protected Criteria createEntityCriteria(){
+ return getSession().createCriteria(persistentClass);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.dao;
+
+import java.util.List;
+
+import org.onap.portalsdk.core.domain.Profile;
+
+public interface ProfileDao {
+ List<Profile> findAll();
+ Profile getProfile(int id);
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.dao;
+
+import java.util.List;
+
+import org.hibernate.Criteria;
+import org.hibernate.criterion.Restrictions;
+import org.onap.portalsdk.core.dao.AbstractDao;
+import org.onap.portalsdk.core.domain.Profile;
+import org.springframework.stereotype.Repository;
+
+@Repository("profileDao")
+public class ProfileDaoImpl extends AbstractDao<Integer, Profile> implements ProfileDao{
+
+
+ public List<Profile> findAll() {
+ Criteria crit = getSession().createCriteria(Profile.class);
+ @SuppressWarnings("unchecked")
+ List<Profile> p = crit.list();
+
+ return p;
+ }
+
+
+ public Profile getProfile(int id) {
+ Criteria crit = getSession().createCriteria(Profile.class);
+ crit.add(Restrictions.eq("id", id));
+ Profile profile = (Profile) crit.uniqueResult();
+
+ return profile;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.dao.hibernate;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.hibernate.Criteria;
+import org.hibernate.FetchMode;
+import org.hibernate.Query;
+import org.hibernate.SQLQuery;
+import org.hibernate.Session;
+import org.hibernate.criterion.Criterion;
+import org.hibernate.criterion.Order;
+import org.hibernate.criterion.ProjectionList;
+import org.hibernate.type.LongType;
+import org.onap.portalsdk.core.dao.support.FusionDao;
+import org.onap.portalsdk.core.domain.Lookup;
+import org.onap.portalsdk.core.domain.support.DomainVo;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.util.SystemProperties;
+
+public abstract class ModelOperationsCommon extends FusionDao {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ModelOperationsCommon.class);
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ public List _getList(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex, String orderBy) {
+ List list = null;
+ String className = domainClass.getName();
+
+ Session session = getSessionFactory().getCurrentSession();
+
+ logger.info(EELFLoggerDelegate.debugLogger, "Getting " + className.toLowerCase() + " records"
+ + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "")
+ + "...");
+
+
+ if (filterClause != null && filterClause.length() > 0) {
+ logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause);
+
+ }
+
+ list = session.createQuery("from " + className + Utilities.nvl(filterClause, "")
+ + ((orderBy != null) ? " order by " + orderBy : "")).list();
+ list = (fromIndex != null) ? list.subList(fromIndex.intValue() - 1, toIndex.intValue()) : list;
+
+ if (orderBy == null && list != null) {
+ Collections.sort(list);
+ }
+
+ return list;
+ }
+
+ public List<?> _getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
+ List<Order> orderByList) {
+ return _getList(domainClass, projectionsList, restrictionsList, orderByList, null);
+ }
+
+ public List<?> _getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
+ List<Order> orderByList, HashMap<String, FetchMode> fetchModeMap) {
+
+ Session session = getSessionFactory().getCurrentSession();
+
+ Criteria criteria = session.createCriteria(domainClass);
+
+ if (projectionsList != null) {
+ criteria.setProjection(projectionsList);
+ }
+
+ if (restrictionsList != null && !restrictionsList.isEmpty()) {
+ for (Criterion criterion : restrictionsList)
+ criteria.add(criterion);
+ }
+
+ if (orderByList != null && !orderByList.isEmpty()) {
+ for (Order order : orderByList)
+ criteria.addOrder(order);
+ }
+
+ if (fetchModeMap != null) {
+ Iterator<String> itr = fetchModeMap.keySet().iterator();
+ String key = null;
+ while (itr.hasNext()) {
+ key = itr.next();
+ criteria.setFetchMode(key, fetchModeMap.get(key));
+ }
+
+ }
+ return criteria.list();
+ }
+
+ @SuppressWarnings("rawtypes")
+ public DomainVo _get(Class domainClass, Serializable id) {
+ DomainVo vo = null;
+
+ Session session = getSessionFactory().getCurrentSession();
+
+ logger.info(EELFLoggerDelegate.debugLogger, "Getting " + domainClass.getName() + " record for id - " + id.toString());
+
+
+ vo = (DomainVo) session.get(domainClass, id);
+
+ if (vo == null) {
+ try {
+ vo = (DomainVo) domainClass.newInstance();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed while instantiating a class of " + domainClass.getName() + e.getMessage());
+
+ }
+ }
+
+ return vo;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public List _getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy,
+ HashMap additionalParams) {
+ logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list...");
+
+ List list = null;
+ String dbOrderByCol = dbOrderBy;
+
+ Session session = getSessionFactory().getCurrentSession();
+
+ // default the orderBy if null;
+ if (Utilities.nvl(dbOrderBy).length() == 0) {
+ dbOrderByCol = dbLabelCol;
+ dbOrderBy = dbLabelCol;
+ } else {
+ if (dbOrderBy.lastIndexOf(" ") > -1) {
+ dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" "));
+ }
+ }
+
+ StringBuffer sql = new StringBuffer();
+
+ sql.append("select distinct ").append(dbLabelCol).append(" as lab, ").append(dbValueCol).append(" as val, ")
+ .append(dbOrderByCol).append(" as sortOrder ").append("from ").append(dbTable).append(" ")
+ .append((Utilities.nvl(dbFilter).length() == 0) ? "" : (" where " + dbFilter)).append(" order by ")
+ .append(dbOrderBy);
+
+ try {
+ list = session.createSQLQuery(sql.toString()).addEntity(Lookup.class).list();
+ } catch (Exception e) {
+ list = null;
+ logger.info(EELFLoggerDelegate.debugLogger, "The results for the lookup list query [" + sql + "] were empty.");
+ }
+
+ return list;
+ } // getLookupList
+
+ /* This method is used to execute SQL queries */
+ @SuppressWarnings("rawtypes")
+ protected final List _executeSQLQuery(String sql, Class domainClass) {
+ return _executeSQLQuery(sql, domainClass, null, null);
+ }
+
+ /* This method is used to execute SQL queries with paging */
+ @SuppressWarnings("rawtypes")
+ protected final List _executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex) {
+ Session session = getSessionFactory().getCurrentSession();
+
+ SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass);
+
+ if (fromIndex != null && toIndex != null) {
+ query.setFirstResult(fromIndex.intValue());
+ int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
+ query.setMaxResults(pageSize);
+ }
+
+ return query.list();
+ }
+
+ /* This method is used to execute HQL queries */
+ @SuppressWarnings("rawtypes")
+ protected final List _executeQuery(String sql) {
+ return _executeQuery(sql, null, null);
+ }
+
+ /* This method is used to execute HQL queries with paging */
+ @SuppressWarnings("rawtypes")
+ protected final List _executeQuery(String sql, Integer fromIndex, Integer toIndex) {
+ Session session = getSessionFactory().getCurrentSession();
+
+ Query query = session.createQuery(sql);
+
+ if (fromIndex != null && toIndex != null) {
+ query.setFirstResult(fromIndex.intValue());
+ int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
+ query.setMaxResults(pageSize);
+ }
+
+ return query.list();
+ }
+
+ /*
+ * This method can be used to execute both HQL or SQL named queries. The
+ * distinction will come in the hbm.xml mapping file defining the named
+ * query. Named HQL queries use the <query> tag while named SQL queries use
+ * the <sql-query> tag.
+ */
+ @SuppressWarnings("rawtypes")
+ protected final List _executeNamedQuery(String queryName, Map params) {
+ return _executeNamedQuery(queryName, params, null, null);
+ }
+
+ /*
+ * This method can be used to execute both HQL or SQL named queries with
+ * paging. The distinction will come in the hbm.xml mapping file defining
+ * the named query. Named HQL queries use the <query> tag while named SQL
+ * queries use the <sql-query> tag.
+ */
+ @SuppressWarnings("rawtypes")
+ protected final List _executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex) {
+ Session session = getSessionFactory().getCurrentSession();
+ Query query = session.getNamedQuery(queryName);
+ bindQueryParameters(query, params);
+ if (fromIndex != null && toIndex != null) {
+ query.setFirstResult(fromIndex.intValue());
+ int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
+ query.setMaxResults(pageSize);
+ }
+ return query.list();
+ }
+
+ // RAPTOR ZK
+ /*
+ * This method can be used to execute both HQL or SQL named queries with
+ * paging. The distinction will come in the hbm.xml mapping file defining
+ * the named query. Named HQL queries use the <query> tag while named SQL
+ * queries use the <sql-query> tag.
+ */
+ @SuppressWarnings("rawtypes")
+ protected final List _executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params) {
+ Session session = getSessionFactory().getCurrentSession();
+ Query query = session.getNamedQuery(queryName);
+ String queryStr = query.getQueryString();
+ StringBuffer modifiedSql = new StringBuffer(" select count(*) as countRows from (" + queryStr + " ) al ");
+ if (whereClause != null && whereClause.length() > 0)
+ modifiedSql.append("where " + whereClause);
+ // SQLQuery sqlQuery = session.createSQLQuery(" select count(*) as
+ // {reportSearch.countRows} from ("+ modifiedSql.toString()+")");
+ SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString());
+ bindQueryParameters(sqlQuery, params);
+ sqlQuery.addScalar("countRows", LongType.INSTANCE);
+ // sqlQuery.addEntity("reportSearch", entity);
+ // sqlQuery.setResultTransformer(new
+ // AliasToBeanResultTransformer(SearchCount.class));
+ return sqlQuery.list();
+
+ }
+
+ /*
+ * This method can be used to execute both HQL or SQL named queries with
+ * paging. The distinction will come in the hbm.xml mapping file defining
+ * the named query. Named HQL queries use the <query> tag while named SQL
+ * queries use the <sql-query> tag. It is modified to test ZK filter.
+ */
+ @SuppressWarnings("rawtypes")
+ protected final List _executeNamedQuery(Class entity, String queryName, String whereClause, Map params,
+ Integer fromIndex, Integer toIndex) {
+ Session session = getSessionFactory().getCurrentSession();
+ Query query = session.getNamedQuery(queryName);
+ bindQueryParameters(query, params);
+ String queryStr = query.getQueryString();
+ StringBuffer modifiedSql = new StringBuffer(" select * from (" + queryStr + " ) al ");
+ if (whereClause != null && whereClause.length() > 0)
+ modifiedSql.append("where " + whereClause);
+
+ SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString());
+ bindQueryParameters(sqlQuery, params);
+ sqlQuery.addEntity("reportSearch", entity);
+
+ if (fromIndex != null && toIndex != null) {
+ sqlQuery.setFirstResult(fromIndex.intValue());
+ int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
+ sqlQuery.setMaxResults(pageSize);
+ }
+ return sqlQuery.list();
+ }
+
+ /*
+ * This method can be used to execute both HQL or SQL named queries with
+ * paging. The distinction will come in the hbm.xml mapping file defining
+ * the named query. Named HQL queries use the <query> tag while named SQL
+ * queries use the <sql-query> tag.
+ */
+ @SuppressWarnings("rawtypes")
+ protected final List _executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy,
+ boolean asc, Integer fromIndex, Integer toIndex) {
+ Session session = getSessionFactory().getCurrentSession();
+ Query query = session.getNamedQuery(queryName);
+ bindQueryParameters(query, params);
+ String queryStr = query.getQueryString();
+ queryStr = String.format(queryStr, _orderBy, asc ? "ASC" : "DESC");
+ SQLQuery sqlQuery = session.createSQLQuery(queryStr);
+ bindQueryParameters(sqlQuery, params);
+ sqlQuery.addEntity("reportSearch", entity);
+ if (fromIndex != null && toIndex != null) {
+ sqlQuery.setFirstResult(fromIndex.intValue());
+ int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
+ sqlQuery.setMaxResults(pageSize);
+ }
+ return sqlQuery.list();
+ }
+
+ // Where Clause
+ @SuppressWarnings("rawtypes")
+ protected final List _executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params,
+ String _orderBy, boolean asc, Integer fromIndex, Integer toIndex) {
+ Session session = getSessionFactory().getCurrentSession();
+ Query query = session.getNamedQuery(queryName);
+ bindQueryParameters(query, params);
+ String queryStr = query.getQueryString();
+ queryStr = String.format(queryStr, _orderBy, asc ? "ASC" : "DESC");
+ // StringBuffer modifiedSql = new StringBuffer(queryStr );
+ StringBuffer modifiedSql = new StringBuffer(" select * from (" + queryStr + " ) al ");
+ // modifiedSql.insert(queryStr.lastIndexOf("order by"), " " +
+ // whereClause + " ");
+ if (whereClause != null && whereClause.length() > 0)
+ modifiedSql.append("where " + whereClause);
+ SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString());
+ bindQueryParameters(sqlQuery, params);
+ sqlQuery.addEntity("reportSearch", entity);
+ if (fromIndex != null && toIndex != null) {
+ sqlQuery.setFirstResult(fromIndex.intValue());
+ int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
+ sqlQuery.setMaxResults(pageSize);
+ }
+ return sqlQuery.list();
+ }
+
+ // RAPTOR ZK END
+
+ /* Processes custom Insert/Update/Delete SQL statements */
+ protected final int _executeUpdateQuery(String sql) throws Exception {
+ Session session = getSessionFactory().getCurrentSession();
+ Query query = session.createSQLQuery(sql);
+ return query.executeUpdate();
+ }
+
+ /* Processes Insert/Update/Delete Named SQL statements */
+ @SuppressWarnings("rawtypes")
+ protected final int _executeNamedUpdateQuery(String queryName, Map params) throws Exception {
+ Session session = getSessionFactory().getCurrentSession();
+ Query query = session.getNamedQuery(queryName);
+ bindQueryParameters(query, params);
+ return query.executeUpdate();
+ }
+
+ protected final void _update(DomainVo vo, Integer userId) {
+ _update(vo, ((userId != null) ? userId.intValue() : 0));
+ }
+
+ protected final void _update(DomainVo vo, int userId) {
+ Date timestamp = new Date();
+
+ Session session = getSessionFactory().getCurrentSession();
+
+ if (vo.getId() == null || vo.getId().intValue() == 0) { // add new
+ vo.setCreated(timestamp);
+ vo.setModified(timestamp);
+
+ if (userId != 0
+ && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
+ vo.setCreatedId(new Long(userId));
+ vo.setModifiedId(new Long(userId));
+ }
+ } else { // update existing
+ vo.setModified(timestamp);
+
+ if (userId != 0
+ && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
+ vo.setModifiedId(new Long(userId));
+ }
+ }
+
+ session.saveOrUpdate(vo);
+ }
+
+ protected final void _remove(DomainVo vo) {
+ Session session = getSessionFactory().getCurrentSession();
+ session.delete(vo);
+ }
+
+ @SuppressWarnings("rawtypes")
+ protected final int _remove(Class domainClass, String whereClause) {
+ int rowsAffected = 0;
+
+ Session session = getSessionFactory().getCurrentSession();
+
+ StringBuffer sql = new StringBuffer("delete from ");
+
+ sql.append(domainClass.getName()).append(" where ").append(whereClause);
+
+ rowsAffected = session.createQuery(sql.toString()).executeUpdate();
+
+ return rowsAffected;
+ }
+
+ protected final void _flush() {
+ Session session = getSessionFactory().getCurrentSession();
+ session.flush();
+ }
+
+ @SuppressWarnings("rawtypes")
+ private void bindQueryParameters(Query query, Map params) {
+ if (params != null) {
+ for (Iterator i = params.entrySet().iterator(); i.hasNext();) {
+ Map.Entry entry = (Map.Entry) i.next();
+
+ Object parameterValue = entry.getValue();
+
+ if (!(parameterValue instanceof Collection) && !(parameterValue instanceof Object[])) {
+ query.setParameter((String) entry.getKey(), parameterValue);
+ } else {
+ if (parameterValue instanceof Collection) {
+ query.setParameterList((String) entry.getKey(), (Collection) parameterValue);
+ } else {
+ if (parameterValue instanceof Object[]) {
+ query.setParameterList((String) entry.getKey(), (Object[]) parameterValue);
+ }
+ }
+ }
+ }
+ }
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.dao.support;
+
+import org.hibernate.SessionFactory;
+import org.onap.portalsdk.core.FusionObject;
+
+public class FusionDao implements FusionObject {
+ private SessionFactory sessionFactory;
+
+ public void setSessionFactory(SessionFactory sessionFactory) {
+ this.sessionFactory = sessionFactory;
+ }
+
+ public SessionFactory getSessionFactory() {
+ return this.sessionFactory;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+import org.onap.portalsdk.core.domain.support.DomainVo;
+
+/**
+ * Represents a row in the FN_APP table in the EP_SDK database. (A nearly
+ * identical table is defined in Portal database.)
+ *
+ * @version 1.0
+ */
+public class App extends DomainVo {
+
+ private static final long serialVersionUID = 3465979916929796990L;
+
+ // superclass defines Id
+ private String name; // app_name
+ private String imageUrl; // app_image_url
+ private String description; // app_description
+ private String notes; // app_notes
+ private String url; // app_url
+ private String alternateUrl; // app_alternate_url
+ private String restEndpoint; // app_rest_endpoint
+ private String mlAppName; // ml_app_name
+ private String mlAppAdminId; // ml_app_admin_id;
+ private String motsId; // mots_id
+ private String appPassword; // app_password
+ private String open;
+ private String enabled;
+ private byte[] thumbnail;
+ private String username; // app_username
+ private String uebKey; // ueb_key
+ private String uebSecret; // ueb_secret
+ private String uebTopicName; // ueb_topic_name
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getAppPassword() {
+ return appPassword;
+ }
+
+ public void setAppPassword(String appPassword) {
+ this.appPassword = appPassword;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public String getImageUrl() {
+ return imageUrl;
+ }
+
+ public void setImageUrl(String imageUrl) {
+ this.imageUrl = imageUrl;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getNotes() {
+ return notes;
+ }
+
+ public void setNotes(String notes) {
+ this.notes = notes;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getAlternateUrl() {
+ return alternateUrl;
+ }
+
+ public void setAlternateUrl(String alternateUrl) {
+ this.alternateUrl = alternateUrl;
+ }
+
+ public String getRestEndpoint() {
+ return restEndpoint;
+ }
+
+ public void setRestEndpoint(String restEndpoint) {
+ this.restEndpoint = restEndpoint;
+ }
+
+ public String getMlAppName() {
+ return mlAppName;
+ }
+
+ public void setMlAppName(String mlAppName) {
+ this.mlAppName = mlAppName;
+ }
+
+ public String getMlAppAdminId() {
+ return mlAppAdminId;
+ }
+
+ public void setMlAppAdminId(String mlAppAdminId) {
+ this.mlAppAdminId = mlAppAdminId;
+ }
+
+ public String getMotsId() {
+ return motsId;
+ }
+
+ public void setMotsId(String motsId) {
+ this.motsId = motsId;
+ }
+
+ public String getOpen() {
+ return open;
+ }
+
+ public void setOpen(String open) {
+ this.open = open;
+ }
+
+ public String getEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(String enabled) {
+ this.enabled = enabled;
+ }
+
+ public byte[] getThumbnail() {
+ return this.thumbnail;
+ }
+
+ public void setThumbnail(byte[] thumbnail) {
+ this.thumbnail = thumbnail;
+ }
+
+ public String getUebKey() {
+ return uebKey;
+ }
+
+ public void setUebKey(String uebKey) {
+ this.uebKey = uebKey;
+ }
+
+ public String getUebSecret() {
+ return uebSecret;
+ }
+
+ public void setUebSecret(String uebSecret) {
+ this.uebSecret = uebSecret;
+ }
+
+ public String getUebTopicName() {
+ return uebTopicName;
+ }
+
+ public void setUebTopicName(String uebTopicName) {
+ this.uebTopicName = uebTopicName;
+ }
+
+ /**
+ * Answers true if the objects have the same ID.
+ */
+ public int compareTo(Object obj) {
+ Long c1 = getId();
+ Long c2 = ((App) obj).getId();
+ return c1.compareTo(c2);
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+import java.util.Date;
+
+import org.onap.portalsdk.core.domain.support.DomainVo;
+
+public class AuditLog extends DomainVo {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ public static final String CD_ACTIVITY_LOGIN = "login";
+ public static final String CD_ACTIVITY_LOGOUT = "logout";
+ public static final String CD_ACTIVITY_MOBILE_LOGIN = "mobile_login";
+ public static final String CD_ACTIVITY_MOBILE_LOGOUT = "mobile_logout";
+
+ /*-------Profile activities -----------*/
+ public static final String CD_ACTIVITY_ROLE_ADD = "add_role";
+ public static final String CD_ACTIVITY_ROLE_REMOVE = "remove_role";
+ public static final String CD_ACTIVITY_CHILD_ROLE_ADD = "add_child_role";
+ public static final String CD_ACTIVITY_CHILD_ROLE_REMOVE = "remove_child_role";
+ public static final String CD_ACTIVITY_ROLE_ADD_FUNCTION = "add_role_function";
+ public static final String CD_ACTIVITY_ROLE_REMOVE_FUNCTION = "remove_role_function";
+ public static final String CD_ACTIVITY_USER_ROLE_ADD = "add_user_role";
+ public static final String CD_ACTIVITY_USER_ROLE_REMOVE = "remove_user_role";
+
+ /*Audit activities*/
+ public static final String CD_ACTIVITY_FUNCTIONAL_ACCESS = "functional_access";
+ public static final String CD_ACTIVITY_TAB_ACCESS = "tab_access";
+ public static final String CD_ACTIVITY_APP_ACCESS = "app_access";
+ public static final String CD_ACTIVITY_LEFT_MENU_ACCESS = "left_menu_access";
+
+
+ private String activityCode;
+ private String affectedRecordId;
+ private String comments;
+ private Date auditDate;
+ private Long userId;
+
+ public AuditLog() {
+ setCreated(new Date());
+ }
+
+ public String getActivityCode() {
+ return activityCode;
+ }
+
+ public String getComments() {
+ return comments;
+ }
+
+ public String getAffectedRecordId() {
+ return affectedRecordId;
+ }
+
+ public void setActivityCode(String activityCode) {
+ this.activityCode = activityCode;
+ }
+
+ public void setComments(String comments) {
+ this.comments = comments;
+ }
+
+ public void setAffectedRecordId(String affectedRecordId) {
+ this.affectedRecordId = affectedRecordId;
+ }
+
+ public Date getAuditDate() {
+ return auditDate;
+ }
+
+ public void setAuditDate(Date auditDate) {
+ this.auditDate = auditDate;
+ }
+
+ public Long getUserId() {
+ return userId;
+ }
+
+ public void setUserId(Long userId) {
+ this.userId = userId;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+import java.util.*;
+
+import org.onap.portalsdk.core.domain.support.DomainVo;
+
+public class BroadcastMessage extends DomainVo {
+
+ /**
+ *
+ */
+
+ private static final long serialVersionUID = 1L;
+ public BroadcastMessage() {
+ }
+
+ public static final String ID_MESSAGE_LOCATION_LOGIN = "10";
+ public static final String ID_MESSAGE_LOCATION_WELCOME = "20";
+
+ private String messageText;
+ private Integer locationId;
+ private Date startDate;
+ private Date endDate;
+ private Integer sortOrder;
+ private Boolean active;
+ private String siteCd;
+
+ public Boolean getActive() {
+ return active;
+ }
+
+ public Date getEndDate() {
+ return endDate;
+ }
+
+ public Integer getLocationId() {
+ return locationId;
+ }
+
+ public String getMessageText() {
+ return messageText;
+ }
+
+ public Integer getSortOrder() {
+ return sortOrder;
+ }
+
+ public Date getStartDate() {
+ return startDate;
+ }
+
+ public String getSiteCd() {
+ return siteCd;
+ }
+
+
+ public void setActive(Boolean active) {
+ this.active = active;
+ }
+
+ public void setEndDate(Date endDate) {
+ this.endDate = endDate;
+ }
+
+ public void setLocationId(Integer locationId) {
+ this.locationId = locationId;
+ }
+
+ public void setMessageText(String messageText) {
+ this.messageText = messageText;
+ }
+
+ public void setSortOrder(Integer sortOrder) {
+ this.sortOrder = sortOrder;
+ }
+
+ public void setStartDate(Date startDate) {
+ this.startDate = startDate;
+ }
+
+ public void setSiteCd(String siteCd) {
+ this.siteCd = siteCd;
+ }
+
+
+ public int compareTo(Object obj){
+ Integer c1 = getLocationId();
+ Integer c2 = ((BroadcastMessage)obj).getLocationId();
+
+ if (c1.compareTo(c2) == 0) {
+ c1 = getSortOrder();
+ c2 = ((BroadcastMessage)obj).getSortOrder();
+
+ if (c1.compareTo(c2) == 0) {
+ Long c3 = getId();
+ Long c4 = ((BroadcastMessage)obj).getId();
+
+ return c3.compareTo(c4);
+ }
+ }
+
+ return c1.compareTo(c2);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Set;
+
+/* Super class from which all data objects descend
+ *
+ * Per Sunder T on 3 June 2016:
+ *
+ * Yes, we need to get rid of domain.DomainVO and fold all the references to the support.DomainVO.
+ */
+@SuppressWarnings("rawtypes")
+@Deprecated
+public class DomainVo extends FusionVo implements Serializable, Cloneable, Comparable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ protected Long id;
+ protected Date created;
+ protected Date modified;
+ protected Long createdId;
+ protected Long modifiedId;
+ protected Long rowNum;
+
+ protected Serializable auditUserId;
+
+ Set auditTrail = null;
+
+ public DomainVo() {
+ }
+
+ public void setId(Long i) {
+ id = i;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ public void setModified(Date modified) {
+ this.modified = modified;
+ }
+
+ public void setCreatedId(Long createdId) {
+ this.createdId = createdId;
+ }
+
+ public void setModifiedId(Long modifiedId) {
+ this.modifiedId = modifiedId;
+ }
+
+ public void setAuditUserId(Serializable auditUserId) {
+ this.auditUserId = auditUserId;
+ }
+
+ public void setRowNum(Long rowNum) {
+ this.rowNum = rowNum;
+ }
+
+ public void setAuditTrail(Set auditTrail) {
+ this.auditTrail = auditTrail;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public Date getModified() {
+ return modified;
+ }
+
+ public Long getCreatedId() {
+ return createdId;
+ }
+
+ public Long getModifiedId() {
+ return modifiedId;
+ }
+
+ public Serializable getAuditUserId() {
+ return auditUserId;
+ }
+
+ public Long getRowNum() {
+ return rowNum;
+ }
+
+ public Set getAuditTrail() {
+ return auditTrail;
+ }
+
+ @SuppressWarnings("unchecked")
+ public void addAuditTrailLog(AuditLog auditLog) {
+ if (getAuditTrail() == null) {
+ setAuditTrail(new HashSet());
+ }
+
+ getAuditTrail().add(auditLog);
+ }
+
+ public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+
+ public Object copy() {
+ return copy(false);
+ }
+
+ public Object copy(boolean isIdNull) {
+ // let's create a "copy" of the object using serialization
+ ByteArrayOutputStream baos = null;
+ ByteArrayInputStream bais = null;
+ ObjectOutputStream oos = null;
+ ObjectInputStream ois = null;
+
+ DomainVo newVo = null;
+
+ try {
+
+ baos = new ByteArrayOutputStream();
+ oos = new ObjectOutputStream(baos);
+ oos.writeObject(this);
+
+ bais = new ByteArrayInputStream(baos.toByteArray());
+ ois = new ObjectInputStream(bais);
+ newVo = (DomainVo) ois.readObject();
+
+ if (isIdNull) {
+ newVo.setId(null);
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return newVo;
+ }
+
+ public int compareTo(Object obj) {
+ Long c1 = getId();
+ Long c2 = ((DomainVo) obj).getId();
+
+ return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+
+import org.onap.portalsdk.core.domain.support.DomainVo;
+
+/**
+ * <p>RoleFunction.java</p>
+ *
+ * <p>Represents a role function data object.</p>
+ *
+ * @version 1.0
+ */
+public class FnMenu extends DomainVo {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ public FnMenu() {}
+
+ private Integer menuId;
+ private String label;
+ private Integer parentId;
+ private String action;
+ private String functionCd;
+ private Integer sortOrder;
+ private String servlet;
+ private String queryString;
+ private String externalUrl;
+ private String target;
+ private String active;
+ private String separator;
+ private String imageSrc;
+ private String menuSetCode;
+
+ public Integer getMenuId() {
+ return menuId;
+ }
+ public void setMenuId(Integer menuId) {
+ this.menuId = menuId;
+ }
+ public String getLabel() {
+ return label;
+ }
+ public void setLabel(String label) {
+ this.label = label;
+ }
+ public Integer getParentId() {
+ return parentId;
+ }
+ public void setParentId(Integer parentId) {
+ this.parentId = parentId;
+ }
+ public String getAction() {
+ return action;
+ }
+ public void setAction(String action) {
+ this.action = action;
+ }
+ public String getFunctionCd() {
+ return functionCd;
+ }
+ public void setFunctionCd(String functionCd) {
+ this.functionCd = functionCd;
+ }
+ public Integer getSortOrder() {
+ return sortOrder;
+ }
+ public void setSortOrder(Integer sortOrder) {
+ this.sortOrder = sortOrder;
+ }
+ public String getServlet() {
+ return servlet;
+ }
+ public void setServlet(String servlet) {
+ this.servlet = servlet;
+ }
+ public String getQueryString() {
+ return queryString;
+ }
+ public void setQueryString(String queryString) {
+ this.queryString = queryString;
+ }
+ public String getExternalUrl() {
+ return externalUrl;
+ }
+ public void setExternalUrl(String externalUrl) {
+ this.externalUrl = externalUrl;
+ }
+ public String getTarget() {
+ return target;
+ }
+ public void setTarget(String target) {
+ this.target = target;
+ }
+ public String getActive() {
+ return active;
+ }
+ public void setActive(String active) {
+ this.active = active;
+ }
+ public String getSeparator() {
+ return separator;
+ }
+ public void setSeparator(String separator) {
+ this.separator = separator;
+ }
+ public String getImageSrc() {
+ return imageSrc;
+ }
+ public void setImageSrc(String imageSrc) {
+ this.imageSrc = imageSrc;
+ }
+ public String getMenuSetCode() {
+ return menuSetCode;
+ }
+ public void setMenuSetCode(String menuSetCode) {
+ this.menuSetCode = menuSetCode;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+import org.onap.portalsdk.core.FusionObject;
+
+public class FusionVo implements FusionObject {
+ public FusionVo() {
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+import java.util.Set;
+
+import org.onap.portalsdk.core.domain.support.FusionCommand;
+
+@SuppressWarnings("rawtypes")
+public class LoginBean extends FusionCommand {
+
+ private String loginId;
+ private String loginPwd;
+ private String hrid;
+ private String orgUserId;
+ private String siteAccess;
+ private String loginErrorMessage;
+
+ private User user;
+ private Set menu;
+ private Set businessDirectMenu;
+
+ /**
+ * getLoginId
+ *
+ * @return String
+ */
+ public String getLoginId() {
+ return loginId;
+ }
+
+ /**
+ * getLoginPwd
+ *
+ * @return String
+ */
+ public String getLoginPwd() {
+ return loginPwd;
+ }
+
+ /**
+ * getMenu
+ *
+ * @return Set
+ */
+ public Set getMenu() {
+ return menu;
+ }
+
+ /**
+ * getUser
+ *
+ * @return User
+ */
+ public User getUser() {
+ return user;
+ }
+
+ /**
+ * getHrid
+ *
+ * @return String
+ */
+ public String getHrid() {
+ return hrid;
+ }
+
+ /**
+ * getSiteAccess
+ *
+ * @return String
+ */
+ public String getSiteAccess() {
+ return siteAccess;
+ }
+
+ /**
+ * getBusinessDirectMenu
+ *
+ * @return Set
+ */
+ public Set getBusinessDirectMenu() {
+ return businessDirectMenu;
+ }
+
+ /**
+ * getLoginErrorMessage
+ *
+ * @return String
+ */
+ public String getLoginErrorMessage() {
+ return loginErrorMessage;
+ }
+
+ public String getOrgUserId() {
+ return orgUserId;
+ }
+
+ /**
+ * setLoginId
+ *
+ * @param loginId String
+ */
+ public void setLoginId(String loginId) {
+ this.loginId = loginId;
+ }
+
+ /**
+ * setLoginPwd
+ *
+ * @param loginPwd String
+ */
+ public void setLoginPwd(String loginPwd) {
+ this.loginPwd = loginPwd;
+ }
+
+ public void setMenu(Set menu) {
+ this.menu = menu;
+ }
+
+ /**
+ * setUser
+ *
+ * @param user User
+ */
+ public void setUser(User user) {
+ this.user = user;
+ }
+
+ /**
+ * setHrid
+ *
+ * @param hrid String
+ */
+ public void setHrid(String hrid) {
+ this.hrid = hrid;
+ }
+
+ /**
+ * setSiteAccess
+ *
+ * @param siteAccess String
+ */
+ public void setSiteAccess(String siteAccess) {
+ this.siteAccess = siteAccess;
+ }
+
+ /**
+ * setBusinessDirectMenu
+ *
+ * @param businessDirectMenu Set
+ */
+ public void setBusinessDirectMenu(Set businessDirectMenu) {
+ this.businessDirectMenu = businessDirectMenu;
+ }
+
+ /**
+ * setLoginErrorMessage
+ *
+ * @param loginErrorMessage String
+ */
+ public void setLoginErrorMessage(String loginErrorMessage) {
+ this.loginErrorMessage = loginErrorMessage;
+ }
+
+ public void setOrgUserId(String orgUserId) {
+ this.orgUserId = orgUserId;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+import java.io.Serializable;
+import java.util.Objects;
+
+import org.onap.portalsdk.core.domain.support.NameValueId;
+
+public class Lookup extends FusionVo implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private NameValueId nameValueId = new NameValueId();
+
+ public Lookup() {}
+
+ public Lookup(String label, String value) {
+ this();
+ setLabel(label);
+ setValue(value);
+ }
+
+ public String getValue() {
+ return getNameValueId().getVal();
+ }
+
+ public String getLabel() {
+ return getNameValueId().getLab();
+ }
+
+ public void setValue(String value) {
+ getNameValueId().setVal(value);
+ }
+
+ public void setLabel(String label) {
+ getNameValueId().setLab(label);
+ }
+
+ public NameValueId getNameValueId() {
+ return nameValueId;
+ }
+
+ public void setNameValueId(NameValueId nameValueId) {
+ this.nameValueId = nameValueId;
+ }
+
+ // required by ZK for to set the selectedItems of Listboxes (used heavily for <select>-style drop-downs)
+ @Override
+ public int hashCode() {
+ return Objects.hash(getValue(), getLabel());
+ }
+
+ @Override
+ public boolean equals( Object obj ) {
+ if (obj == null || !(obj instanceof Lookup))
+ return false;
+ Lookup lookup = (Lookup)obj;
+ return Objects.equals(lookup.getValue(), getValue()) && Objects.equals(lookup.getLabel(), getLabel());
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+
+import org.onap.portalsdk.core.domain.support.*;
+
+
+/**
+ * <p>luCountry.java</p>
+ *
+ * <p>Represents a country data object.</p>
+ *
+ * @version 1.0
+ */
+public class LuCountry extends DomainVo {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ LuCountry() {}
+
+ public String getCountry() {
+ return country;
+ }
+
+ public String getAbbr() {
+ return abbr;
+ }
+
+ public void setCountry(String country) {
+ this.country = country;
+ }
+
+ public void setAbbr(String abbr) {
+ this.abbr = abbr;
+ }
+
+
+ public String getFullName() {
+ return fullName;
+ }
+
+ public void setFullName(String fullName) {
+ this.fullName = fullName;
+ }
+
+ public String getWebphoneCountryLabel() {
+ return webphoneCountryLabel;
+ }
+
+ public void setWebphoneCountryLabel(String webphoneCountryLabel) {
+ this.webphoneCountryLabel = webphoneCountryLabel;
+ }
+
+ public int compareTo(Object obj){
+ String c1 = getCountry();
+ String c2 = ((LuCountry)obj).getCountry();
+
+ return c1.compareTo(c2);
+ }
+
+
+ private String abbr;
+ private String country;
+ private String fullName;
+ private String webphoneCountryLabel;
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+
+import org.onap.portalsdk.core.domain.support.*;
+
+
+/**
+ * <p>State.java</p>
+ *
+ * <p>Represents a state data object.</p>
+ *
+ * @version 1.0
+ */
+public class LuState extends DomainVo {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ LuState() {}
+
+ public String getState() {
+ return state;
+ }
+
+ public String getAbbr() {
+ return abbr;
+ }
+
+ public void setState(String state) {
+ this.state = state;
+ }
+
+ public void setAbbr(String abbr) {
+ this.abbr = abbr;
+ }
+
+
+ public int compareTo(Object obj){
+ String c1 = getState();
+ String c2 = ((LuState)obj).getState();
+
+ return c1.compareTo(c2);
+ }
+
+
+ private String abbr;
+ private String state;
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+
+import org.onap.portalsdk.core.domain.support.*;
+
+
+/**
+ * <p>LuTimeZone.java</p>
+ *
+ * <p>Represents a LuTimeZone data object.</p>
+ *
+ * @version 1.0
+ */
+public class LuTimeZone extends DomainVo {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ LuTimeZone() {}
+
+ public String getName() {
+ return name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+
+ public Long getTimezoneId() {
+ return timezoneId;
+ }
+
+ public void setTimezoneId(Long timezoneId) {
+ this.timezoneId = timezoneId;
+ }
+
+ public int compareTo(Object obj){
+ Long c1 = getId();
+ Long c2 = ((LuTimeZone)obj).getId();
+
+ return c1.compareTo(c2);
+ }
+
+
+ private String name;
+ private Long timezoneId;
+ private String value;
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+
+import org.onap.portalsdk.core.domain.support.DomainVo;
+
+public class Menu extends DomainVo {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ public Menu() {}
+
+ public String getAction() {
+ return action;
+ }
+
+ public boolean isActive() {
+ return active;
+ }
+
+ public String getExternalUrl() {
+ return externalUrl;
+ }
+
+ public String getFunctionCd() {
+ return functionCd;
+ }
+
+ public String getLabel() {
+ return label;
+ }
+
+ public String getMenuLevel() {
+ return menuLevel;
+ }
+
+ public Long getParentId() {
+ return parentId;
+ }
+
+ public String getQueryString() {
+ return queryString;
+ }
+
+ public String getServlet() {
+ return servlet;
+ }
+
+ public Short getSortOrder() {
+ return sortOrder;
+ }
+
+ public String getTarget() {
+ return target;
+ }
+
+ public String getMenuSetCode() {
+ return menuSetCode;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public void setActive(boolean active) {
+ this.active = active;
+ }
+
+ public void setExternalUrl(String externalUrl) {
+ this.externalUrl = externalUrl;
+ }
+
+ public void setFunctionCd(String functionCd) {
+ this.functionCd = functionCd;
+ }
+
+ public void setLabel(String label) {
+ this.label = label;
+ }
+
+ public void setMenuLevel(String menuLevel) {
+ this.menuLevel = menuLevel;
+ }
+
+ public void setParentId(Long parentId) {
+ this.parentId = parentId;
+ }
+
+ public void setQueryString(String queryString) {
+ this.queryString = queryString;
+ }
+
+ public void setServlet(String servlet) {
+ this.servlet = servlet;
+ }
+
+ public void setSortOrder(Short sortOrder) {
+ this.sortOrder = sortOrder;
+ }
+
+ public void setTarget(String target) {
+ this.target = target;
+ }
+
+ public void setMenuSetCode(String menuSetCode) {
+ this.menuSetCode = menuSetCode;
+ }
+
+ public boolean isSeparator() {
+ return separator;
+ }
+
+ public void setSeparator(boolean separator) {
+ this.separator = separator;
+ }
+
+ public String getImageSrc() {
+ return imageSrc;
+ }
+
+ public void setImageSrc(String imageSrc) {
+ this.imageSrc = imageSrc;
+ }
+
+ private String menuLevel;
+ private String label;
+ private Long parentId;
+ private String action;
+ private String functionCd;
+ private Short sortOrder;
+ private String servlet;
+ private String queryString;
+ private String externalUrl;
+ private String target;
+ private boolean active;
+ private String menuSetCode;
+ private boolean separator;
+ private String imageSrc;
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+import java.util.*;
+
+public class MenuData extends Menu {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private MenuData parentMenu;
+ private Set childMenus = new TreeSet();
+
+ public MenuData() {}
+
+ public Set getChildMenus() {
+ return childMenus;
+ }
+
+ public MenuData getParentMenu() {
+ return parentMenu;
+ }
+
+ public void setChildMenus(Set childMenus) {
+ this.childMenus = childMenus;
+ }
+
+ public void setParentMenu(MenuData parentMenu) {
+ this.parentMenu = parentMenu;
+ }
+
+ public int compareTo(Object obj){
+
+ Short c1 = getSortOrder();
+ Short c2 = ((MenuData)obj).getSortOrder();
+
+ return (c1 == null || c2 == null) ? 1 : ((c1.compareTo(c2) == 0) ? 1 : c1.compareTo(c2));
+ }
+
+ public String getActiveAsString(){
+ return String.valueOf(isActive());
+ }
+
+ public String getParentIdAsString(){
+ return String.valueOf(getParentId());
+ }
+
+ public String getSeparatorAsString(){
+ return String.valueOf(isSeparator());
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+import org.onap.portalsdk.core.domain.support.DomainVo;
+
+public class Profile extends DomainVo{
+
+ private static final long serialVersionUID = 3409056457412656883L;
+
+ private Long id;
+ private String first_name;
+ private String last_name;
+ private String email;
+ private String orgManagerUserId;
+ private String active_yn;
+ private String orgUserId;
+ public Profile() {}
+
+
+ public Long getId() {
+ return id;
+ }
+
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+
+ public String getFirst_name() {
+ return first_name;
+ }
+
+ public void setFirst_name(String first_name) {
+ this.first_name = first_name;
+ }
+
+ public String getLast_name() {
+ return last_name;
+ }
+
+ public void setLast_name(String last_name) {
+ this.last_name = last_name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getOrgManagerUserId() {
+ return orgManagerUserId;
+ }
+
+ public void setOrgManagerUserId(String orgManagerUserId) {
+ this.orgManagerUserId = orgManagerUserId;
+ }
+
+ public String getActive_yn() {
+ return active_yn;
+ }
+
+ public void setActive_yn(String active_yn) {
+ this.active_yn = active_yn;
+ }
+
+ public String getOrgUserId() {
+ return orgUserId;
+ }
+
+ public void setOrgUserId(String orgUserId) {
+ this.orgUserId = orgUserId;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+
+import java.util.Iterator;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.onap.portalsdk.core.domain.support.DomainVo;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+/**
+ * <p>Role.java</p>
+ * <p>Represents a role data object.</p>
+ *
+ * @version 1.0
+ */
+public class Role extends DomainVo {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private String name;
+ private boolean active;
+ private Integer priority;
+
+ private Set roleFunctions = new TreeSet();
+
+ private Set childRoles = new TreeSet();
+ @JsonIgnore
+ private Set parentRoles = new TreeSet();
+
+ public Role() {}
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean getActive() {
+ return active;
+ }
+
+ public Set getRoleFunctions() {
+ return roleFunctions;
+ }
+
+ public Integer getPriority() {
+ return priority;
+ }
+
+ public Set getChildRoles() {
+ return childRoles;
+ }
+
+ public Set getParentRoles() {
+ return parentRoles;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setActive(boolean active) {
+ this.active = active;
+ }
+
+ public void setRoleFunctions(Set roleFunctions) {
+ this.roleFunctions = roleFunctions;
+ }
+
+ public void setPriority(Integer priority) {
+ this.priority = priority;
+ }
+
+
+ public void setChildRoles(Set childRoles) {
+ this.childRoles = childRoles;
+ }
+
+ public void setParentRoles(Set parentRoles) {
+ this.parentRoles = parentRoles;
+ }
+
+ @SuppressWarnings("unchecked")
+ public void addRoleFunction(RoleFunction roleFunction) {
+ this.roleFunctions.add(roleFunction);
+ }
+
+ @SuppressWarnings("unchecked")
+ public void addChildRole(Role role) {
+ this.childRoles.add(role);
+ }
+
+ @SuppressWarnings("unchecked")
+ public void addParentRole(Role role) {
+ this.parentRoles.add(role);
+ }
+
+ public String getEditUrl() {
+ return "/role.htm?role_id=" + getId();
+ }
+
+ public String getToggleActiveImage() {
+ return "/static/fusion/images/" + (getActive() ? "active.png" : "inactive.png" );
+ }
+
+ public String getToggleActiveAltText() {
+ return getActive() ? "Click to Deactivate Role" : "Click to Activate Role";
+ }
+
+ public void removeChildRole(Long roleId) {
+ Iterator i = this.childRoles.iterator();
+
+ while (i.hasNext()) {
+ Role childRole = (Role)i.next();
+ if (childRole.getId().equals(roleId)) {
+ this.childRoles.remove(childRole);
+ break;
+ }
+ }
+ }
+
+ public void removeParentRole(Long roleId) {
+ Iterator i = this.parentRoles.iterator();
+
+ while (i.hasNext()) {
+ Role parentRole = (Role)i.next();
+ if (parentRole.getId().equals(roleId)) {
+ this.parentRoles.remove(parentRole);
+ break;
+ }
+ }
+ }
+
+ public void removeRoleFunction(String roleFunctionCd) {
+ Iterator i = this.roleFunctions.iterator();
+
+ while (i.hasNext()) {
+ RoleFunction roleFunction = (RoleFunction)i.next();
+ if (roleFunction.getCode().equals(roleFunctionCd)) {
+ this.roleFunctions.remove(roleFunction);
+ break;
+ }
+ }
+ }
+
+ public int compareTo(Object obj){
+ String c1 = getName();
+ String c2 = ((Role)obj).getName();
+
+ return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+
+import org.onap.portalsdk.core.domain.support.DomainVo;
+
+/**
+ * <p>RoleFunction.java</p>
+ *
+ * <p>Represents a role function data object.</p>
+ *
+ * @version 1.0
+ */
+public class RoleFunction extends DomainVo {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ public RoleFunction() {}
+
+ public String getName() {
+ return name;
+ }
+
+ public String getCode() {
+ return code;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setCode(String code) {
+ this.code = code;
+ }
+
+ public String getEditUrl() {
+ return "/role_function.htm?role_function_id=" + getCode();
+ }
+
+ public int compareTo(Object obj){
+ String c1 = getName();
+ String c2 = ((RoleFunction)obj).getName();
+
+ return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
+ }
+
+ private String code;
+ private String name;
+ private String editUrl;
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+import java.io.Serializable;
+import java.util.Objects;
+
+public class UrlsAccessible extends FusionVo implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private UrlsAccessibleKey urlsAccessibleKey = new UrlsAccessibleKey();
+
+ public UrlsAccessible() {}
+
+ public UrlsAccessible(String url, String functionCd) {
+ this();
+ setUrl(url);
+ setFunctionCd(functionCd);
+ }
+
+ public String getUrl() {
+ return getUrlsAccessibleKey().getUrl();
+ }
+
+ public String getFunctionCd() {
+ return getUrlsAccessibleKey().getFunctionCd();
+ }
+
+ public void setUrl(String url) {
+ getUrlsAccessibleKey().setUrl(url);
+ }
+
+ public void setFunctionCd(String functionCd) {
+ getUrlsAccessibleKey().setFunctionCd(functionCd);
+ }
+
+ public UrlsAccessibleKey getUrlsAccessibleKey() {
+ return urlsAccessibleKey;
+ }
+
+ public void setUrlsAccessibleKey(UrlsAccessibleKey urlsAccessibleKey) {
+ this.urlsAccessibleKey = urlsAccessibleKey;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getUrl(), getFunctionCd());
+ }
+
+ @Override
+ public boolean equals( Object obj ) {
+ if (obj == null || !(obj instanceof UrlsAccessible))
+ return false;
+ UrlsAccessible ua = (UrlsAccessible)obj;
+ return Objects.equals(ua.getUrl(), getUrl()) && Objects.equals(ua.getFunctionCd(), getFunctionCd());
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+import java.io.*;
+
+
+public class UrlsAccessibleKey implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private String url;
+ private String functionCd;
+
+ public UrlsAccessibleKey() {
+ }
+
+ public UrlsAccessibleKey(String url, String functionCd) {
+ setUrl(url);
+ setFunctionCd(functionCd);
+ }
+
+
+ public String getUrl() {
+ return url;
+ }
+
+
+ public String getFunctionCd() {
+ return functionCd;
+ }
+
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+
+ public void setFunctionCd(String functionCd) {
+ this.functionCd = functionCd;
+ }
+
+
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+
+ if (o == null) {
+ return false;
+ }
+
+ if (!(o instanceof UrlsAccessibleKey)) {
+ return false;
+ }
+
+ final UrlsAccessibleKey key = (UrlsAccessibleKey)o;
+
+ if (getFunctionCd().equals(key.getFunctionCd()) & getUrl().equals(key.getUrl())) {
+ return true;
+ }
+
+ return false;
+ }
+
+
+ public int hashCode() {
+ return getUrl().hashCode() + getFunctionCd().hashCode();
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+
+import java.util.Date;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import org.onap.portalsdk.core.domain.support.DomainVo;
+
+/**
+ * <p>User.java</p>
+ *
+ * <p>Represents a user data object.</p>
+ *
+ * @version 1.0
+ */
+public class User extends DomainVo {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private Long orgId;
+ private Long managerId;
+ private String firstName;
+ private String middleInitial;
+ private String lastName;
+ private String phone;
+ private String fax;
+ private String cellular;
+ private String email;
+ private Long addressId;
+ private String alertMethodCd;
+ private String hrid;
+ private String orgUserId;
+ private String orgCode;
+ private String address1;
+ private String address2;
+ private String city;
+ private String state;
+ private String zipCode;
+ private String country;
+ private String orgManagerUserId;
+ private String locationClli;
+ private String businessCountryCode;
+ private String businessCountryName;
+ private String businessUnit;
+ private String businessUnitName;
+ private String department;
+ private String departmentName;
+ private String companyCode;
+ private String company;
+ private String zipCodeSuffix;
+ private String jobTitle;
+ private String commandChain;
+ private String siloStatus;
+ private String costCenter;
+ private String financialLocCode;
+
+
+
+ private String loginId;
+ private String loginPwd;
+ private Date lastLoginDate;
+ private boolean active;
+ private boolean internal;
+ private Long selectedProfileId;
+ private Long timeZoneId;
+ private boolean online;
+ private String chatId;
+
+ private Set userApps = new TreeSet();
+
+ private Set pseudoRoles = new TreeSet();
+
+
+ public User() {}
+
+ public Long getAddressId() {
+ return addressId;
+ }
+
+ public String getAlertMethodCd() {
+ return alertMethodCd;
+ }
+
+ public String getCellular() {
+ return cellular;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public String getFax() {
+ return fax;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public String getHrid() {
+ return hrid;
+ }
+
+ public Date getLastLoginDate() {
+ return lastLoginDate;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public String getFullName() {
+ return getFirstName() + " " + getLastName();
+ }
+
+ public String getLoginId() {
+ return loginId;
+ }
+
+ public String getLoginPwd() {
+ return loginPwd;
+ }
+
+ public Long getManagerId() {
+ return managerId;
+ }
+
+ public String getMiddleInitial() {
+ return middleInitial;
+ }
+
+ public String getOrgCode() {
+ return orgCode;
+ }
+
+ public Long getOrgId() {
+ return orgId;
+ }
+
+ public String getPhone() {
+ return phone;
+ }
+
+ public String getOrgUserId() {
+ return orgUserId;
+ }
+
+ public boolean getActive() {
+ return active;
+ }
+
+ public boolean getInternal() {
+ return internal;
+ }
+
+ public String getAddress1() {
+ return address1;
+ }
+
+ public String getAddress2() {
+ return address2;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public String getCountry() {
+ return country;
+ }
+
+ public String getState() {
+ return state;
+ }
+
+ public String getZipCode() {
+ return zipCode;
+ }
+
+ public String getBusinessCountryCode() {
+ return businessCountryCode;
+ }
+
+ public String getCommandChain() {
+ return commandChain;
+ }
+
+ public String getCompany() {
+ return company;
+ }
+
+ public String getCompanyCode() {
+ return companyCode;
+ }
+
+ public String getDepartment() {
+ return department;
+ }
+
+ public String getJobTitle() {
+ return jobTitle;
+ }
+
+ public String getLocationClli() {
+ return locationClli;
+ }
+
+ public String getOrgManagerUserId() {
+ return orgManagerUserId;
+ }
+
+ public String getZipCodeSuffix() {
+ return zipCodeSuffix;
+ }
+
+ public String getBusinessCountryName() {
+ return businessCountryName;
+ }
+
+ public Set getPseudoRoles() {
+ return pseudoRoles;
+ }
+
+ public Long getSelectedProfileId() {
+ return selectedProfileId;
+ }
+
+ public void setAddressId(Long addressId) {
+ this.addressId = addressId;
+ }
+
+ public void setAlertMethodCd(String alertMethodCd) {
+ this.alertMethodCd = alertMethodCd;
+ }
+
+ public void setCellular(String cellular) {
+ this.cellular = cellular;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public void setFax(String fax) {
+ this.fax = fax;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public void setHrid(String hrid) {
+ this.hrid = hrid;
+ }
+
+ public void setLastLoginDate(Date lastLoginDate) {
+ this.lastLoginDate = lastLoginDate;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public void setLoginId(String loginId) {
+ this.loginId = loginId;
+ }
+
+ public void setLoginPwd(String loginPwd) {
+ this.loginPwd = loginPwd;
+ }
+
+ public void setManagerId(Long managerId) {
+ this.managerId = managerId;
+ }
+
+ public void setMiddleInitial(String middleInitial) {
+ this.middleInitial = middleInitial;
+ }
+
+ public void setOrgCode(String orgCode) {
+ this.orgCode = orgCode;
+ }
+
+ public void setOrgId(Long orgId) {
+ this.orgId = orgId;
+ }
+
+ public void setPhone(String phone) {
+ this.phone = phone;
+ }
+
+ public void setOrgUserId(String orgUserId) {
+ this.orgUserId = orgUserId;
+ }
+
+ public void setActive(boolean active) {
+ this.active = active;
+ }
+
+ public void setInternal(boolean internal) {
+ this.internal = internal;
+ }
+
+ public void setAddress1(String address1) {
+ this.address1 = address1;
+ }
+
+ public void setAddress2(String address2) {
+ this.address2 = address2;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ public void setCountry(String country) {
+ this.country = country;
+ }
+
+ public void setState(String state) {
+ this.state = state;
+ }
+
+ public void setZipCode(String zipCode) {
+ this.zipCode = zipCode;
+ }
+
+ public void setBusinessCountryCode(String businessCountryCode) {
+ this.businessCountryCode = businessCountryCode;
+ }
+
+ public void setCommandChain(String commandChain) {
+ this.commandChain = commandChain;
+ }
+
+ public void setCompany(String company) {
+ this.company = company;
+ }
+
+ public void setCompanyCode(String companyCode) {
+ this.companyCode = companyCode;
+ }
+
+ public void setDepartment(String department) {
+ this.department = department;
+ }
+
+ public void setJobTitle(String jobTitle) {
+ this.jobTitle = jobTitle;
+ }
+
+ public void setLocationClli(String locationClli) {
+ this.locationClli = locationClli;
+ }
+
+ public void setOrgManagerUserId(String orgManagerUserId) {
+ this.orgManagerUserId = orgManagerUserId;
+ }
+
+ public void setZipCodeSuffix(String zipCodeSuffix) {
+ this.zipCodeSuffix = zipCodeSuffix;
+ }
+
+ public void setBusinessCountryName(String businessCountryName) {
+ this.businessCountryName = businessCountryName;
+ }
+
+ public void setPseudoRoles(Set pseudoRoles) {
+ this.pseudoRoles = pseudoRoles;
+ }
+
+ public void setSelectedProfileId(Long selectedProfileId) {
+ this.selectedProfileId = selectedProfileId;
+ }
+
+ public Long getTimeZoneId() {
+ return timeZoneId;
+ }
+
+ public void setTimeZoneId(Long timeZoneId) {
+ this.timeZoneId = timeZoneId;
+ }
+
+ public String getBusinessUnit() {
+ return businessUnit;
+ }
+
+ public void setBusinessUnit(String businessUnit) {
+ this.businessUnit = businessUnit;
+ }
+
+ public String getSiloStatus() {
+ return siloStatus;
+ }
+
+ public void setSiloStatus(String siloStatus) {
+ this.siloStatus = siloStatus;
+ }
+
+ public String getCostCenter() {
+ return costCenter;
+ }
+
+ public void setCostCenter(String costCenter) {
+ this.costCenter = costCenter;
+ }
+
+ public String getFinancialLocCode() {
+ return financialLocCode;
+ }
+
+ public void setFinancialLocCode(String financialLocCode) {
+ this.financialLocCode = financialLocCode;
+ }
+
+ public String getBusinessUnitName() {
+ return businessUnitName;
+ }
+
+ public void setBusinessUnitName(String businessUnitName) {
+ this.businessUnitName = businessUnitName;
+ }
+
+ public String getDepartmentName() {
+ return departmentName;
+ }
+
+ public void setDepartmentName(String departmentName) {
+ this.departmentName = departmentName;
+ }
+
+ public int compareTo(Object obj){
+ User user = (User)obj;
+
+ String c1 = getLastName() + getFirstName() + getMiddleInitial();
+ String c2 = user.getLastName() + user.getFirstName() + user.getMiddleInitial();
+
+ return c1.compareTo(c2);
+ }
+
+ public boolean isOnline() {
+ return online;
+ }
+
+ public void setOnline(boolean online) {
+ this.online = online;
+ }
+
+ public String getChatId() {
+ return chatId;
+ }
+
+ public void setChatId(String chatId) {
+ this.chatId = chatId;
+ }
+
+ public Set getUserApps() {
+ return userApps;
+ }
+
+ public void setUserApps(Set userApps) {
+ this.userApps = userApps;
+ }
+
+ @SuppressWarnings("unchecked")
+ public void addAppRoles(App app, SortedSet<Role> roles) {
+ if(roles!=null){
+ //add all
+ Set userApps = new TreeSet();
+ Iterator itr = roles.iterator();
+ while(itr.hasNext()){
+ Role role = (Role) itr.next();
+ UserApp userApp = new UserApp();
+ userApp.setUserId(this.id);
+ userApp.setApp(app);
+ userApp.setRole(role);
+ userApps.add(userApp);
+ }
+ setUserApps(userApps);
+ } else {
+ //remove all
+ this.userApps.clear();
+ }
+
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public SortedSet<Role> getAppRoles(App app) {
+ SortedSet<Role> roles = new TreeSet();
+ Set apps = getUserApps();
+ Iterator appsItr = apps.iterator();
+ UserApp userApp = null;
+ //getting default app
+ while(appsItr.hasNext()){
+ UserApp tempUserApp = (UserApp)appsItr.next();
+ if(tempUserApp.getApp().getId().equals(app.getId())){
+ userApp = tempUserApp;
+ roles.add(userApp.getRole());
+ }
+ }
+ return roles;
+ }
+
+ public SortedSet<Role> getRoles() {
+ App app = new App();
+ app.setId(new Long(1));
+ app.setName("Default");
+ return getAppRoles(app);
+ }
+
+ public UserApp getDefaultUserApp(){
+ Set apps = getUserApps();
+ Iterator appsItr = apps.iterator();
+ UserApp userApp = null;
+ //getting default app
+ while(appsItr.hasNext()){
+ UserApp tempApp = (UserApp)appsItr.next();
+ if(tempApp.equals(new Long(1))){
+ userApp = tempApp;
+ break;
+ }
+ }
+ return userApp;
+ }
+
+ public void setRoles(SortedSet<Role> roles) {
+ App app = new App();
+ app.setId(new Long(1));
+ app.setName("Default");
+ addAppRoles(app,roles);
+ }
+
+ public void removeRole(Long roleId) {
+ Set apps = getUserApps();
+ Iterator appsItr = apps.iterator();
+ //getting default app
+ while(appsItr.hasNext()){
+ UserApp tempUserApp = (UserApp)appsItr.next();
+ if(tempUserApp.getRole().getId().equals(roleId)){
+ appsItr.remove();
+ }
+ }
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public void addRole(Role role){
+ if(role!=null){
+ SortedSet<Role> roles = getRoles();
+ if(roles==null){
+ roles = new TreeSet();
+ }
+ roles.add(role);
+ setRoles(roles);
+ }
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+import java.util.Set;
+import java.util.TreeSet;
+
+// Generated Aug 27, 2014 5:51:36 PM by Hibernate Tools 3.4.0.CR1
+
+/**
+ * FnUserRole generated by hbm2java
+ */
+@SuppressWarnings("rawtypes")
+public class UserApp implements java.io.Serializable, Comparable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private Long userId;
+ private App app;
+ private Role role;
+ private Short priority;
+
+ public UserApp() {
+ }
+
+ public Long getUserId() {
+ return userId;
+ }
+
+ public void setUserId(Long userId) {
+ this.userId = userId;
+ }
+
+ public App getApp() {
+ return app;
+ }
+
+ public void setApp(App app) {
+ this.app = app;
+ }
+
+ public Role getRole() {
+ return role;
+ }
+
+ public void setRole(Role role) {
+ this.role = role;
+ }
+
+ public Short getPriority() {
+ return this.priority;
+ }
+
+ public void setPriority(Short priority) {
+ this.priority = priority;
+ }
+
+ public boolean equals(Object other) {
+ if ((this == other))
+ return true;
+ if ((other == null))
+ return false;
+ if (!(other instanceof UserApp))
+ return false;
+ UserApp castOther = (UserApp) other;
+
+ return (this.getUserId().equals(castOther.getUserId()))
+ && (this.getApp().getId().equals(castOther.getApp().getId()))
+ && (this.getRole().getId().equals(castOther.getRole().getId()))
+ && ((this.priority==null && castOther.getPriority()==null) || this.getPriority().equals(castOther.getPriority()));
+ }
+
+ public int hashCode() {
+ int result = 17;
+
+ result = 37 * result + (int) (this.getUserId()==null ? 0 : this.getUserId().intValue());
+ result = 37 * result + (int) (this.getApp().getId()==null ? 0 : this.getApp().getId().intValue());
+ result = 37 * result + (int) (this.getRole().getId()==null ? 0 : this.getRole().getId().intValue());
+ result = 37 * result + (int) (this.priority==null ? 0 : this.priority);
+ return result;
+ }
+
+ public int compareTo(Object other){
+ UserApp castOther = (UserApp) other;
+
+ Long c1 = (this.getUserId()==null ? 0 : this.getUserId()) + (this.getApp()==null||this.getApp().getId()==null ? 0 : this.getApp().getId()) + (this.getRole()==null||this.getRole().getId()==null ? 0 : this.getRole().getId()) + (this.priority==null ? 0 : this.priority);
+ Long c2 = (castOther.getUserId()==null ? 0 : castOther.getUserId()) + (castOther.getApp()==null||castOther.getApp().getId()==null ? 0 : castOther.getApp().getId()) + (castOther.getRole()==null||castOther.getRole().getId()==null ? 0 : castOther.getRole().getId()) + (castOther.priority==null ? 0 : castOther.priority);
+
+ return c1.compareTo(c2);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain;
+
+// Generated Aug 27, 2014 5:51:36 PM by Hibernate Tools 3.4.0.CR1
+
+/**
+ * FnUserRoleId generated by hbm2java
+ */
+public class UserAppId implements java.io.Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private Long userId;
+ private App app;
+ private Role role;
+
+ public UserAppId() {
+ super();
+ }
+
+ public Long getUserId() {
+ return userId;
+ }
+
+ public void setUserId(Long userId) {
+ this.userId = userId;
+ }
+
+ public App getApp() {
+ return app;
+ }
+
+ public void setApp(App app) {
+ this.app = app;
+ }
+
+ public Role getRole() {
+ return role;
+ }
+
+ public void setRole(Role role) {
+ this.role = role;
+ }
+
+ public boolean equals(Object other) {
+ if ((this == other))
+ return true;
+ if ((other == null))
+ return false;
+ if (!(other instanceof UserAppId))
+ return false;
+ UserAppId castOther = (UserAppId) other;
+
+ return (this.getUserId() == castOther.getUserId())
+ && (this.getApp().getId() == castOther.getApp().getId())
+ && (this.getRole().getId() == castOther.getRole().getId());
+ }
+
+ public int hashCode() {
+ int result = 17;
+
+ result = 37 * result + (int) (this.getUserId()==null ? 0 : this.getUserId().intValue());
+ result = 37 * result + (int) (this.getApp().getId()==null ? 0 : this.getApp().getId().intValue());
+ result = 37 * result + (int) (this.getRole().getId()==null ? 0 : this.getRole().getId().intValue());
+ return result;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.sessionmgt;
+
+public class TimeoutVO implements Comparable<TimeoutVO>{
+
+ private String jSessionId;
+ private Long sessionTimOutMilliSec;
+
+ public TimeoutVO(){
+
+ }
+
+ public TimeoutVO(String _jSessionId, Long _sessionTimOutMilliSec) {
+ setjSessionId(_jSessionId);
+ setSessionTimOutMilliSec(_sessionTimOutMilliSec);
+
+ }
+
+ public String getjSessionId() {
+ return jSessionId;
+ }
+
+ public void setjSessionId(String jSessionId) {
+ this.jSessionId = jSessionId;
+ }
+
+ public Long getSessionTimOutMilliSec() {
+ return sessionTimOutMilliSec;
+ }
+
+ public void setSessionTimOutMilliSec(Long sessionTimOutMilliSec) {
+ this.sessionTimOutMilliSec = sessionTimOutMilliSec;
+ }
+
+ @Override
+ public int compareTo(TimeoutVO o) {
+ return sessionTimOutMilliSec.compareTo(o.sessionTimOutMilliSec);
+ }
+
+
+
+
+
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.support;
+
+public class Attribute {
+ public double width;
+ public double top;
+ public double left;
+ public String name;
+ public double height;
+
+ public double getWidth() {
+ return width;
+ }
+ public void setWidth(double width) {
+ this.width = width;
+ }
+ public double getTop() {
+ return top;
+ }
+ public void setTop(double top) {
+ this.top = top;
+ }
+ public double getLeft() {
+ return left;
+ }
+ public void setLeft(double left) {
+ this.left = left;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public double getHeight() {
+ return height;
+ }
+ public void setHeight(double height) {
+ this.height = height;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.support;
+
+import java.io.Serializable;
+import java.util.HashSet;
+
+public class CollaborateList implements Serializable {
+
+ private static final long serialVersionUID = -4104440747626736243L;
+ private HashSet<String> userNameList = new HashSet<String>();
+ private static CollaborateList userListData = new CollaborateList();
+ private CollaborateList(){}
+
+ public static CollaborateList getInstance(){
+ return userListData;
+ }
+
+ public HashSet<String> getAllUserName(){
+ return userNameList;
+ }
+
+ public static void addUserName(String name){
+ final HashSet<String> allUserName = CollaborateList.getInstance().getAllUserName();
+ if(allUserName.contains(name)){
+ //System.out.println("cannot add this user");
+ }else{
+ allUserName.add(name);
+ }
+ }
+
+ public static void delUserName(String name){
+ final HashSet<String> allUserName = CollaborateList.getInstance().getAllUserName();
+ allUserName.remove((String) name);
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.support;
+
+import java.util.List;
+import java.util.Map;
+
+public class Container {
+
+ String id;
+
+ public String name;
+
+ Size size;
+
+ Position p;
+
+ public Map<String,Container> containerRowCol;
+
+ public Map<String,Element> elementRowCol;
+
+ int numOfRows;
+
+ int numOfCols;
+
+ double sum = 0;
+
+ double interEleWd;
+
+ double interEleH;
+
+ double interEleToContainerWd;
+
+ double interEleToContainerH;
+
+ double interEleToInnerContainerWd;
+
+ double interEleToInnerContainerH;
+
+ public double top;
+
+ public double left;
+
+ public double height;
+
+ public double width;
+
+ public String visibilityType;
+
+
+
+
+
+ public Container(String id, String name, int numOfRows, int numOfCols, double interEleWd, double interEleH,
+ double interEleToContainerWd, double interEleToContainerH, double interEleToInnerContainerWd,
+ double interEleToInnerContainerH) {
+
+ this.id = id;
+ this.name = name;
+ this.numOfRows = numOfRows;
+ this.numOfCols = numOfCols;
+ this.interEleWd = interEleWd;
+ this.interEleH = interEleH;
+ this.interEleToContainerWd = interEleToContainerWd;
+ this.interEleToContainerH = interEleToContainerH;
+ this.interEleToInnerContainerWd = interEleToInnerContainerWd;
+ this.interEleToInnerContainerH = interEleToInnerContainerH;
+
+ }
+
+
+ public List<Container> innerCList;
+
+ public List<Element> elementList;
+
+ public Container() {
+
+ }
+
+
+
+ public Map<String, Container> getContainerRowCol() {
+ return containerRowCol;
+ }
+
+
+
+
+ public Map<String, Element> getElementRowCol() {
+ return elementRowCol;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+ public void setInnerContainer(Map<String,Container> innerCon) {
+ containerRowCol = innerCon;
+ }
+
+ public void setElements(Map<String,Element> innerE) {
+ elementRowCol = innerE;
+ }
+
+
+ public Position getP() {
+ return p;
+ }
+
+ public void setP(Position p) {
+ this.p = p;
+ }
+
+
+ public void setTop(double top) {
+ this.top = top;
+ }
+
+
+ public void setLeft(double left) {
+ this.left = left;
+ }
+
+
+ public void setHeight(double height) {
+ this.height = height;
+ }
+
+
+ public void setWidth(double width) {
+ this.width = width;
+ }
+
+
+ public void setInnerCList(List<Container> innerCList) {
+ this.innerCList = innerCList;
+ }
+
+
+
+ public void setElementList(List<Element> elementList) {
+ this.elementList = elementList;
+ }
+
+ public void setVisibilityType(String visibilityType) {
+ this.visibilityType = visibilityType;
+ }
+
+ public Size computeSize() {
+ Size size = new Size();
+ double width = 0;
+ double height = 0;
+ // System.out.println("Inside computesize");
+ for (int i = 0; i<numOfRows; i++) {
+ if ((containerRowCol != null && containerRowCol.containsKey(i+String.valueOf(numOfCols-1))) ||
+ (elementRowCol!=null && elementRowCol.containsKey(i+String.valueOf(numOfCols-1)))) {
+ for (int j = 0; j < numOfCols; j++) {
+ if (containerRowCol!=null && containerRowCol.containsKey(i+String.valueOf(j))) {
+ width+=containerRowCol.get(i+String.valueOf(j)).computeSize().getWidth();
+ // System.out.println(containerRowCol.get(i+String.valueOf(j)).getName()+" "+
+ // containerRowCol.get(i+String.valueOf(j)).computeSize().getWidth());
+ }else if (elementRowCol!=null && elementRowCol.containsKey(i+String.valueOf(j)))
+ width+=elementRowCol.get(i+String.valueOf(j)).computeSize().getWidth();
+ }
+ break;
+ }
+ }
+ // System.out.println("Object name "+this.getName());
+ if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers")
+ || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") || this.getName().equals("Neo") || this.getName().equals("Support")) {
+ width+=(numOfCols-1)*interEleWd+2*interEleToInnerContainerWd;
+ } else {
+ width+=(numOfCols-1)*interEleWd+2*interEleToContainerWd;
+ }
+ size.setWidth(width);
+ for (int j = 0; j<numOfCols; j++) {
+ // System.out.println("Inside computesize height "+numOfCols);
+ // System.out.println(containerRowCol.toString());
+ if ((containerRowCol != null && containerRowCol.containsKey(String.valueOf(numOfRows-1)+j)) ||
+ (elementRowCol!= null && elementRowCol.containsKey(String.valueOf(numOfRows-1)+j))) {
+ //System.out.println("Inside if");
+ for (int i = 0; i < numOfRows; i++) {
+ if (containerRowCol!= null && containerRowCol.containsKey(i+String.valueOf(j))) {
+ height+=containerRowCol.get(i+String.valueOf(j)).computeSize().getHeight();
+ //System.out.println("My C name "+this.getName()+":"+containerRowCol.get(i+String.valueOf(j)).computeSize().getHeight());
+ }
+ else if (elementRowCol!=null && elementRowCol.containsKey(i+String.valueOf(j)))
+ height+=elementRowCol.get(String.valueOf(i)+String.valueOf(j)).computeSize().getHeight();
+ }
+ break;
+ }
+ }
+ if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers")
+ || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") || this.getName().equals("Neo") || this.getName().equals("Support")) {
+ height+=(numOfRows-1)*interEleH+2*interEleToInnerContainerH+0.1;
+ } else {
+ if (this.getName().equals("VoLTE UE") || this.getName().equals("3G UE") || this.getName().equals("HC UE-A")
+ || this.getName().equals("HC UE-B") || this.getName().equals("VNI UE") || this.getName().equals("PSTN")) {
+ height+=(numOfRows-1)*interEleH+interEleToContainerH/2;
+ }else
+ height+=(numOfRows-1)*interEleH+2*interEleToContainerH;
+ }
+ size.setHeight(height);
+ // System.out.println("C name "+this.getName()+" height "+height);
+ // System.out.println("test C height "+this.getName()+" height "+height+" (numOfRows-1)*interEleH "+(numOfRows-1)*interEleH+
+ // " interEleToContainerH "+interEleToContainerH/2);
+ return size;
+ }
+
+
+
+ public void computeElementPositions() {
+ double xsum = 0;
+ double ysum = 0;
+ for (int i=0; i<numOfRows; i++){
+ for (int j=0; j<numOfCols; j++){
+ if (containerRowCol != null && containerRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) {
+ Container c = containerRowCol.get(String.valueOf(i)+ String.valueOf(j));
+ Position p = new Position();
+ //System.out.println("within container");
+ p.x =j*interEleWd+xsum+this.getP().getX()+
+ interEleToContainerWd;
+ ysum = 0;
+ for (int k=0; k<i; k++) {
+ if (containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
+ ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
+ else if (elementRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
+ ysum+= elementRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
+ }
+ p.y = i*interEleH+ysum+this.getP().getY() + interEleToContainerH;
+ // containerCoord.add(c,p);
+ xsum+= c.computeSize().getWidth();
+ c.setP(p);
+
+ } else if (elementRowCol!=null && elementRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) {
+ Element e = elementRowCol.get(String.valueOf(i)+ String.valueOf(j));
+ Position p = new Position();
+ // System.out.println("i "+i+"j "+j);
+ // System.out.println("element "+e.getName());
+ // System.out.println("Is this "+this.getP());
+ if (j==numOfCols-1) {
+ for (int t=0; t<i; t++) {
+ if (containerRowCol!=null && containerRowCol.containsKey(String.valueOf(t)+ String.valueOf(j-1))) {
+ if (!elementRowCol.containsKey(String.valueOf(i)+ String.valueOf(j-1)) &&
+ !containerRowCol.containsKey(String.valueOf(i)+ String.valueOf(j-1))) {
+ xsum+=containerRowCol.get(String.valueOf(t)+ String.valueOf(j-1)).computeSize().getWidth();
+ break;
+ }
+ }
+ }
+ }
+ if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers")
+ || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider")
+ || this.getName().equals("Neo") || this.getName().equals("Support")) {
+ p.x = j*interEleWd+xsum+this.getP().getX()+interEleToInnerContainerWd;
+ }
+ else if (this.getName().equals("VNI UE") || this.getName().equals("PSTN") || this.getName().equals("3G UE")
+ || this.getName().equals("HC UE-A") || this.getName().equals("HC UE-B")) {
+ p.x = j*interEleWd+xsum+this.getP().getX()+interEleToContainerWd-0.8;
+ }else {
+ p.x = j*interEleWd+xsum+this.getP().getX()+interEleToContainerWd;
+ //System.out.println("element name "+e.getName()+" j*interEleWd "+j*interEleWd
+ // +" xsum " +xsum+"this.getP().getX() "+this.getP().getX()+" interEleToContainerWd " +interEleToContainerWd+" p.x "+p.x);
+ }
+ ysum = 0;
+ for (int k=0; k<i; k++) {
+ if (containerRowCol!= null && containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
+ ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
+ else if (elementRowCol!=null && elementRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
+ ysum+= elementRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
+ else if (containerRowCol!= null) {
+ for (int chk=j; chk>0; chk--) {
+ if (containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(chk-1))) {
+ if (containerRowCol.get(String.valueOf(k)+ String.valueOf(chk-1)).computeSize().getWidth()
+ + containerRowCol.get(String.valueOf(k)+ String.valueOf(chk-1)).getP().getX() > p.x) {
+ ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(chk-1)).computeSize().getHeight();
+ break;
+ }
+ }
+ }
+ }
+
+ }
+ if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers")
+ || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") || this.getName().equals("Neo") || this.getName().equals("Support")) {
+ p.y = this.getP().getY()+ysum+i*interEleH+interEleToInnerContainerH+1;
+ } else {
+ // System.out.println("element name "+e.getName()+" this.getP().getY() "+this.getP().getY()
+ // +" ysum " +ysum+" i*interEleH "+i*interEleH+" interEleToContainerH " +interEleToContainerH);
+ if (e.getName().equals("")) {
+ p.y = this.getP().getY()+ysum+i*interEleH+(interEleToContainerH);
+ //System.out.println("test element name "+this.getName()+" Container height "+this.computeSize().getHeight()+" this.getP().getY() "+this.getP().getY()
+ // +" ysum " +ysum+" i*interEleH "+i*interEleH+" interEleToContainerH-3 " +interEleToContainerH+" p.y "+p.y);
+ }else
+ p.y = this.getP().getY()+ysum+i*interEleH+interEleToContainerH;
+ // System.out.println(e.getName()+"My contain this.getP().getY() "+this.getP().getY()
+ // +"elements Y "+p.y);
+ }
+ xsum+= e.computeSize().getWidth();
+ e.setP(p);
+ //System.out.println("my element name "+e.getName()+" e.getP().getX() "+e.getP().getX());
+ //System.out.println();
+ }
+ }
+ xsum = 0;
+ }
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.support;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public class Domain {
+ // Unique identifier of the domain
+ String id;
+ // List<Container> cList;
+
+ public String name;
+ Size size;
+ Position p;
+
+ //Attribute1 at;
+
+ public Position getP() {
+ return p;
+ }
+
+ public void setP(Position p) {
+ this.p = p;
+ }
+
+ //Horizontal space between a pair of containers
+ double interContWd = 1.0;
+ //Vertical space between a pair of containers
+ double interContH;
+ double domainToLayoutWd;
+ double domainToContH;
+ double domainToLayoutH;
+ int numOfRowsofContainer;
+ int numOfColsofContainer;
+ boolean indexChanged;
+ Map<String,Container> containerRowCol;
+ public Domain(String id, String name, double interContWd, double interContH, double domainToLayoutWd,
+ double domainToLayoutH, double domainToContH, int numOfRowsofContainer, int numOfColsofContainer) {
+ this.id = id;
+ this.name = name;
+ this.interContWd = interContWd;
+ this.interContH = interContH;
+ this.domainToLayoutWd = domainToLayoutWd;
+ this.domainToLayoutH = domainToLayoutH;
+ this.domainToContH = domainToContH;
+ this.numOfRowsofContainer = numOfRowsofContainer;
+ this.numOfColsofContainer = numOfColsofContainer;
+ // at = new Attribute1();
+ }
+
+
+
+
+ public double top;
+
+ public double left;
+
+ public double height;
+
+ public double width;
+
+ public List<Container> containerList;
+
+ public double newXafterColl;
+
+ public double YafterColl;
+
+ public void setNewXafterColl(double newXafterColl) {
+ this.newXafterColl = newXafterColl;
+ }
+
+ public double getNewXafterColl() {
+ return newXafterColl;
+ }
+
+ public double getYafterColl() {
+ return YafterColl;
+ }
+
+ public void setYafterColl(double yafterColl) {
+ YafterColl = yafterColl;
+ }
+
+ public void setDomainToLayoutWd(double domainToLayoutWd) {
+ this.domainToLayoutWd = domainToLayoutWd;
+ }
+
+ public double getDomainToLayoutWd() {
+ return domainToLayoutWd;
+ }
+
+ public double getTop() {
+ return top;
+ }
+
+ public void setTop(double top) {
+ this.top = top;
+ }
+
+ public double getLeft() {
+ return left;
+ }
+
+ public void setLeft(double left) {
+ this.left = left;
+ }
+
+ public double getHeight() {
+ return height;
+ }
+
+ public void setHeight(double height) {
+ this.height = height;
+ }
+
+ public double getWidth() {
+ return width;
+ }
+
+ public void setWidth(double width) {
+ this.width = width;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setContainers(Map<String,Container> containerRowCol) {
+ this.containerRowCol = containerRowCol;
+ }
+
+ public Map<String, Container> getContainerRowCol() {
+ return containerRowCol;
+ }
+
+
+ /* public Attribute1 getAt() {
+ return at;
+ }
+
+ public void setAt(Attribute1 at) {
+ this.at = at;
+ }*/
+
+ public void setContainerList(List<Container> containerList) {
+ // new ArrayList<Container>();
+ this.containerList = containerList;
+ }
+
+
+
+/* public boolean isCollapsed() {
+ return collapsed;
+ }
+
+ public void setCollapsed(boolean collapsed) {
+ this.collapsed = collapsed;
+ }*/
+
+ public boolean isIndexChanged() {
+ return indexChanged;
+ }
+
+ public void setIndexChanged(boolean indexChanged) {
+ this.indexChanged = indexChanged;
+ }
+
+ //Compute the size of any domain
+ public Size computeSize() {
+ size = new Size();
+ size.setHeight(5);
+ double width = 0;
+ for (int i = 0; i < numOfRowsofContainer; i++) {
+ if (containerRowCol!=null && containerRowCol.containsKey(String.valueOf(i)+String.valueOf(numOfColsofContainer-1))) {
+ for (int j = 0; j < numOfColsofContainer; j++) {
+ width+=containerRowCol.get(String.valueOf(i)+String.valueOf(j)).computeSize().getWidth();
+ }
+ break;
+ }
+
+ }
+ width+=(numOfColsofContainer-1)*interContWd;
+ if (this.getName().equals("VNI"))
+ size.setWidth(width-4);
+ else
+ size.setWidth(width);
+ return size;
+ }
+
+ public void computeConatinerPositions() {
+
+ double xsum = 0;
+ double ysum = 0;
+ for (int i=0; i< numOfRowsofContainer; i++){
+ for (int j=0; j<numOfColsofContainer; j++){
+ if (containerRowCol!=null && containerRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) {
+ Container c = containerRowCol.get(String.valueOf(i)+ String.valueOf(j));
+ // System.out.println("container "+c.toString());
+ Position p = new Position();
+ if (this.getName().equals("VNI")) {
+ p.x = j*(interContWd-2)+xsum+domainToLayoutWd;
+ } else
+ p.x = j*interContWd+xsum+domainToLayoutWd;
+ // this.computeSize();
+ // p.x = j*interContWd+xsum+this.getP().getX();
+ ysum = 0;
+ for (int k=0; k<i; k++) {
+ // System.out.println("i value "+i);
+ if (containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
+ ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
+ // System.out.println("Container height "+containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).getName()+
+ // ":"+" "+containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight());
+ else if (j>0 && containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j-1)) &&
+ !containerRowCol.get(String.valueOf(i)+ String.valueOf(j)).getName().equals("AIC - Alpharetta")) {
+ ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j-1)).computeSize().getHeight();
+ }
+ }
+ //System.out.println("C name "+c.getName()+" ysum "+ysum+" domainToLayoutH "+domainToLayoutH+" this.computeSize().getHeight() "+
+ // this.computeSize().getHeight()+" domainToContH "+domainToContH+" interContH "+interContH);
+ p.y = domainToLayoutH+ysum+this.computeSize().getHeight()+
+ domainToContH+i*interContH;
+
+ c.setP(p);
+ xsum+= c.computeSize().getWidth();
+
+ }
+ }
+ xsum = 0;
+
+ }
+
+ }
+
+}
+
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.support;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.util.Date;
+import java.util.Set;
+
+import org.onap.portalsdk.core.domain.FusionVo;
+
+
+/* Super class from which all data objects descend */
+public class DomainVo extends FusionVo implements Serializable, Cloneable, Comparable {
+
+ protected Long id;
+ protected Date created;
+ protected Date modified;
+ protected Long createdId;
+ protected Long modifiedId;
+ protected Long rowNum;
+
+ protected Serializable auditUserId;
+
+ Set auditTrail = null;
+
+ public DomainVo() {}
+
+
+ public void setId(Long i) {
+ id = i;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ public void setModified(Date modified) {
+ this.modified = modified;
+ }
+
+ public void setCreatedId(Long createdId) {
+ this.createdId = createdId;
+ }
+
+ public void setModifiedId(Long modifiedId) {
+ this.modifiedId = modifiedId;
+ }
+
+ public void setAuditUserId(Serializable auditUserId) {
+ this.auditUserId = auditUserId;
+ }
+
+ public void setRowNum(Long rowNum) {
+ this.rowNum = rowNum;
+ }
+
+ public void setAuditTrail(Set auditTrail) {
+ this.auditTrail = auditTrail;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public Date getModified() {
+ return modified;
+ }
+
+ public Long getCreatedId() {
+ return createdId;
+ }
+
+ public Long getModifiedId() {
+ return modifiedId;
+ }
+
+ public Serializable getAuditUserId() {
+ return auditUserId;
+ }
+
+ public Long getRowNum() {
+ return rowNum;
+ }
+
+ public Set getAuditTrail() {
+ return auditTrail;
+ }
+
+
+ public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+
+
+ public Object copy() {
+ return copy(false);
+ }
+
+
+ public Object copy(boolean isIdNull) {
+ // let's create a "copy" of the object using serialization
+ ByteArrayOutputStream baos = null;
+ ByteArrayInputStream bais = null;
+ ObjectOutputStream oos = null;
+ ObjectInputStream ois = null;
+
+ DomainVo newVo = null;
+
+ try {
+
+ baos = new ByteArrayOutputStream();
+ oos = new ObjectOutputStream(baos);
+ oos.writeObject(this);
+
+ bais = new ByteArrayInputStream(baos.toByteArray());
+ ois = new ObjectInputStream(bais);
+ newVo = (DomainVo)ois.readObject();
+
+ if (isIdNull) {
+ newVo.setId(null);
+ }
+
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return newVo;
+ }
+
+
+
+ public int compareTo(Object obj){
+ Long c1 = getId();
+ Long c2 = ((DomainVo)obj).getId();
+
+ return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.support;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class Element {
+
+ public String id;
+ public String name;
+
+ public double top;
+
+ public double left;
+
+ public double height;
+
+ public String imgFileName;
+
+ public String borderType;
+
+ public String bgColor;
+
+ public ElementDetails details;
+
+ //public List<ElementDetails> details;
+
+
+ public void setBgColor(String bgColor) {
+ this.bgColor = bgColor;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public void setTop(double top) {
+ this.top = top;
+ }
+
+ public void setLeft(double left) {
+ this.left = left;
+ }
+
+ public void setHeight(double height) {
+ this.height = height;
+ }
+
+ public void setWidth(double width) {
+ this.width = width;
+ }
+
+
+ public double width;
+
+
+ public String getId() {
+ return id;
+ }
+
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+ Position p;
+
+ public Position getP() {
+ return p;
+ }
+
+ public void setP(Position p) {
+ this.p = p;
+ }
+
+
+
+ public Element(String id, String name, String imgPath, String bgColor, String logical_group, String display_longname,
+ String description, String primary_function, String key_interfaces, String location, String vendor, String vendor_shortname) {
+ this.id = id;
+ this.name = name;
+ this.imgFileName = imgPath;
+ this.bgColor = bgColor;
+
+
+ }
+
+ public Element(String id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ public Element(String id, String name, String imgFilename, String bgColor, String borderType, ElementDetails details) {
+ this.id = id;
+ this.name = name;
+ this.imgFileName = imgFilename;
+ this.bgColor = bgColor;
+ this.borderType = borderType;
+ this.details = details;
+
+ }
+
+
+ public void setBorderType(String borderType) {
+ this.borderType = borderType;
+ }
+
+ public String getImgFileName() {
+ return imgFileName;
+ }
+
+ public void setImgFileName(String imgFileName) {
+ this.imgFileName = imgFileName;
+ }
+
+ public String getBorderType() {
+ return borderType;
+ }
+
+
+
+ public ElementDetails getDetails() {
+ return details;
+ }
+
+
+
+ public void setDetails(ElementDetails details) {
+ this.details = details;
+ }
+
+ public Size computeSize() {
+ Size size= new Size();
+ size.setWidth(0.5*7.0);
+ size.setHeight(0.5*3.0);
+ // size.setWidth(0.5*10.0);
+ // size.setHeight(0.5*6.0);
+ return size;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.support;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class ElementDetails {
+ public String logical_group;
+ public String display_longname;
+ public String description;
+ public String primary_function;
+ public String network_function;
+ public String key_interfaces;
+ public String location;
+ public String vendor;
+ public String vendor_shortname;
+ public String enclosingContainer;
+
+
+// public Map<String,String> details1;
+
+// public ElementDetails(Map<String, String> details) {
+
+ // this.details = new HashMap<String, String>();
+ // this.details1 = details;
+// }
+
+
+
+
+
+ public ElementDetails(String logical_group, String display_longname, String description, String primary_function, String network_function,
+ String key_interfaces, String location, String vendor, String vendor_shortname, String enclosingContainer) {
+
+ this.logical_group = logical_group;
+ this.display_longname = display_longname;
+ this.description = description;
+ this.primary_function = primary_function;
+ this.network_function = network_function;
+ this.key_interfaces = key_interfaces;
+ this.location = location;
+ this.vendor = vendor;
+ this.vendor_shortname = vendor_shortname;
+ this.enclosingContainer = enclosingContainer;
+ }
+
+ public void setLogical_group(String logical_group) {
+ this.logical_group = logical_group;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.support;
+
+import org.onap.portalsdk.core.FusionObject;
+
+public class FusionCommand implements FusionObject {
+
+ private String task;
+
+ public FusionCommand() {
+ }
+
+ public String getTask() {
+ return task;
+ }
+
+ public void setTask(String task) {
+ this.task = task;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.support;
+
+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 java.util.TreeMap;
+
+public class Layout {
+ //width of the screen
+// double width;
+ //height of the screen;
+// double height;
+ // Total number of domains present on the screen and assume that
+
+ public Map<String,Domain> domainRowCol;
+
+ Map<String,Domain> originalDomainRowCol;
+
+ //Horizontal space between a pair of domains
+ double interDomainWd;
+ //Vertical space between a pair of domains
+ double interDomainH;
+ //Computing the co-ordinates of any domain
+ int numberofRowsofDomains;
+
+ int numberofColsofDomains;
+
+ Map<String, Domain> collapsedDomains;
+
+ List<Domain> collapsedDomainsNewList;
+
+ public List<Domain> getCollapsedDomainsNewList() {
+ return collapsedDomainsNewList;
+ }
+
+ public void setCollapsedDomainsNewList(List<Domain> collapsedDomainsNewList) {
+ this.collapsedDomainsNewList = collapsedDomainsNewList;
+ }
+
+ public void setCollapsedDomains(Map<String, Domain> collapsedDomains) {
+ this.collapsedDomains = collapsedDomains;
+ }
+
+ public Map<String, Domain> getCollapsedDomains() {
+ return collapsedDomains;
+ }
+
+ public int getNumberofColsofDomains() {
+ return numberofColsofDomains;
+ }
+
+ public void setNumberofColsofDomains(int numberofColsofDomains) {
+ this.numberofColsofDomains = numberofColsofDomains;
+ }
+
+ public Layout(Map<String,Domain> domainRowCol, double interDomainWd, double interDomainH,
+ int numberofRowsofDomains, int numberofColsofDomains) {
+
+ this.domainRowCol = domainRowCol;
+ this.interDomainWd = interDomainWd;
+ this.interDomainH = interDomainH;
+ this.numberofRowsofDomains = numberofRowsofDomains;
+ this.numberofColsofDomains = numberofColsofDomains;
+ this.collapsedDomains = new HashMap<String, Domain>();
+ this.originalDomainRowCol = new TreeMap<String,Domain>();
+ //nline
+ this.collapsedDomainsNewList = new ArrayList<Domain>();
+ }
+
+ public Map<String, Domain> getDomainRowCol() {
+ return domainRowCol;
+ }
+
+ public void setDomainRowCol(Map<String, Domain> domainRowCol) {
+ this.domainRowCol = domainRowCol;
+ }
+
+
+ public void computeDomainPositions() {
+ double xsum = 0;
+ double domainTolayout = 10.6;
+ for (int i=0; i< numberofRowsofDomains; i++){
+ for (int j=0; j<numberofColsofDomains; j++){
+ if (domainRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) {
+ Domain d = domainRowCol.get(String.valueOf(i)+ String.valueOf(j));
+ Position p = new Position();
+ if (j==0)
+ //p.x = (j+1)* (interDomainWd+2.6) + xsum;
+ p.x = domainTolayout;
+ else
+ // p.x = (j+1)* interDomainWd + xsum;
+ p.x = j*interDomainWd + xsum + domainTolayout;
+ if (getCollapsedDomainsNewList().size() > 0)
+ p.x+= accountForPlusSpaceBefore(d);
+ xsum+=d.computeSize().getWidth();
+ double ysum=0;
+ for (int k=0; k<i; k++) {
+ if (domainRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
+ ysum+= domainRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
+ }
+ // p.y = domainToLayoutH+ysum+this.computeSize().getHeight()+
+ // domainToContH+i*interContH;
+ p.y = (i+1)* interDomainH + ysum;
+ d.setP(p);
+
+ }
+ }
+ xsum = 0;
+ }
+ }
+
+ public void computeDomainPositionsModified() {
+ //double xsum = 0;
+ // double domainTolayout = 10.6;
+ for (int i=0; i< numberofRowsofDomains; i++){
+ for (int j=0; j<numberofColsofDomains; j++){
+ if (domainRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) {
+ Domain d = domainRowCol.get(String.valueOf(i)+ String.valueOf(j));
+ Position p = new Position();
+ Map<String,Container> enclosedContainers = d.getContainerRowCol();
+ for (Map.Entry<String, Container> entry : enclosedContainers.entrySet()) {
+ if (entry.getKey().equals("00")) {
+ double containerX = entry.getValue().getP().getX();
+ p.x = containerX;
+ double ysum=0;
+ for (int k=0; k<i; k++) {
+ if (domainRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
+ ysum+= domainRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
+ }
+ p.y = (i+1)* interDomainH + ysum;
+ d.setP(p);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+
+ }
+ public Layout collapseDomainModified(String domainsToCollapse) {
+
+ if(domainsToCollapse == null || domainsToCollapse.isEmpty())
+ return null;
+
+ Map<String,Domain> updatedRC = new HashMap<String, Domain>();
+
+ for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) {
+ updatedRC.put(copyEntry.getKey(), copyEntry.getValue());
+ // System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
+ }
+
+ Map<String, Domain> updatedRCSorted = new TreeMap<String, Domain>(updatedRC);
+
+ Map<String, Domain> collapsedDomainMap = getCollapsedDomains();
+
+ List<Domain> collapsedDomainNewL = getCollapsedDomainsNewList();
+
+
+ if (collapsedDomainNewL.size() == 0) {
+ for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) {
+ originalDomainRowCol.put(copyEntry.getKey(), copyEntry.getValue());
+ // System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
+ }
+ }
+
+
+ Map<String, Domain> updatedRCSortedTrunc = new TreeMap<String, Domain>();
+
+ int colToDelete = 0;
+ for (Map.Entry<String, Domain> entry : updatedRCSorted.entrySet()) {
+ if (entry.getValue().getName().equals(domainsToCollapse)) {
+ if (entry.getValue().isIndexChanged()) {
+ collapsedDomainMap.put("0"+String.valueOf(Integer.parseInt(entry.getKey())+1), entry.getValue());
+
+ }
+ //Domain toRemove = entry.getValue();
+ else {
+ collapsedDomainMap.put(entry.getKey(),entry.getValue());
+ }
+
+ collapsedDomainNewL.add(entry.getValue());
+ setNumberofColsofDomains(getNumberofColsofDomains()-1);
+ updatedRC.remove(entry.getKey());
+ colToDelete = Character.getNumericValue(entry.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+
+
+ for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) {
+ updatedRCSortedTrunc.put(copyEntry.getKey(), copyEntry.getValue());
+ //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
+ }
+
+ for (Map.Entry<String, Domain> rmv : updatedRCSorted.entrySet()) {
+ if (Character.getNumericValue(rmv.getKey().toCharArray()[1]) <= colToDelete) {
+ updatedRCSortedTrunc.remove(rmv.getKey());
+ }
+ }
+
+
+ /* for (Map.Entry<String, Domain> entry : updatedRCSortedTrunc.entrySet()) {
+ System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
+ }*/
+
+ for (Map.Entry<String, Domain> updateOthers : updatedRCSortedTrunc.entrySet()) {
+ char update[] = updateOthers.getKey().toCharArray();
+ int charToupdate = Character.getNumericValue(update[1]);
+ --charToupdate;
+ String resultRowCol = String.valueOf(update[0])+String.valueOf(charToupdate);
+ updateOthers.getValue().setIndexChanged(true);
+ updatedRC.put(resultRowCol, updateOthers.getValue());
+ updatedRC.remove(updateOthers.getKey());
+
+ }
+ setDomainRowCol(updatedRC);
+
+ /* for (Map.Entry<String, Domain> entry : updatedRC.entrySet()) {
+ System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
+ }*/
+
+ double currDistFromLftM = 11.0;
+ int orgColofCollapsedd = -1;
+ int orgColofDisplayedd = -1;
+ for (Map.Entry<String,Domain> cd : updatedRC.entrySet()) {
+ /*for (Domain pl : collapsedDomainNewL) {
+ for (Map.Entry<String, Domain> colCheck : originalDomainRowCol.entrySet()) {
+ if (colCheck.getValue().getName().equals(pl.getName())) {
+ orgColofCollapsedd = Character.getNumericValue(colCheck.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+
+ for (Map.Entry<String, Domain> colCheckk : originalDomainRowCol.entrySet()) {
+ if (colCheckk.getValue().getName().equals(cd.getValue().getName())) {
+ orgColofDisplayedd = Character.getNumericValue(colCheckk.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+
+ if (orgColofCollapsedd < orgColofDisplayedd) {
+ currDistFromLftM+= 3;
+ }
+ }*/
+ Domain d = cd.getValue();
+ double accountPlus = accountForPlusSpaceBefore(d);
+ // currDistFromLftM+= accountForPlusSpaceBefore(d);
+ d.setDomainToLayoutWd(currDistFromLftM+accountPlus);
+ d.computeConatinerPositions();
+ for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
+ Container c = entry1.getValue();
+ c.computeSize();
+ c.computeElementPositions();
+ if (c.getContainerRowCol() != null) {
+ for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
+ Container inner = entryInner.getValue();
+ inner.computeElementPositions();
+ }
+ }
+ }
+ currDistFromLftM += d.computeSize().getWidth()+2;
+
+ }
+
+
+
+
+ //nline
+ // Insert method invocation
+ updatePlusPosition(collapsedDomainNewL, updatedRC);
+
+ //order changed
+ setCollapsedDomains(collapsedDomainMap);
+ setCollapsedDomainsNewList(collapsedDomainNewL);
+
+
+ computeDomainPositionsModified();
+ return this;
+ }
+
+
+
+ public Layout collapseDomainNew(String domainsToCollapse) {
+
+ if(domainsToCollapse == null || domainsToCollapse.isEmpty())
+ return null;
+
+ Map<String,Domain> updatedRC = new HashMap<String, Domain>();
+
+ for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) {
+ updatedRC.put(copyEntry.getKey(), copyEntry.getValue());
+ //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
+ }
+
+ Map<String, Domain> updatedRCSorted = new TreeMap<String, Domain>(updatedRC);
+
+ Map<String, Domain> collapsedDomainMap = getCollapsedDomains();
+
+ List<Domain> collapsedDomainNewL = getCollapsedDomainsNewList();
+
+
+ if (collapsedDomainNewL.size() == 0) {
+ for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) {
+ originalDomainRowCol.put(copyEntry.getKey(), copyEntry.getValue());
+ // System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
+ }
+ }
+
+
+ Map<String, Domain> updatedRCSortedTrunc = new TreeMap<String, Domain>();
+
+ int colToDelete = 0;
+ for (Map.Entry<String, Domain> entry : updatedRCSorted.entrySet()) {
+ if (entry.getValue().getName().equals(domainsToCollapse)) {
+ if (entry.getValue().isIndexChanged()) {
+ collapsedDomainMap.put("0"+String.valueOf(Integer.parseInt(entry.getKey())+1), entry.getValue());
+
+ }
+ //Domain toRemove = entry.getValue();
+ else {
+ collapsedDomainMap.put(entry.getKey(),entry.getValue());
+ }
+
+ collapsedDomainNewL.add(entry.getValue());
+ setNumberofColsofDomains(getNumberofColsofDomains()-1);
+ updatedRC.remove(entry.getKey());
+ colToDelete = Character.getNumericValue(entry.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+
+
+ for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) {
+ updatedRCSortedTrunc.put(copyEntry.getKey(), copyEntry.getValue());
+ //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
+ }
+
+ for (Map.Entry<String, Domain> rmv : updatedRCSorted.entrySet()) {
+ if (Character.getNumericValue(rmv.getKey().toCharArray()[1]) <= colToDelete) {
+ updatedRCSortedTrunc.remove(rmv.getKey());
+ }
+ }
+
+
+ /* for (Map.Entry<String, Domain> entry : updatedRCSortedTrunc.entrySet()) {
+ System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
+ }*/
+
+ for (Map.Entry<String, Domain> updateOthers : updatedRCSortedTrunc.entrySet()) {
+ char update[] = updateOthers.getKey().toCharArray();
+ int charToupdate = Character.getNumericValue(update[1]);
+ --charToupdate;
+ String resultRowCol = String.valueOf(update[0])+String.valueOf(charToupdate);
+ updateOthers.getValue().setIndexChanged(true);
+ updatedRC.put(resultRowCol, updateOthers.getValue());
+ updatedRC.remove(updateOthers.getKey());
+
+ }
+ setDomainRowCol(updatedRC);
+
+ double currDistFromLftM = 11.0;
+
+ boolean isDisplayed;
+ for (Map.Entry<String,Domain> orgEntry : originalDomainRowCol.entrySet()) {
+ isDisplayed = false;
+ for (Map.Entry<String,Domain> cd : updatedRC.entrySet()) {
+ if (cd.getValue().getName().equals(orgEntry.getValue().getName())) {
+ Domain d = cd.getValue();
+ d.setDomainToLayoutWd(currDistFromLftM);
+ d.computeConatinerPositions();
+ for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
+ Container c = entry1.getValue();
+ c.computeSize();
+ c.computeElementPositions();
+ if (c.getContainerRowCol() != null) {
+ for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
+ Container inner = entryInner.getValue();
+ inner.computeElementPositions();
+ }
+ }
+ }
+ currDistFromLftM += d.computeSize().getWidth()+1;
+ isDisplayed = true;
+ break;
+ }
+ }
+
+ if (!isDisplayed) {
+ Domain myCollapsed = orgEntry.getValue();
+ myCollapsed.setNewXafterColl(currDistFromLftM);
+ myCollapsed.setYafterColl(myCollapsed.getP().getY());
+ currDistFromLftM += 4;
+ }
+ }
+
+ setCollapsedDomains(collapsedDomainMap);
+ setCollapsedDomainsNewList(collapsedDomainNewL);
+
+
+ computeDomainPositionsModified();
+ return this;
+
+ }
+
+
+ public Layout collapseDomain(String domainsToCollapse) {
+
+ Map<String,Domain> updatedRC = new HashMap<String, Domain>();
+
+ for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) {
+ updatedRC.put(copyEntry.getKey(), copyEntry.getValue());
+ //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
+ }
+
+ Map<String, Domain> updatedRCSorted = new TreeMap<String, Domain>(updatedRC);
+
+ Map<String, Domain> collapsedDomainMap = getCollapsedDomains();
+
+ if (collapsedDomainMap.size() == 0) {
+ for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) {
+ originalDomainRowCol.put(copyEntry.getKey(), copyEntry.getValue());
+ // System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
+ }
+ }
+
+
+ // List<Domain> collapsedDomainsList = getCollapsedDomains();
+
+ /* for (Map.Entry<String, Domain> entry : updatedRCSorted.entrySet()) {
+ System.out.println("Sorted Key: "+entry.getKey());
+ }*/
+
+ double prevDomXCordinate = 0.0;
+ Map<String, Domain> updatedRCSortedTrunc = new TreeMap<String, Domain>();
+ // for (String dToCollapse : domainsToCollapse) {
+ int colToDelete = 0;
+ for (Map.Entry<String, Domain> entry : updatedRCSorted.entrySet()) {
+ if (entry.getValue().getName().equals(domainsToCollapse)) {
+ if (entry.getValue().isIndexChanged())
+ collapsedDomainMap.put("0"+String.valueOf(Integer.parseInt(entry.getKey())+1), entry.getValue());
+ //Domain toRemove = entry.getValue();
+ else
+ collapsedDomainMap.put(entry.getKey(),entry.getValue());
+ prevDomXCordinate = entry.getValue().getP().getX();
+ entry.getValue().getP().setX(prevDomXCordinate-2);
+ // toRemove.setCollapsed(true);
+ setNumberofColsofDomains(getNumberofColsofDomains()-1);
+ updatedRC.remove(entry.getKey());
+ colToDelete = Character.getNumericValue(entry.getKey().toCharArray()[1]);
+ // collapsedDomainList.put(entry.getKey(),entry.getValue());
+ break;
+ }
+ }
+
+ /* for (Map.Entry<String, Domain> entry : updatedRC.entrySet()) {
+ System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
+ }*/
+
+ setCollapsedDomains(collapsedDomainMap);
+
+ for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) {
+ updatedRCSortedTrunc.put(copyEntry.getKey(), copyEntry.getValue());
+ //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
+ }
+
+ for (Map.Entry<String, Domain> rmv : updatedRCSorted.entrySet()) {
+ if (Character.getNumericValue(rmv.getKey().toCharArray()[1]) <= colToDelete) {
+ updatedRCSortedTrunc.remove(rmv.getKey());
+ }
+ }
+
+
+ /* for (Map.Entry<String, Domain> entry : updatedRCSortedTrunc.entrySet()) {
+ System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
+ }*/
+
+ for (Map.Entry<String, Domain> updateOthers : updatedRCSortedTrunc.entrySet()) {
+ // if (!updateOthers.getValue().getName().equals(dToCollapse)) {
+ // if ((int)updateOthers.getKey().toCharArray()[1] > colToDelete) {
+ char update[] = updateOthers.getKey().toCharArray();
+ int charToupdate = Character.getNumericValue(update[1]);
+ --charToupdate;
+ String resultRowCol = String.valueOf(update[0])+String.valueOf(charToupdate);
+ // update[1] = (char)charToupdate;
+ // updatedRC.put(String.valueOf(update), updateOthers.getValue());
+ updateOthers.getValue().setIndexChanged(true);
+ updatedRC.put(resultRowCol, updateOthers.getValue());
+ updatedRC.remove(updateOthers.getKey());
+ // }
+ // }
+ }
+
+ // }
+ setDomainRowCol(updatedRC);
+
+
+
+ for (Map.Entry<String, Domain> entry : updatedRCSortedTrunc.entrySet()) {
+ Domain d = entry.getValue();
+ // if (d.getName().equals("Datacenter with AIC") || d.getName().equals("VNI")) {
+ // d.setDomainToLayoutWd(d.getDomainToLayoutWd()-33);
+ if (collapsedDomains.size() == 2 && collapsedDomains.containsKey("00") && collapsedDomains.containsKey("01") && domainsToCollapse.equals("RAN")) {
+ if (d.getName().equals("USP"))
+ d.setDomainToLayoutWd(prevDomXCordinate);
+ else if (d.getName().equals("VNI"))
+ d.setDomainToLayoutWd(prevDomXCordinate+8);
+ else
+ d.setDomainToLayoutWd(prevDomXCordinate+10);
+ //System.out.println("Inside RAN EPC");
+ }
+ else if (domainsToCollapse.equals("RAN") && !d.getName().equals("EPC") && collapsedDomains.size() < 3)
+ d.setDomainToLayoutWd(prevDomXCordinate+11);
+ else if (domainsToCollapse.equals("RAN") && collapsedDomains.size() == 3 && collapsedDomains.containsKey("01") && collapsedDomains.containsKey("04")) {
+ if (d.getName().equals("USP"))
+ d.setDomainToLayoutWd(prevDomXCordinate);
+ else
+ d.setDomainToLayoutWd(prevDomXCordinate+10);
+ }
+
+ else if (collapsedDomains.containsKey("00") && collapsedDomains.size() == 3 && collapsedDomains.containsKey("01") && collapsedDomains.containsKey("02")) {
+ //System.out.println("Inside test");
+ if (d.getName().equals("VNI"))
+ d.setDomainToLayoutWd(prevDomXCordinate+10);
+ else
+ d.setDomainToLayoutWd(prevDomXCordinate);
+
+ }
+
+ else if (collapsedDomains.containsKey("00") && collapsedDomains.size() == 3 && collapsedDomains.containsKey("01") && collapsedDomains.containsKey("03")) {
+ //System.out.println("Inside test");
+ if (d.getName().equals("VNI"))
+ d.setDomainToLayoutWd(prevDomXCordinate+10);
+ else
+ d.setDomainToLayoutWd(prevDomXCordinate);
+
+ }
+
+
+
+ else {
+ d.setDomainToLayoutWd(prevDomXCordinate);
+ }
+ d.computeConatinerPositions();
+ prevDomXCordinate = d.getP().getX();
+ for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
+ Container c = entry1.getValue();
+ c.computeSize();
+ c.computeElementPositions();
+ if (c.getContainerRowCol() != null) {
+ for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
+ Container inner = entryInner.getValue();
+ inner.computeElementPositions();
+ }
+ }
+ }
+ // }
+ // System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
+ }
+ // setNumberofColsofDomains(getNumberofColsofDomains()-1);
+ computeDomainPositions();
+ return this;
+ /* CoordinateMain cm = new CoordinateMain();
+ try {
+ cm.convertToYAML(this);
+ } catch (Exception e) {
+
+ }*/
+
+ }
+
+ public Layout uncollapseDomainModified(String domainToUnCollapse) {
+ Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol);
+ Map<String, Domain> updateDomains = new TreeMap<String,Domain>();
+ Map<String, Domain> collapsedDomainList = getCollapsedDomains();
+ Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList);
+
+ List<Domain> domainstoUpd = new ArrayList<Domain>();
+
+ int colToUnCollapse = 99;
+
+ Domain domainToInsert = null;
+
+ if (collapsedDomains.size() == 0) {
+ for (Map.Entry<String, Domain> unindexDomain : originalDomainRowCol.entrySet()) {
+ Domain dm = unindexDomain.getValue();
+ dm.setIndexChanged(false);
+ }
+ }
+
+
+ for (Map.Entry<String, Domain> entry : collapsedDomainListSorted.entrySet()) {
+ if (entry.getValue().getName().equals(domainToUnCollapse)) {
+ colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]);
+ domainToInsert = entry.getValue();
+ collapsedDomainList.remove(entry.getKey());
+ break;
+ }
+ }
+
+ domainstoUpd.add(domainToInsert);
+
+ //for (Map.Entry<String, Domain> e : originalDomainRowCol.entrySet())
+ // System.out.println("Original key value"+e.getKey()+":"+e.getValue().getName());
+
+ int lastKeyCol = -1;
+ for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) {
+ int currcol = Character.getNumericValue(entry.getKey().toCharArray()[1]);
+ if (currcol < colToUnCollapse) {
+ for (Map.Entry<String, Domain> currDomainsEntry : currentDomainsSorted.entrySet()) {
+ if (currDomainsEntry.getValue().getName().equals(entry.getValue().getName())) {
+ updateDomains.put(currDomainsEntry.getKey(), currDomainsEntry.getValue());
+ lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+ } else {
+ String newKey = "0"+String.valueOf(lastKeyCol+1);
+ if (currcol == colToUnCollapse) {
+ updateDomains.put(newKey, domainToInsert);
+ ++lastKeyCol;
+ } else {
+ for (Map.Entry<String, Domain> currDomainsEnt : currentDomainsSorted.entrySet()) {
+ if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) {
+ updateDomains.put(newKey, currDomainsEnt.getValue());
+ domainstoUpd.add(currDomainsEnt.getValue());
+ ++lastKeyCol;
+ // lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+ }
+
+ }
+ }
+
+ setNumberofColsofDomains(getNumberofColsofDomains()+1);
+ setDomainRowCol(updateDomains);
+ setCollapsedDomains(collapsedDomainList);
+
+ //for (Map.Entry<String, Domain> e : updateDomains.entrySet())
+ // System.out.println("me Updatedomains key value"+e.getKey()+":"+e.getValue().getName());
+
+ // for (int i = 1; i < domainstoUpd.size(); i++) {
+ for (int i = 0; i < domainstoUpd.size(); i++) {
+ Domain d = domainstoUpd.get(i);
+ double newX = 0.0;
+ if (i+1 < domainstoUpd.size())
+ // newX = domainstoUpd.get(i-1).getP().getX()+domainstoUpd.get(i-1).computeSize().getWidth()+5;
+ newX = domainstoUpd.get(i+1).getP().getX();
+ //d.setDomainToLayoutWd(domainstoUpd.get(i+1).getP().getX());
+ else
+ newX = domainstoUpd.get(i).getP().getX()+32;
+ // d.setDomainToLayoutWd(domainstoUpd.get(i).getP().getX()+38);
+ /* if (i > 0) {
+ if (d.getWidth() < domainstoUpd.get(i-1).getWidth())
+ newX+= domainstoUpd.get(i-1).getWidth() - d.getWidth();
+ else if (d.getWidth() > domainstoUpd.get(i-1).getWidth())
+ newX-= d.getWidth() - domainstoUpd.get(i-1).getWidth() ;
+ } else {
+ if (d.getWidth() < domainInserted.getWidth())
+ newX+= domainInserted.getWidth() - d.getWidth();
+ else if (d.getWidth() > domainInserted.getWidth())
+ newX-= d.getWidth() - domainInserted.getWidth() ;
+ }*/
+ if (d.getName().equals("Datacenter with AIC"))
+ newX+= 2;
+ d.setDomainToLayoutWd(newX);
+ /* if (i == 0)
+ d.setDomainToLayoutWd(domainInserted.getP().getX()+domainInserted.getWidth());
+ else
+ d.setDomainToLayoutWd(domainstoUpd.get(i-1).getP().getX()+domainstoUpd.get(i-1).getWidth());*/
+ d.computeConatinerPositions();
+ for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
+ Container c = entry1.getValue();
+ c.computeSize();
+ c.computeElementPositions();
+ if (c.getContainerRowCol() != null) {
+ for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
+ Container inner = entryInner.getValue();
+ inner.computeElementPositions();
+ }
+ }
+ }
+ // }
+ // System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
+ }
+
+ computeDomainPositions();
+ return this;
+
+ }
+
+
+
+ public Layout uncollapseDomain(String domainToCollapse) {
+ Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol);
+ Map<String, Domain> updateDomains = new TreeMap<String,Domain>();
+ Map<String, Domain> collapsedDomainList = getCollapsedDomains();
+ Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList);
+
+ List<Domain> domainstoUpd = new ArrayList<Domain>();
+ /* for (Map.Entry<String, Domain> entry : collapsedDomainListSorted.entrySet()) {
+ if (entry.getValue().getName().equals("domainToCollapse")) {
+ if (currentDomainsSorted != null) {
+ if (!currentDomainsSorted.containsKey(entry.getKey())) {
+ updateDomains.put(entry.getKey(), entry.getValue());
+ collapsedDomainList.remove(entry.getKey());
+ break;
+ } else {
+ int colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]);
+ for (Map.Entry<String, Domain> curr : currentDomainsSorted.entrySet()) {
+ if (Character.getNumericValue(curr.getKey().toCharArray()[1]) < colToUnCollapse) {
+ updateDomains.put(curr.getKey(),curr.getValue());
+ } else {
+ updateDomains.put(curr.getKey()+1,curr.getValue());
+
+ }
+ }
+ updateDomains.put(entry.getKey(), entry.getValue());
+ }
+ }
+
+
+ }
+ }*/
+
+ Domain domainInserted = null;
+ for (Map.Entry<String, Domain> entry : collapsedDomainListSorted.entrySet()) {
+ if (entry.getValue().getName().equals(domainToCollapse)) {
+ domainInserted = entry.getValue();
+ if (currentDomainsSorted != null) {
+ int colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]);
+ for (Map.Entry<String, Domain> curr : currentDomainsSorted.entrySet()) {
+ if (Character.getNumericValue(curr.getKey().toCharArray()[1]) < colToUnCollapse) {
+ updateDomains.put(curr.getKey(),curr.getValue());
+ } else {
+ updateDomains.put("0"+String.valueOf(Integer.parseInt(curr.getKey())+1),curr.getValue());
+ domainstoUpd.add(curr.getValue());
+ }
+ }
+ }
+ updateDomains.put(entry.getKey(), entry.getValue());
+ collapsedDomainList.remove(entry.getKey());
+ break;
+
+ }
+ }
+ setNumberofColsofDomains(getNumberofColsofDomains()+1);
+ setDomainRowCol(updateDomains);
+ setCollapsedDomains(collapsedDomainList);
+
+ //for (Map.Entry<String, Domain> e : updateDomains.entrySet())
+ // System.out.println("Updatedomains key value"+e.getKey()+":"+e.getValue().getName());
+
+
+ for (int i = 0; i < domainstoUpd.size(); i++) {
+ Domain d = domainstoUpd.get(i);
+ double newX = 0.0;
+ if (i+1 < domainstoUpd.size())
+ newX = domainstoUpd.get(i+1).getP().getX();
+ //d.setDomainToLayoutWd(domainstoUpd.get(i+1).getP().getX());
+ else
+ newX = domainstoUpd.get(i).getP().getX()+38;
+ // d.setDomainToLayoutWd(domainstoUpd.get(i).getP().getX()+38);
+ /* if (i > 0) {
+ if (d.getWidth() < domainstoUpd.get(i-1).getWidth())
+ newX+= domainstoUpd.get(i-1).getWidth() - d.getWidth();
+ else if (d.getWidth() > domainstoUpd.get(i-1).getWidth())
+ newX-= d.getWidth() - domainstoUpd.get(i-1).getWidth() ;
+ } else {
+ if (d.getWidth() < domainInserted.getWidth())
+ newX+= domainInserted.getWidth() - d.getWidth();
+ else if (d.getWidth() > domainInserted.getWidth())
+ newX-= d.getWidth() - domainInserted.getWidth() ;
+ }*/
+ if (d.getName().equals("Datacenter with AIC"))
+ newX+= 5;
+ d.setDomainToLayoutWd(newX);
+ /* if (i == 0)
+ d.setDomainToLayoutWd(domainInserted.getP().getX()+domainInserted.getWidth());
+ else
+ d.setDomainToLayoutWd(domainstoUpd.get(i-1).getP().getX()+domainstoUpd.get(i-1).getWidth());*/
+ d.computeConatinerPositions();
+ for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
+ Container c = entry1.getValue();
+ c.computeSize();
+ c.computeElementPositions();
+ if (c.getContainerRowCol() != null) {
+ for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
+ Container inner = entryInner.getValue();
+ inner.computeElementPositions();
+ }
+ }
+ }
+ // }
+ // System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
+ }
+
+ computeDomainPositions();
+ return this;
+ }
+
+ public Layout uncollapseDomainNew(String domainToUnCollapse) {
+ Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol);
+ Map<String, Domain> updateDomains = new TreeMap<String,Domain>();
+ Map<String, Domain> collapsedDomainList = getCollapsedDomains();
+ Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList);
+
+ List<Domain> domainstoUpd = new ArrayList<Domain>();
+
+ //nline
+ List<Domain> collapsedDomainNewLL = getCollapsedDomainsNewList();
+
+ int colToUnCollapse = 99;
+
+ Domain domainToInsert = null;
+
+ //nline
+ // if (collapsedDomains.size() == 0) {
+ if (collapsedDomainNewLL.size() == 0) {
+ for (Map.Entry<String, Domain> unindexDomain : originalDomainRowCol.entrySet()) {
+ Domain dm = unindexDomain.getValue();
+ dm.setIndexChanged(false);
+ }
+ }
+
+
+ for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) {
+ if (entry.getValue().getName().equals(domainToUnCollapse)) {
+ colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]);
+ domainToInsert = entry.getValue();
+ collapsedDomainList.remove(entry.getKey());
+ //nline
+ collapsedDomainNewLL.remove(entry.getValue());
+ break;
+ }
+ }
+
+ domainstoUpd.add(domainToInsert);
+
+ // for (Map.Entry<String, Domain> e : originalDomainRowCol.entrySet())
+ // System.out.println("Original key value"+e.getKey()+":"+e.getValue().getName());
+
+ int lastKeyCol = -1;
+ for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) {
+ int currcol = Character.getNumericValue(entry.getKey().toCharArray()[1]);
+ if (currcol < colToUnCollapse) {
+ for (Map.Entry<String, Domain> currDomainsEntry : currentDomainsSorted.entrySet()) {
+ if (currDomainsEntry.getValue().getName().equals(entry.getValue().getName())) {
+ updateDomains.put(currDomainsEntry.getKey(), currDomainsEntry.getValue());
+ lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+ } else {
+ String newKey = "0"+String.valueOf(lastKeyCol+1);
+ if (currcol == colToUnCollapse) {
+ updateDomains.put(newKey, domainToInsert);
+ ++lastKeyCol;
+ } else {
+ for (Map.Entry<String, Domain> currDomainsEnt : currentDomainsSorted.entrySet()) {
+ if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) {
+ updateDomains.put(newKey, currDomainsEnt.getValue());
+ domainstoUpd.add(currDomainsEnt.getValue());
+ ++lastKeyCol;
+ // lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+ }
+
+ }
+ }
+
+ setNumberofColsofDomains(getNumberofColsofDomains()+1);
+ setDomainRowCol(updateDomains);
+
+ //for (Map.Entry<String, Domain> e : updateDomains.entrySet())
+ // System.out.println("me Updatedomains key value"+e.getKey()+":"+e.getValue().getName());
+
+
+
+ double currDistFromLftMargin = 11.0;
+ for (Map.Entry<String,Domain> cd : updateDomains.entrySet()) {
+ Domain d = cd.getValue();
+ double accountPlus = accountForPlusSpaceBefore(d);
+ d.setDomainToLayoutWd(currDistFromLftMargin+accountPlus);
+ d.computeConatinerPositions();
+ for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
+ Container c = entry1.getValue();
+ c.computeSize();
+ c.computeElementPositions();
+ if (c.getContainerRowCol() != null) {
+ for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
+ Container inner = entryInner.getValue();
+ inner.computeElementPositions();
+ }
+ }
+ }
+ currDistFromLftMargin += d.computeSize().getWidth()+2;
+
+ }
+
+ //nline
+ updatePlusPosition(collapsedDomainNewLL, updateDomains);
+
+ //order changed
+ setCollapsedDomains(collapsedDomainList);
+
+ //nline
+ setCollapsedDomainsNewList(collapsedDomainNewLL);
+
+
+ computeDomainPositionsModified();
+ return this;
+
+ }
+
+ public Layout uncollapseDomainNew1(String domainToUnCollapse) {
+
+ if(domainToUnCollapse == null || domainToUnCollapse.isEmpty())
+ return null;
+
+ Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol);
+ Map<String, Domain> updateDomains = new TreeMap<String,Domain>();
+ Map<String, Domain> collapsedDomainList = getCollapsedDomains();
+ Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList);
+
+ List<Domain> domainstoUpd = new ArrayList<Domain>();
+
+ //nline
+ List<Domain> collapsedDomainNewLL = getCollapsedDomainsNewList();
+
+ int colToUnCollapse = 99;
+
+ Domain domainToInsert = null;
+
+ //nline
+ // if (collapsedDomains.size() == 0) {
+ if (collapsedDomainNewLL.size() == 0) {
+ for (Map.Entry<String, Domain> unindexDomain : originalDomainRowCol.entrySet()) {
+ Domain dm = unindexDomain.getValue();
+ dm.setIndexChanged(false);
+ }
+ }
+
+
+ for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) {
+ if (entry.getValue().getName().equals(domainToUnCollapse)) {
+ colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]);
+ domainToInsert = entry.getValue();
+ collapsedDomainList.remove(entry.getKey());
+ //nline
+ collapsedDomainNewLL.remove(entry.getValue());
+ break;
+ }
+ }
+
+ domainstoUpd.add(domainToInsert);
+
+ //for (Map.Entry<String, Domain> e : originalDomainRowCol.entrySet())
+ // System.out.println("Original key value"+e.getKey()+":"+e.getValue().getName());
+
+ int lastKeyCol = -1;
+ for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) {
+ int currcol = Character.getNumericValue(entry.getKey().toCharArray()[1]);
+ if (currcol < colToUnCollapse) {
+ for (Map.Entry<String, Domain> currDomainsEntry : currentDomainsSorted.entrySet()) {
+ if (currDomainsEntry.getValue().getName().equals(entry.getValue().getName())) {
+ updateDomains.put(currDomainsEntry.getKey(), currDomainsEntry.getValue());
+ lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+ } else {
+ String newKey = "0"+String.valueOf(lastKeyCol+1);
+ if (currcol == colToUnCollapse) {
+ updateDomains.put(newKey, domainToInsert);
+ ++lastKeyCol;
+ } else {
+ for (Map.Entry<String, Domain> currDomainsEnt : currentDomainsSorted.entrySet()) {
+ if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) {
+ updateDomains.put(newKey, currDomainsEnt.getValue());
+ domainstoUpd.add(currDomainsEnt.getValue());
+ ++lastKeyCol;
+ // lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+ }
+
+ }
+ }
+
+ setNumberofColsofDomains(getNumberofColsofDomains()+1);
+ setDomainRowCol(updateDomains);
+
+ //for (Map.Entry<String, Domain> e : updateDomains.entrySet())
+ // System.out.println("me Updatedomains key value"+e.getKey()+":"+e.getValue().getName());
+
+
+
+
+ double currDistFromLftM = 11.0;
+
+ boolean isDisplayed;
+ for (Map.Entry<String,Domain> orgEntry : originalDomainRowCol.entrySet()) {
+ isDisplayed = false;
+ for (Map.Entry<String,Domain> cd : updateDomains.entrySet()) {
+ if (cd.getValue().getName().equals(orgEntry.getValue().getName())) {
+ Domain d = cd.getValue();
+ d.setDomainToLayoutWd(currDistFromLftM);
+ d.computeConatinerPositions();
+ for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
+ Container c = entry1.getValue();
+ c.computeSize();
+ c.computeElementPositions();
+ if (c.getContainerRowCol() != null) {
+ for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
+ Container inner = entryInner.getValue();
+ inner.computeElementPositions();
+ }
+ }
+ }
+ currDistFromLftM += d.computeSize().getWidth()+1;
+ isDisplayed = true;
+ break;
+ }
+ }
+
+ if (!isDisplayed) {
+ Domain myCollapsed = orgEntry.getValue();
+ myCollapsed.setNewXafterColl(currDistFromLftM);
+ currDistFromLftM += 4;
+ }
+ }
+
+ // plus.setNewXafterColl(distOfCollFrmLft+1.5);
+
+ //order changed
+ setCollapsedDomains(collapsedDomainList);
+
+ //nline
+ setCollapsedDomainsNewList(collapsedDomainNewLL);
+
+
+ computeDomainPositionsModified();
+ return this;
+
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private void updatePlusPosition(List<Domain> collapsedDNewL, Map<String, Domain> displayedDomainMap) {
+ List<Domain> copyCollapseList = new ArrayList<Domain>();
+
+ for (Domain copyCollapse : collapsedDNewL) {
+ copyCollapseList.add(copyCollapse);
+ }
+
+ //double distOfCollFrmLft = 0.0;
+ int orgColofCollapsed = -1;
+ int orgColofDisplayed = -1;
+ int orgColofDisplayedOtherPlus = -1;
+ int orgColofInterDomainPlus = -1;
+ List<Domain> dsplyList = new ArrayList<Domain>();
+
+ for (Domain plus : collapsedDNewL) {
+ double distOfCollFrmLft = 0.0;
+ for (Map.Entry<String, Domain> colCheck : originalDomainRowCol.entrySet()) {
+ if (colCheck.getValue().getName().equals(plus.getName())) {
+ orgColofCollapsed = Character.getNumericValue(colCheck.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+ for (Map.Entry<String, Domain> displayedEntry : displayedDomainMap.entrySet()) {
+
+ for (Map.Entry<String, Domain> colCheck1 : originalDomainRowCol.entrySet()) {
+ if (colCheck1.getValue().getName().equals(displayedEntry.getValue().getName())) {
+ orgColofDisplayed = Character.getNumericValue(colCheck1.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+ if (orgColofDisplayed < orgColofCollapsed) {
+ distOfCollFrmLft+= displayedEntry.getValue().computeSize().getWidth();
+
+
+ /* if (dsplyList.size() > 0) {
+ Domain lastAdded = dsplyList.get(dsplyList.size()-1);
+ int orgColofLastAdded = -1;
+ for (Map.Entry<String, Domain> colCh : originalDomainRowCol.entrySet()) {
+ if (colCh.getValue().getName().equals(lastAdded.getName())) {
+ orgColofLastAdded = Character.getNumericValue(colCh.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+ if (Math.abs(orgColofDisplayed - orgColofLastAdded) == 1) {
+ boolean adjDomainsWithPlus = false;
+ for (Domain colp : copyCollapseList) {
+ if (!colp.getName().equals(plus.getName())) {
+ for (Map.Entry<String, Domain> colCk2 : originalDomainRowCol.entrySet()) {
+ if (colCk2.getValue().getName().equals(colp.getName())) {
+ orgColofInterDomainPlus = Character.getNumericValue(colCk2.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+ if (orgColofInterDomainPlus > orgColofLastAdded && orgColofInterDomainPlus < orgColofDisplayed) {
+ adjDomainsWithPlus = true;
+ break;
+ }
+ }
+ }
+ if (!adjDomainsWithPlus)
+ distOfCollFrmLft+=interDomainWd;
+ }
+ }
+ dsplyList.add(displayedEntry.getValue()); */
+
+
+
+ }
+
+ }
+
+ for (Domain collp : copyCollapseList) {
+ if (!collp.getName().equals(plus.getName())) {
+ for (Map.Entry<String, Domain> colCheck2 : originalDomainRowCol.entrySet()) {
+ if (colCheck2.getValue().getName().equals(collp.getName())) {
+ orgColofDisplayedOtherPlus = Character.getNumericValue(colCheck2.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+ if (orgColofDisplayedOtherPlus < orgColofCollapsed) {
+ distOfCollFrmLft+=3.0;
+ }
+ }
+ }
+
+ plus.setNewXafterColl(distOfCollFrmLft+1.5);
+
+
+ }
+ }
+
+
+ private double accountForPlusSpaceBefore(Domain d) {
+
+ int orgColofCollapsed = 0;
+ int orgColofDisplayed = 0;
+ double distFromLftM = 0.0;
+
+ for (Map.Entry<String, Domain> colCheckk : originalDomainRowCol.entrySet()) {
+ if (colCheckk.getValue().getName().equals(d.getName())) {
+ orgColofDisplayed = Character.getNumericValue(colCheckk.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+
+ for (Domain collapsed : getCollapsedDomainsNewList()) {
+ for (Map.Entry<String, Domain> colCheck : originalDomainRowCol.entrySet()) {
+ if (colCheck.getValue().getName().equals(collapsed.getName())) {
+ orgColofCollapsed = Character.getNumericValue(colCheck.getKey().toCharArray()[1]);
+ break;
+ }
+ }
+
+ if (orgColofCollapsed < orgColofDisplayed) {
+ distFromLftM+= 2;
+ }
+ }
+ return distFromLftM;
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.support;
+
+import java.io.Serializable;
+
+
+public class NameValueId implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private String lab;
+ private String val;
+
+ public NameValueId() {
+ }
+
+ public NameValueId(String value, String label) {
+ setVal(value);
+ setLab(label);
+ }
+
+
+ public String getLab() {
+ return lab;
+ }
+
+
+ public String getVal() {
+ return val;
+ }
+
+
+ public void setLab(String label) {
+ this.lab = label;
+ }
+
+
+ public void setVal(String value) {
+ this.val = value;
+ }
+
+
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+
+ if (o == null) {
+ return false;
+ }
+
+ if (!(o instanceof NameValueId)) {
+ return false;
+ }
+
+ final NameValueId nameValueId = (NameValueId)o;
+
+ if (!getVal().equals(nameValueId.getVal())) {
+ return false;
+ }
+
+ if (!getLab().equals(nameValueId.getLab())) {
+ return false;
+ }
+
+ return true;
+ }
+
+
+ public int hashCode() {
+ return getVal().hashCode();
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.support;
+
+public class Position {
+ double x;
+ double y;
+
+ public double getX() {
+ return x;
+ }
+ public void setX(double x) {
+ this.x = x;
+ }
+ public double getY() {
+ return y;
+ }
+ public void setY(double y) {
+ this.y = y;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.domain.support;
+
+public class Size {
+ private double width;
+ private double height;
+
+ public double getWidth() {
+ return width;
+ }
+ public void setWidth(double width) {
+ this.width = width;
+ }
+ public double getHeight() {
+ return height;
+ }
+ public void setHeight(double height) {
+ this.height = height;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.drools;
+
+public interface DroolsRuleService {
+
+ public void init(String... params);
+ public String getResultsString();
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.drools;
+
+
+/**
+ *
+ * This is POC test class to execute sample rules
+ */
+public class DroolsRuleServiceImpl implements DroolsRuleService{
+
+
+ private String state;
+ private String resultsString;
+
+ public DroolsRuleServiceImpl() {
+
+ }
+
+ public void init(String... params) {
+ this.state = params[0];
+ }
+
+
+
+ public String getState() {
+ return state;
+ }
+
+ public String accessLabel() {
+ return "Drools POC Test";
+ }
+
+ public String getResultsString() {
+ return resultsString;
+ }
+
+ public void setResultsString(String resultsString) {
+ this.resultsString = resultsString;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.exception;
+
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.servlet.ModelAndView;
+
+@ControllerAdvice
+public class FusionExceptionResolver {
+
+ @ExceptionHandler(UrlAccessRestrictedException.class)
+ public ModelAndView handleUrlAccessException(UrlAccessRestrictedException ex) {
+ ModelAndView model = new ModelAndView("error");
+ model.addObject("errMsg", ex.getMessage());
+ return model;
+
+ }
+ @ExceptionHandler(SessionExpiredException.class)
+ public ModelAndView handleSessionException(SessionExpiredException ex) {
+ ModelAndView model = new ModelAndView("error");
+ model.addObject("errMsg", ex.getMessage());
+ return model;
+ }
+ @ExceptionHandler(Exception.class)
+ public ModelAndView handleAllException(Exception ex) {
+ ModelAndView model = new ModelAndView("error");
+ model.addObject("errMsg", ex.getMessage());
+ return model;
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.exception;
+
+import org.onap.portalsdk.core.exception.support.FusionRuntimeException;
+
+public class SessionExpiredException extends FusionRuntimeException {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ public static final String MESSAGE = "Your session has expired. Please login again.";
+
+ public SessionExpiredException() {
+ super(MESSAGE);
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.exception;
+
+import org.onap.portalsdk.core.exception.support.FusionRuntimeException;
+
+public class UrlAccessRestrictedException extends FusionRuntimeException {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ public static final String MESSAGE = "Authorization Denied";
+
+ public UrlAccessRestrictedException() {
+ super(MESSAGE);
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.exception.support;
+
+import org.onap.portalsdk.core.FusionObject;
+
+public interface FusionException extends FusionObject {}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.exception.support;
+
+public class FusionRuntimeException extends RuntimeException implements FusionException {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ public FusionRuntimeException() {
+ this("");
+ }
+
+ public FusionRuntimeException(String message) {
+ super(message);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.interceptor;
+
+import java.net.HttpURLConnection;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalsdk.core.controller.FusionBaseController;
+import org.onap.portalsdk.core.domain.App;
+import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
+import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.objectcache.AbstractCacheManager;
+import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.service.LoginService;
+import org.onap.portalsdk.core.service.UrlAccessService;
+import org.onap.portalsdk.core.service.WebServiceCallService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
+
+public class ResourceInterceptor extends HandlerInterceptorAdapter {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ResourceInterceptor.class);
+
+ public static final String APP_METADATA = "APP.METADATA";
+
+ @Autowired
+ private DataAccessService dataAccessService;
+ @Autowired
+ private LoginService loginService;
+ @Autowired
+ private WebServiceCallService webServiceCallService;
+
+ private AbstractCacheManager cacheManager;
+
+ @Autowired
+ UrlAccessService urlAccessService;
+
+ @Override
+ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
+ throws Exception {
+ String uri = request.getRequestURI();
+ String url = uri.substring(uri.indexOf("/", 1) + 1);
+ logger.info(EELFLoggerDelegate.debugLogger, "Url - " + url);
+ logger.info(EELFLoggerDelegate.debugLogger, "lastIndexOf - " + uri.substring(uri.lastIndexOf("/") + 1));
+ if (handler instanceof HandlerMethod) {
+ HandlerMethod method = (HandlerMethod) handler;
+ FusionBaseController controller = (FusionBaseController) method.getBean();
+ if (!controller.isAccessible()) {
+ if (controller.isRESTfulCall()) {
+ // check user authentication for RESTful calls
+ String secretKey = null;
+ try {
+ if (!webServiceCallService.verifyRESTCredential(secretKey, request.getHeader("username"),
+ request.getHeader("password"))) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Error accesing RESTful service. Un-authorized",AlarmSeverityEnum.MINOR);
+ throw new UrlAccessRestrictedException();
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Error authenticating RESTful service :" + e,AlarmSeverityEnum.MINOR);
+ //throw new UrlAccessRestrictedException();
+ HttpSession httpSession = request.getSession();
+ ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
+ return false;
+ }
+ }
+ if (!urlAccessService.isUrlAccessible(request, url)) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Error accesing URL. Un-authorized",AlarmSeverityEnum.MINOR);
+ throw new UrlAccessRestrictedException();
+ }
+ }
+ }
+
+ logger.debug("successfully authorized rest call");
+ logger.info(EELFLoggerDelegate.debugLogger, "successfully authorized rest call");
+ handleSessionUpdates(request);
+ logger.debug("handled session updates for synchronization");
+ logger.info(EELFLoggerDelegate.debugLogger, "handled session updates for synchronization");
+ return super.preHandle(request, response, handler);
+ }
+
+ /**
+ *
+ * @param request
+ */
+ protected void handleSessionUpdates(HttpServletRequest request) {
+
+ App app = null;
+ Object appObj = getCacheManager().getObject(APP_METADATA);
+ if (appObj == null) {
+ app = findApp();
+ getCacheManager().putObject(APP_METADATA, app);
+
+ } else {
+ app = (App) appObj;
+ }
+
+ String ecompRestURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
+ String decreptedPwd = "";
+ try {
+ decreptedPwd = CipherUtil.decrypt(app.getAppPassword(),
+ SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Could not decrypt Password" + e.getMessage(),AlarmSeverityEnum.MINOR);
+ }
+
+ PortalTimeoutHandler.handleSessionUpdatesNative(request, app.getUsername(), decreptedPwd,
+ PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), ecompRestURL, null);
+ }
+
+ public App findApp() {
+ List<?> list = null;
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where id = 1");
+ list = getDataAccessService().getList(App.class, criteria.toString(), null, null);
+ return (list == null || list.size() == 0) ? null : (App) list.get(0);
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ public LoginService getLoginService() {
+ return loginService;
+ }
+
+ public void setLoginService(LoginService loginService) {
+ this.loginService = loginService;
+ }
+
+ @Autowired
+ public void setCacheManager(AbstractCacheManager cacheManager) {
+ this.cacheManager = cacheManager;
+ }
+
+ public AbstractCacheManager getCacheManager() {
+ return cacheManager;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.interceptor;
+
+import java.net.URLEncoder;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalsdk.core.controller.FusionBaseController;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.exception.SessionExpiredException;
+import org.onap.portalsdk.core.listener.CollaborateListBindingListener;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.web.support.AppUtils;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
+
+public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionTimeoutInterceptor.class);
+
+ public SessionTimeoutInterceptor() {
+ }
+
+ /**
+ * Checks all requests for valid session information. If not found,
+ * redirects to a controller that will establish a valid session.
+ */
+ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
+ throws Exception {
+ if (handler instanceof HandlerMethod) {
+ HandlerMethod method = (HandlerMethod) handler;
+ FusionBaseController controller = (FusionBaseController) method.getBean();
+ if (!controller.isAccessible() && !controller.isRESTfulCall()) {
+ try {
+ // getSession() throws SessionExpiredException
+ HttpSession session = AppUtils.getSession(request);
+ User user = UserUtils.getUserSession(request);
+ // check if user is logging out
+ if (request.getRequestURI().indexOf("logout.htm") > -1) {
+ session.removeAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME);
+ throw new SessionExpiredException();
+ } else if (user == null) {
+ // Jump to the redirection code
+ throw new Exception("preHandle: user not found in session");
+ } else {
+ // session binding listener will add this value to the
+ // map, and with session replication the listener will
+ // fire in all tomcat instances
+ session.setAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME,
+ new CollaborateListBindingListener(user.getOrgUserId()));
+ }
+ } catch (Exception ex) {
+ // get the path within the webapp that the user requested (no host name etc.)
+ final String forwardUrl = request.getRequestURI().substring(request.getContextPath().length() + 1)
+ + (request.getQueryString() == null ? "" : "?" + request.getQueryString());
+ final String forwardUrlParm = "forwardURL=" + URLEncoder.encode(forwardUrl, "UTF-8");
+ final String singleSignonPrefix = "/single_signon.htm?";
+ if (ex instanceof SessionExpiredException) {
+ // Session is expired; send to portal.
+ // Redirect to an absolute path in the webapp; e.g., "/context/single_signon.htm"
+ final String redirectUrl = request.getContextPath() + singleSignonPrefix + "redirectToPortal=Yes&" + forwardUrlParm;
+ logger.debug(EELFLoggerDelegate.debugLogger, "preHandle: session is expired, redirecting to {}",
+ redirectUrl);
+ response.sendRedirect(redirectUrl);
+ return false;
+ } else {
+ // Other issue; do not send to portal.
+ // Redirect to an absolute path in the webapp; e.g., "/context/single_signon.htm"
+ final String redirectUrl = request.getContextPath() + singleSignonPrefix + forwardUrlParm;
+ logger.debug(EELFLoggerDelegate.debugLogger, "preHandle: took exception {}, redirecting to {}",
+ ex.getMessage(), redirectUrl);
+ response.sendRedirect(redirectUrl);
+ return false;
+ }
+ }
+ }
+ }
+
+ return super.preHandle(request, response, handler);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.interfaces;
+
+public interface SecurityInterface {
+ public boolean isAccessible();
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.listener;
+
+import javax.servlet.ServletContext;
+import javax.servlet.annotation.WebListener;
+
+import org.onap.portalsdk.core.lm.FusionLicenseManager;
+import org.onap.portalsdk.core.lm.FusionLicenseManagerUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationListener;
+import org.springframework.context.event.ContextRefreshedEvent;
+import org.springframework.stereotype.Component;
+
+@WebListener
+@Component
+public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> {
+
+ @Autowired
+ ServletContext context;
+ @Autowired
+ FusionLicenseManager lm;
+ @Autowired
+ FusionLicenseManagerUtils fusionLicenseManagerUtils;
+
+
+ public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) {
+ int licenseStatus = fusionLicenseManagerUtils.verifyLicense(context);
+ context.setAttribute("licenseVerification", licenseStatus);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.listener;
+
+import java.io.Serializable;
+
+import javax.servlet.http.HttpSessionBindingEvent;
+import javax.servlet.http.HttpSessionBindingListener;
+
+import org.onap.portalsdk.core.domain.support.CollaborateList;
+
+public class CollaborateListBindingListener implements HttpSessionBindingListener, Serializable {
+
+ private static final long serialVersionUID = 1L;
+ private String userName;
+ public static final String SESSION_ATTR_NAME = "CollaborateListSessionAttrName";
+
+ public CollaborateListBindingListener(String _userName) {
+ userName = _userName;
+ }
+
+ @Override
+ public void valueBound(HttpSessionBindingEvent event) {
+ final CollaborateListBindingListener value = ((CollaborateListBindingListener) event.getValue());
+ CollaborateList.addUserName(value.getUserName());
+
+ }
+
+ @Override
+ public void valueUnbound(HttpSessionBindingEvent event) {
+ final CollaborateListBindingListener value = ((CollaborateListBindingListener) event.getValue());
+ if (value != null)
+ CollaborateList.delUserName(value.getUserName());
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+
+ public void setUserName(String userName) {
+ this.userName = userName;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.listener;
+
+import javax.servlet.annotation.WebListener;
+import javax.servlet.http.HttpSession;
+import javax.servlet.http.HttpSessionEvent;
+import javax.servlet.http.HttpSessionListener;
+
+import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+
+@WebListener
+public class UserSessionListener implements HttpSessionListener{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserSessionListener.class);
+
+ public void sessionCreated(HttpSessionEvent event){
+
+ }
+
+ /**
+ * Removes sessions from the context scoped HashMap when they expire
+ * or are invalidated.
+ */
+ public void sessionDestroyed(HttpSessionEvent event){
+ try {
+ HttpSession session = event.getSession();
+ session.removeAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME);
+
+ // Object user = session.getAttribute(SystemProperties.getProperty("user.attribute.name"));
+
+ //if( user != null)
+ // {
+ session.removeAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME);
+ //CollaborateList.getInstance().delUserName(user.getOrgUserId());
+ // }
+
+ }
+ catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "sessionDestroyed" + e.getMessage(),AlarmSeverityEnum.MINOR);
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.lm;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.ServletContext;
+
+//import de.schlichtherle.license.LicenseContent;
+
+public interface FusionLicenseManager {
+
+
+ public static final int DEVELOPER_LICENSE = 0;
+ public static final int EXPIRED_LICENSE = 1;
+ public static final int VALID_LICENSE = 2;
+ public static final int INVALID_LICENSE = 3;
+ public static final int OPENSOURCE_LICENSE = 4;
+
+ public void initKeyStoreParam();
+
+ public void initCipherParam();
+
+ public void initLicenseParam();
+
+ public void doInitWork();
+
+ public int installLicense();
+
+ public int verifyLicense(ServletContext context);
+
+ //public LicenseContent createLicenseContent(Map<String, String> clientInfoMap, List<String> ipAddressList);
+
+ public void generateLicense(Map<String, String> clientInfoMap, List<String> ipAddressList) throws Exception;
+
+ public String nvl(String s);
+
+ public Date getExpiredDate();
+
+ public void setExpiredDate(Date expiredDate);
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.lm;
+
+import java.util.Date;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.servlet.support.RequestContextUtils;
+
+@Component
+public class FusionLicenseManagerUtils {
+
+ @Autowired
+ private FusionLicenseManager licenseManager;
+
+ @Autowired
+ private SystemProperties sysProps;
+ static {
+ }
+
+ public int verifyLicense(ServletContext context) {
+ if(sysProps == null) {
+ try {
+ sysProps = new SystemProperties();
+ sysProps.setServletContext(context);
+// sysProps.load();
+// licenseManager = new FusionLicenseManagerImpl(new LicenseableClassImpl());
+ System.out.println(licenseManager);
+ licenseManager.installLicense();
+ }
+ catch(Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+
+
+
+// WebApplicationContext ctx =RequestContextUtils.getWebApplicationContext(request);
+// int flag = ((FusionLicenseManager)ctx.getBean("fusionLicenseManager")).verifyLicense(request);
+// logger.debug("****************FLAG ******************** " + flag);
+// return flag;
+// return 2;
+ return licenseManager.verifyLicense(context);
+ }
+
+ public static Date getLicenseExpiryDate(HttpServletRequest request) {
+ WebApplicationContext ctx =RequestContextUtils.getWebApplicationContext(request);
+ return ((FusionLicenseManager)ctx.getBean("fusionLicenseManager")).getExpiredDate();
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.lm;
+
+import java.io.*;
+
+/**
+ * created by Alvin Alexander of http://devdaily.com.
+ * modified by Sundar Ramalingam
+ */
+public interface LicenseableClass
+{
+ public String getApplicationName();
+ public InputStream getPublicKeystoreAsInputStream() throws FileNotFoundException;
+ public String getAlias();
+ public String getPublicKeystorePassword();
+ public String getKeyPasswd();
+ public String getCipherParamPassword();
+ public Class getClassToLicense();
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.logging.aspect;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+
+@Target({ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface AuditLog {
+ String value() default "";
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.logging.aspect;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.logging.format.AuditLogFormatter;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.AppService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.att.eelf.configuration.Configuration;
+
+@org.springframework.context.annotation.Configuration
+public class EELFLoggerAdvice {
+
+ private static final EELFLoggerDelegate adviceLogger = EELFLoggerDelegate.getLogger(EELFLoggerAdvice.class);
+
+ @Autowired
+ private AppService appService;
+
+ // DateTime Format according to the ECOMP Application Logging Guidelines.
+ private static final SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
+
+ /**
+ * Gets the current date and time in expected ECOMP log format.
+ *
+ * @return Current date and time
+ */
+ public static String getCurrentDateTimeUTC() {
+ String currentDateTime = ecompLogDateFormat.format(new Date());
+ return currentDateTime;
+ }
+
+ /**
+ *
+ * @param securityEventType
+ * @param args
+ * @param passOnArgs
+ * @return One-element array containing an empty String object.
+ */
+ public Object[] before(SecurityEventTypeEnum securityEventType, Object[] args, Object[] passOnArgs) {
+ try {
+ String className = "";
+ if (passOnArgs[0] != null) {
+ className = passOnArgs[0].toString();
+ }
+
+ String methodName = "";
+ if (passOnArgs[1] != null) {
+ methodName = passOnArgs[1].toString();
+ }
+
+ String appName = appService.getDefaultAppName();
+ if (appName == null || appName == "") {
+ appName = SystemProperties.SDK_NAME;
+ }
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className);
+
+ // Initialize Request defaults only for controller methods.
+ MDC.put(className + methodName + SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC());
+ MDC.put(SystemProperties.TARGET_ENTITY, appName + "_BE");
+ MDC.put(SystemProperties.TARGET_SERVICE_NAME, methodName);
+ if (securityEventType != null) {
+ MDC.put(className + methodName + SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC());
+ HttpServletRequest req = null;
+ if (args[0] != null && args[0] instanceof HttpServletRequest) {
+ req = (HttpServletRequest) args[0];
+ logger.setRequestBasedDefaultsIntoGlobalLoggingContext(req, appName);
+ }
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, (methodName + " was invoked."));
+ } catch (Exception e) {
+ adviceLogger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred in EELFLoggerAdvice.before() method. Details: " + e.getMessage());
+ }
+
+ return new Object[] { "" };
+ }
+
+ /**
+ *
+ * @param securityEventType
+ * @param result
+ * @param args
+ * @param returnArgs
+ * @param passOnArgs
+ */
+ public void after(SecurityEventTypeEnum securityEventType, String result, Object[] args, Object[] returnArgs,
+ Object[] passOnArgs) {
+ try {
+ String className = "";
+ if (passOnArgs[0] != null) {
+ className = passOnArgs[0].toString();
+ }
+
+ String methodName = "";
+ if (passOnArgs[1] != null) {
+ methodName = passOnArgs[1].toString();
+ }
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className);
+
+ String appName = appService.getDefaultAppName();
+ if (appName == null || appName == "") {
+ appName = SystemProperties.SDK_NAME;
+ }
+
+ if (MDC.get(SystemProperties.TARGET_SERVICE_NAME) == null
+ || MDC.get(SystemProperties.TARGET_SERVICE_NAME) == "") {
+ MDC.put(SystemProperties.TARGET_SERVICE_NAME, methodName);
+ }
+
+ if (MDC.get(SystemProperties.TARGET_ENTITY) == null || MDC.get(SystemProperties.TARGET_ENTITY) == "") {
+ MDC.put(SystemProperties.TARGET_ENTITY, appName + "_BE");
+ }
+
+ MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP,
+ MDC.get(className + methodName + SystemProperties.METRICSLOG_BEGIN_TIMESTAMP));
+ MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, getCurrentDateTimeUTC());
+ this.calculateDateTimeDifference(MDC.get(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP),
+ MDC.get(SystemProperties.METRICSLOG_END_TIMESTAMP));
+
+ logger.info(EELFLoggerDelegate.metricsLogger, methodName + " operation is completed.");
+ logger.debug(EELFLoggerDelegate.debugLogger, "Finished executing " + methodName + ".");
+
+ if (securityEventType != null) {
+
+ MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
+ MDC.get(className + methodName + SystemProperties.AUDITLOG_BEGIN_TIMESTAMP));
+ MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, getCurrentDateTimeUTC());
+ this.calculateDateTimeDifference(MDC.get(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+ MDC.get(SystemProperties.AUDITLOG_END_TIMESTAMP));
+
+ this.logSecurityMessage(logger, securityEventType, result, methodName);
+
+ // clear when finishes audit logging
+ MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
+ MDC.remove(SystemProperties.PARTNER_NAME);
+ MDC.remove(SystemProperties.MDC_LOGIN_ID);
+ MDC.remove(SystemProperties.PROTOCOL);
+ MDC.remove(SystemProperties.FULL_URL);
+ MDC.remove(Configuration.MDC_SERVICE_NAME);
+ MDC.remove(SystemProperties.RESPONSE_CODE);
+ MDC.remove(SystemProperties.STATUS_CODE);
+ MDC.remove(className + methodName + SystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+ MDC.remove(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+ MDC.remove(SystemProperties.AUDITLOG_END_TIMESTAMP);
+ }
+
+ MDC.remove(className + methodName + SystemProperties.METRICSLOG_BEGIN_TIMESTAMP);
+ MDC.remove(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP);
+ MDC.remove(SystemProperties.METRICSLOG_END_TIMESTAMP);
+ MDC.remove(SystemProperties.MDC_TIMER);
+ MDC.remove(SystemProperties.TARGET_ENTITY);
+ MDC.remove(SystemProperties.TARGET_SERVICE_NAME);
+ } catch (Exception e) {
+ adviceLogger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred in EELFLoggerAdvice.after() method. Details: " + e.getMessage());
+ }
+ }
+
+ /**
+ *
+ * @param logger
+ * @param securityEventType
+ * @param result
+ * @param restMethod
+ */
+ private void logSecurityMessage(EELFLoggerDelegate logger, SecurityEventTypeEnum securityEventType, String result,
+ String restMethod) {
+ StringBuilder additionalInfoAppender = new StringBuilder();
+ String auditMessage = "";
+
+ additionalInfoAppender.append(String.format("%s request was received.", restMethod));
+
+ // Status code
+ MDC.put(SystemProperties.STATUS_CODE, result);
+
+ String fullURL = MDC.get(SystemProperties.FULL_URL);
+ if (fullURL != null && fullURL != "") {
+ additionalInfoAppender.append(" Request-URL:" + MDC.get(SystemProperties.FULL_URL));
+ }
+
+ auditMessage = AuditLogFormatter.getInstance().createMessage(MDC.get(SystemProperties.PROTOCOL),
+ securityEventType.name(), MDC.get(SystemProperties.MDC_LOGIN_ID), additionalInfoAppender.toString());
+
+ logger.info(EELFLoggerDelegate.auditLogger, auditMessage);
+ }
+
+ /**
+ *
+ * @param beginDateTime
+ * @param endDateTime
+ */
+ private void calculateDateTimeDifference(String beginDateTime, String endDateTime) {
+ if (beginDateTime != null && endDateTime != null) {
+ try {
+ Date beginDate = ecompLogDateFormat.parse(beginDateTime);
+ Date endDate = ecompLogDateFormat.parse(endDateTime);
+ String timeDifference = String.format("%d ms", endDate.getTime() - beginDate.getTime());
+ MDC.put(SystemProperties.MDC_TIMER, timeDifference);
+ } catch (Exception e) {
+ adviceLogger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred in EELFLoggerAdvice.calculateDateTimeDifference() method. Details: "
+ + e.getMessage());
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.logging.aspect;
+
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Pointcut;
+import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
+import org.springframework.beans.factory.annotation.Autowired;
+
+
+@Aspect
+@org.springframework.context.annotation.Configuration
+public class EELFLoggerAspect {
+
+ @Autowired
+ EELFLoggerAdvice advice;
+
+ /*
+ * Point-cut expression to handle all INCOMING_REST_MESSAGES
+ */
+ @Pointcut("execution(public * org.onap.portalsdk.core.controller.*.*(..))")
+ public void incomingAuditMessages() {}
+
+ @Around("incomingAuditMessages() && @annotation(auditLog)")
+ public Object logAuditMethodAround(ProceedingJoinPoint joinPoint, AuditLog auditLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
+ }
+
+ @Around("incomingAuditMessages() && @within(auditLog)")
+ public Object logAuditMethodClassAround(ProceedingJoinPoint joinPoint, AuditLog auditLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
+ }
+
+ /*
+ * Point cut expression to capture metrics logging
+ */
+ @Pointcut("execution(public * *(..))")
+ public void publicMethod() {}
+
+ @Around("publicMethod() && @within(metricsLog)")
+ public Object logMetricsClassAround(ProceedingJoinPoint joinPoint, MetricsLog metricsLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, null);
+ }
+
+ @Around("publicMethod() && @annotation(metricsLog)")
+ public Object logMetricsMethodAround(ProceedingJoinPoint joinPoint, MetricsLog metricsLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, null);
+ }
+
+ private Object logAroundMethod(ProceedingJoinPoint joinPoint, SecurityEventTypeEnum securityEventType) throws Throwable {
+ //Before
+ Object[] passOnArgs = new Object[] {joinPoint.getSignature().getDeclaringType().getName(),joinPoint.getSignature().getName()};
+ Object[] returnArgs = advice.before(securityEventType, joinPoint.getArgs(), passOnArgs);
+
+ //Execute the actual method
+ Object result = null;
+ String restStatus = "COMPLETE";
+ try {
+ result = joinPoint.proceed();
+ } catch(Exception e) {
+ restStatus = "ERROR";
+ }
+
+ //After
+ advice.after(securityEventType, restStatus, joinPoint.getArgs(), returnArgs, passOnArgs);
+
+ return result;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.logging.aspect;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+
+@Target({ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface MetricsLog {
+ String value() default "";
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.logging.format;
+
+public enum AlarmSeverityEnum {
+ CRITICAL,
+ MAJOR,
+ MINOR,
+ INFORMATIONAL,
+ NONE,
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.logging.format;
+
+public enum AppMessagesEnum {
+ /*
+ 100-199 Security/Permission Related
+ - Authentication problems (from external client, to external server)
+ - Certification errors
+ -
+
+ 200-299 Availability/Timeout Related
+ - connectivity error
+ - connection timeout
+
+ 300-399 Data Access/Integrity Related
+ - Data in graph in invalid(E.g. no creator is found for service)
+ - Artifact is missing in ES, but exists in graph.
+
+ 400-499 Schema Interface Type/Validation
+ - received Pay-load checksum is invalid
+ - received JSON is not valid
+
+ 500-599 Business/Flow Processing Related
+ - check out to service is not allowed
+ - Roll-back is done
+ - failed to generate heat file
+
+
+ 600-899 Reserved - do not use
+
+ 900-999 Unknown Errors
+ - Unexpected exception
+ */
+
+ BeUebAuthenticationError(ErrorCodesEnum.BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR100E", "An Authentication failure occurred during access to UEB server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
+
+ BeRestApiAuthenticationError(ErrorCodesEnum.BERESTAPIAUTHENTICATIONERROR, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR101E", "Rejected an incoming REST API request due to invalid credentials", "", "Please check application credentials defined in Database or properties files."),
+
+ InternalAuthenticationInfo(ErrorCodesEnum.INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR199I", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
+
+ InternalAuthenticationWarning(ErrorCodesEnum.INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
+ "ERR199W", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
+
+ InternalAuthenticationError(ErrorCodesEnum.INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR199E", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
+
+ InternalAuthenticationFatal(ErrorCodesEnum.INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL,
+ "ERR199F", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
+
+ BeHealthCheckError(ErrorCodesEnum.BeHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR200E", "ECOMP-PORTAL Back-end probably lost connectivity to either one of the following components: MySQL DB, UEB Cluster", "", "Please check the logs for more information."),
+
+ BeHealthCheckMySqlError(ErrorCodesEnum.BEHEALTHCHECKMYSQLERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR201E", "ECOMP-PORTAL Back-end probably lost connectivity to MySQL DB", "", "Check connectivity to MYSQL is configured correctly under system.properties file."),
+
+ BeHealthCheckUebClusterError(ErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR203E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "", "Check connectivity to UEB cluster which is configured under portal.properties file."),
+
+ FeHealthCheckError(ErrorCodesEnum.FEHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR204E", "Unable to connect to a valid ECOMP-PORTAL Back-end Server.", "", "Please check connectivity from this FE instance towards BE or BE Load Balancer."),
+
+ BeHealthCheckRecovery(ErrorCodesEnum.BEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR205I", "ECOMP-PORTAL Back-end Recovery to either one of the following components: MySQL DB, UEB Cluster", "", "Please check logs for more specific information about the problem."),
+
+ BeHealthCheckMySqlRecovery(ErrorCodesEnum.BEHEALTHCHECKMYSQLRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR206I", "ECOMP-PORTAL Back-end connection recovery to MySQL DB", "", "Please check logs for more specific information about the problem."),
+
+ BeHealthCheckUebClusterRecovery(ErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR208I", "ECOMP-PORTAL Back-end connection recovery to UEB Cluster", "", "Please check logs for more specific information about the problem."),
+
+ FeHealthCheckRecovery(ErrorCodesEnum.FEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR209I", "Connectivity to ECOMP-PORTAL Front-end Server is recovered", "", "Please check logs for more specific information about the problem."),
+
+ BeUebConnectionError(ErrorCodesEnum.BEUEBCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR210E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
+
+ BeUebUnkownHostError(ErrorCodesEnum.BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR211E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Cannot reach host: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
+
+ BeUebRegisterOnboardingAppError(ErrorCodesEnum.BEUEBREGISTERONBOARDINGAPPERROR, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR212E", "Failed to register the On-boarding application with UEB Communication server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
+
+ BeHttpConnectionError(ErrorCodesEnum.BEHTTPCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR213E", "It could be that communication to an external application might resulted an exception or failed to reach the external application",
+ "Details: {0}.", "Please check logs for more information."),
+
+ InternalConnectionInfo(ErrorCodesEnum.INTERNALCONNECTIONINFO_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR299I", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
+
+ InternalConnectionWarning(ErrorCodesEnum.INTERNALCONNECTIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
+ "ERR299W", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
+
+ InternalConnectionError(ErrorCodesEnum.INTERNALCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR299E", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
+
+ InternalConnectionFatal(ErrorCodesEnum.INTERNALCONNECTIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL,
+ "ERR299F", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
+
+ BeUebObjectNotFoundError(ErrorCodesEnum.BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR303E", "Error occurred during access to U-EB Server.", "Data not found: {0}.", "An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic."),
+
+ BeUserMissingError(ErrorCodesEnum.BEUSERMISSINGERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR310E", "User is not found", "", "User {0} must be added to the corresponding application with proper user roles."),
+
+ BeUserInactiveWarning(ErrorCodesEnum.BEUSERINACTIVEWARNING_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
+ "ERR313W", "User is found but in-active", "", "User {0} must be added to the corresponding application with proper user roles."),
+
+ BeUserAdminPrivilegesInfo(ErrorCodesEnum.BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
+ "ERR314W", "User is found but don't have administrative privileges", "", "User {0} should be given administrator role for the corresponding application to perform the necessary actions."),
+
+ BeInvalidJsonInput(ErrorCodesEnum.BEINVALIDJSONINPUT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR405E", "Failed to convert JSON input to object", "", "Please check logs for more information."),
+
+ BeIncorrectHttpStatusError(ErrorCodesEnum.BEINCORRECTHTTPSTATUSERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR407E", "Communication to an external application is resulted in with Incorrect Http response code", "", "Please check logs for more information."),
+
+ BeInitializationError(ErrorCodesEnum.BEINITIALIZATIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR500E", "ECOMP-PORTAL Back-end was not initialized properly", "", "Please check logs for more information."),
+
+ BeUebSystemError(ErrorCodesEnum.BEUEBSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR502E", "Error occurred during access to U-EB Server", "Details: {0}.", "An error occurred in {1} distribution mechanism. Please check the logs for more information."),
+
+ BeDaoSystemError(ErrorCodesEnum.BEDAOSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR505E", "Performing DDL or DML operations on database might have failed", "", "Please check MySQL DB health or look at the logs for more details."),
+
+ BeSystemError(ErrorCodesEnum.BESYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR506E", "Unexpected error during operation", "", "Please check logs for more information."),
+
+ BeExecuteRollbackError(ErrorCodesEnum.BEEXECUTEROLLBACKERROR, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR507E", "Roll-back operation towards database has failed", "", "Please check MYSQL DB health or look at the logs for more details."),
+
+ FeHttpLoggingError(ErrorCodesEnum.FEHTTPLOGGINGERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.ERROR,
+ "ERR517E", "Error when logging FE HTTP request/response", "", "Please check MYSQL DB health or look at the logs for more details."),
+
+ FePortalServletError(ErrorCodesEnum.FEPORTALSERVLETERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR518E", "Error when trying to access FE Portal page.", "", "Please check logs for more information."),
+
+ BeDaoCloseSessionError(ErrorCodesEnum.BEDAOCLOSESESSIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR519E", "Close local session operation with database failed", "", "Please check MYSQL DB health or look at the logs form more details."),
+
+ BeRestApiGeneralError(ErrorCodesEnum.BERESTAPIGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR900E", "Unexpected error during ECOMP-PORTAL Back-end REST API execution", "", "Please check error log for more information."),
+
+ FeHealthCheckGeneralError(ErrorCodesEnum.FEHEALTHCHECKGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR901E", "General error during FE Health Check", "", "Please check error log for more information."),
+
+ InternalUnexpectedInfo(ErrorCodesEnum.INTERNALUNEXPECTEDINFO_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR999I", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
+
+ InternalUnexpectedWarning(ErrorCodesEnum.INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
+ "ERR999W", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
+
+ InternalUnexpectedError(ErrorCodesEnum.INTERNALUNEXPECTEDERROR_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR999E", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
+
+ InternalUnexpectedFatal(ErrorCodesEnum.INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL,
+ "ERR999F", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
+
+ ;
+
+ ErrorTypeEnum eType;
+ AlarmSeverityEnum alarmSeverity;
+ ErrorCodesEnum messageCode;
+ ErrorSeverityEnum errorSeverity;
+ String errorCode;
+ String errorDescription;
+ String details;
+ String resolution;
+
+ AppMessagesEnum(ErrorCodesEnum messageCode, ErrorTypeEnum eType, AlarmSeverityEnum alarmSeverity, ErrorSeverityEnum errorSeverity, String errorCode, String errorDescription,
+ String details, String resolution) {
+ this.messageCode = messageCode;
+ this.eType = eType;
+ this.alarmSeverity = alarmSeverity;
+ this.errorSeverity = errorSeverity;
+ this.errorCode = errorCode;
+ this.errorDescription = errorDescription;
+ this.details = details;
+ this.resolution = resolution;
+ }
+
+ public String getDetails() {
+ return this.details;
+ }
+
+ public String getResolution() {
+ return this.resolution;
+ }
+ public String getErrorCode() {
+ return this.errorCode;
+ }
+
+ public String getErrorDescription() {
+ return this.errorDescription;
+ }
+
+ public ErrorSeverityEnum getErrorSeverity() {
+ return this.errorSeverity;
+ }
+
+ public void setErrorSeverity(ErrorSeverityEnum errorSeverity) {
+ this.errorSeverity = errorSeverity;
+ }
+
+ public ErrorCodesEnum getMessageCode() {
+ return messageCode;
+ }
+
+ public void setMessageCode(ErrorCodesEnum messageCode) {
+ this.messageCode = messageCode;
+ }
+
+ public AlarmSeverityEnum getAlarmSeverity() {
+ return alarmSeverity;
+ }
+
+ public void setAlarmSeverity(AlarmSeverityEnum alarmSeverity) {
+ this.alarmSeverity = alarmSeverity;
+ }
+
+ public ErrorTypeEnum getErrorType() {
+ return eType;
+ }
+
+ public void setErrorType(ErrorTypeEnum eType) {
+ this.eType = eType;
+ }
+}
--- /dev/null
+###
+# ============LICENSE_START==========================================
+# ONAP Portal SDK
+# ===================================================================
+# Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+# ===================================================================
+#
+# Unless otherwise specified, all software contained herein is licensed
+# under the Apache License, Version 2.0 (the “License”);
+# you may not use this software 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.
+#
+# Unless otherwise specified, all documentation contained herein is licensed
+# under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+# you may not use this documentation except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://creativecommons.org/licenses/by/4.0/
+#
+# Unless required by applicable law or agreed to in writing, documentation
+# 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.
+#
+# ============LICENSE_END============================================
+#
+# ECOMP is a trademark and service mark of AT&T Intellectual Property.
+###
+########################################################################
+#Resource key=Error Code|Message text|Resolution text |Description text
+#######
+#Newlines can be utilized to add some clarity ensuring continuing line
+#has atleast one leading space
+#ResourceKey=\
+# ERR0000E\
+# Sample error msg txt\
+# Sample resolution msg\
+# Sample description txt
+#
+######
+#Error code classification category
+#100 Permission errors
+#200 Availability errors/Timeouts
+#300 Data errors
+#400 Schema Interface type/validation errors
+#500 Business process errors
+#900 Unknown errors
+#
+########################################################################
+
+#Health check
+BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT=\
+ ERR100E|\
+ Authentication problem towards U-EB server. Reason: {0}.|\
+ An Authentication failure occurred during access to UEB server. Please check that UEB keys are configured correctly under fusion.properties file.|
+
+BERESTAPIAUTHENTICATIONERROR =\
+ ERR101E|\
+ Rejected an incoming REST API request to {0} from {1} due to invalid credentials.|\
+ Please check application credentials defined in Database or portal.properties file.|
+
+INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT=\
+ ERR199I|\
+ Internal authentication problem. Description: {0}.|
+
+INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT=\
+ ERR199W|\
+ Internal authentication problem. Description: {0}.|
+
+INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT=\
+ ERR199E|\
+ Internal authentication problem. Description: {0}.|
+
+INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT=\
+ ERR199F|\
+ Internal authentication problem. Description: {0}.|
+
+BEHEALTHCHECKERROR=\
+ ERR200E|\
+ {0} probably lost connectivity to either one of the following components: MySQL DB, UEB Cluster. Please check the logs for more information.|
+
+BEHEALTHCHECKMYSQLERROR=\
+ ERR201E|\
+ {0} probably lost connectivity to MySQL DB. Please check the logs for more information.|\
+ Check connectivity to MYSQL is configured correctly under system.properties file.|
+
+BEHEALTHCHECKUEBCLUSTERERROR=\
+ ERR203E|\
+ {0} probably lost connectivity to UEB Cluster. Please check the logs for more information.|\
+ Check connectivity to UEB cluster which is configured under portal.properties file.|
+
+BEHEALTHCHECKRECOVERY=\
+ ERR205I|\
+ {0} Recovery to either one of the following components: MySQL DB, UEB Cluster.|
+
+BEHEALTHCHECKMYSQLRECOVERY=\
+ ERR206I|\
+ {0} connection recovery to MySQL DB.|
+
+BEHEALTHCHECKUEBCLUSTERRECOVERY=\
+ ERR208I|\
+ {0} connection recovery to UEB Cluster.|
+
+FEHEALTHCHECKRECOVERY=\
+ ERR209I|\
+ Connectivity to {0} Server is recovered.|
+
+#UEB communication
+BEUEBCONNECTIONERROR_ONE_ARGUMENT=\
+ ERR210E|\
+ Connection problem towards U-EB server. Reason: {0}.|\
+ Please check that that parameter uebServers in portal.properties points to a valid UEB Cluster.|
+
+BEUEBSYSTEMERROR=\
+ ERR502E|\
+ Error occurred during access to U-EB Server. Operation: {0}.|\
+ An error occurred in {1} distribution mechanism. Please check the logs for more information.|
+
+BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT=\
+ ERR211E|\
+ Connection problem towards U-EB server. Cannot reach host {0}.|\
+ Please check that that parameter uebServers in portal.properties points to a valid UEB Cluster.|
+
+#Onboarding apps
+BEUEBREGISTERONBOARDINGAPPERROR=\
+ ERR212E|\
+ Unable to register the On-boarding application with the U-EB server. Reason: {0}.|\
+ Please check that that parameter uebServers in system.properties points to a valid UEB Cluster.|
+
+#HTTP communication
+BEHTTPCONNECTIONERROR_ONE_ARGUMENT=\
+ ERR213E|\
+ HTTP connection to an external application is failed. Reason: {0}.|\
+ Please check the logs for more information.|
+
+INTERNALCONNECTIONINFO_ONE_ARGUMENT=\
+ ERR299I|\
+ Internal Connection problem. Description: {0}.|
+
+INTERNALCONNECTIONWARNING_ONE_ARGUMENT=\
+ ERR299W|\
+ Internal Connection problem. Description: {0}.|
+
+INTERNALCONNECTIONERROR_ONE_ARGUMENT=\
+ ERR299E|\
+ Internal Connection problem. Description: {0}.|
+
+INTERNALCONNECTIONFATAL_ONE_ARGUMENT=\
+ ERR299F|\
+ Internal Connection problem. Description: {0}.|
+
+BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT=\
+ ERR303E|\
+ Error occurred during access to U-EB Server. Data not found: {0}.|\
+ An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic.|
+
+#Login error codes
+BEUSERMISSINGERROR_ONE_ARGUMENT=\
+ ERR310E|\
+ User {0} requested is not found.|
+
+BEUSERINACTIVEWARNING_ONE_ARGUMENT=\
+ ERR313W|\
+ User {0} is found but inactive.|
+
+BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT=\
+ ERR314W|\
+ User {0} is found but don't have administrative privileges.|
+
+BEINVALIDJSONINPUT=\
+ ERR405E|\
+ Failed to convert JSON input to object.|\
+ Please check error logs for more information.|
+
+BEINCORRECTHTTPSTATUSERROR=\
+ ERR407E|\
+ Incorrect HttpResponse Received.|\
+ Please check error & metrics logs for more information.|
+
+BEINITIALIZATIONERROR=\
+ ERR500E|\
+ BE was not initialized properly.|
+
+BEDAOSYSTEMERROR=\
+ ERR505E|\
+ Operation towards database failed.|\
+ Please check MySQL DB health or look at the logs for more details.|
+
+BESYSTEMERROR=\
+ ERR506E|\
+ Unexpected error during operation.|
+
+BEEXECUTEROLLBACKERROR=\
+ ERR507E|\
+ Roll-back operation towards database failed.|\
+ Please check MYSQL DB health or look at the logs for more details.|
+
+FEHTTPLOGGINGERROR=\
+ ERR517E|\
+ Error when logging FE HTTP request/response.|
+
+BEDAOCLOSESESSIONERROR=\
+ ERR519E|\
+ Close local session operation with database failed.|\
+ Please check MYSQL DB health or look at the logs form more details.|
+
+BERESTAPIGENERALERROR=\
+ ERR900E|\
+ Unexpected error during BE REST API execution.|\
+ Please check error log for more information.|
+
+FEHEALTHCHECKGENERALERROR=\
+ ERR901E|\
+ General error during FE Health Check.|
+
+INTERNALUNEXPECTEDINFO_ONE_ARGUMENT=\
+ ERR999I|\
+ Unexpected error. Description: {0}.|
+
+INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT=\
+ ERR999W|\
+ Unexpected error. Description: {0}.|
+
+INTERNALUNEXPECTEDERROR_ONE_ARGUMENT=\
+ ERR999E|\
+ Unexpected error. Description: {0}.|
+
+INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT=\
+ ERR999F|\
+ Unexpected error. Description: {0}.|
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.logging.format;
+
+import java.text.MessageFormat;
+import java.util.Map;
+
+import org.onap.portalsdk.core.util.SystemProperties;
+
+public class AuditLogFormatter {
+ //Singleton
+ private static AuditLogFormatter instance = new AuditLogFormatter();
+
+ public static AuditLogFormatter getInstance() {
+
+ return instance;
+ }
+
+ public String createMessage(String protocol,String set,
+ String loginId, String message) {
+
+ Object[] securityMessageArgs = prepareFormatArgs(
+ protocol,
+ set,
+ loginId,
+ message );
+
+ return MessageFormat.format(SystemProperties.SECURITY_LOG_TEMPLATE, securityMessageArgs);
+ }
+
+ /**
+ * A method for normalizing the security log field - returns
+ * the @Param defaultValue in case the entry is null or empty.
+ * If the @param entry is not empty, a single quotation is added to it.
+ *
+ * @param entry the entry
+ * @param defaultValue The default value in case the entry is empty
+ * @return String (formatted)
+ */
+ private String formatEntry(Object entry, String defaultValue) {
+ return (entry!=null && !entry.toString().isEmpty()) ? addSingleQuotes(entry.toString()): defaultValue;
+
+ }
+
+ private String addSingleQuotes(String s) {
+ if (null!=s && !s.isEmpty()) {
+ s = SystemProperties.SINGLE_QUOTE+s+SystemProperties.SINGLE_QUOTE;
+ }
+ return s;
+ }
+
+
+ /**
+ * This method prepares an Object array of arguments that would be passed
+ * to the MessageFormat.format() method, to format the security log.
+ *
+ * @param protocol
+ * @param set
+ * @param loginId
+ * @param accessingClient
+ * @param isSuccess
+ * @param message
+ * @return
+ */
+ private Object[] prepareFormatArgs(String protocol,String set,
+ String loginId, String message) {
+
+ Object[] messageFormatArgs = {
+ formatEntry(protocol, SystemProperties.NA),
+ formatEntry(set, SystemProperties.NA),
+ formatEntry(loginId, SystemProperties.UNKNOWN),
+ message
+ };
+ return messageFormatArgs;
+ }
+
+
+ public String createMessage(Map<String, String> logArgsMap) {
+
+ Object[] securityMessageArgs = prepareFormatArgs(
+ logArgsMap.get(SystemProperties.PROTOCOL),
+ logArgsMap.get(SystemProperties.SECURIRY_EVENT_TYPE),
+ logArgsMap.get(SystemProperties.LOGIN_ID),
+ logArgsMap.get(SystemProperties.ADDITIONAL_INFO)
+ );
+
+ return MessageFormat.format(SystemProperties.SECURITY_LOG_TEMPLATE, securityMessageArgs);
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.logging.format;
+
+import com.att.eelf.i18n.EELFResolvableErrorEnum;
+//import com.att.eelf.i18n.EELFResourceManager;
+
+public enum ErrorCodesEnum implements EELFResolvableErrorEnum {
+ BERESTAPIAUTHENTICATIONERROR,
+ BEHTTPCONNECTIONERROR_ONE_ARGUMENT,
+ BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT,
+
+ INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT,
+ INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT,
+ INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT,
+ INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT,
+
+ BEHEALTHCHECKRECOVERY,
+ BEHEALTHCHECKMYSQLRECOVERY,
+ BEHEALTHCHECKUEBCLUSTERRECOVERY,
+ FEHEALTHCHECKRECOVERY,
+ BeHEALTHCHECKERROR,
+
+ BEHEALTHCHECKMYSQLERROR,
+ BEHEALTHCHECKUEBCLUSTERERROR,
+ FEHEALTHCHECKERROR,
+ BEUEBCONNECTIONERROR_ONE_ARGUMENT,
+ BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT,
+ BEUEBREGISTERONBOARDINGAPPERROR,
+
+ INTERNALCONNECTIONINFO_ONE_ARGUMENT,
+ INTERNALCONNECTIONWARNING_ONE_ARGUMENT,
+ INTERNALCONNECTIONERROR_ONE_ARGUMENT,
+ INTERNALCONNECTIONFATAL_ONE_ARGUMENT,
+
+ BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT,
+ BEUSERMISSINGERROR_ONE_ARGUMENT,
+
+ BEUSERINACTIVEWARNING_ONE_ARGUMENT,
+ BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT,
+
+ BEINVALIDJSONINPUT,
+ BEINCORRECTHTTPSTATUSERROR,
+
+ BEINITIALIZATIONERROR,
+ BEUEBSYSTEMERROR,
+ BEDAOSYSTEMERROR,
+ BESYSTEMERROR,
+ BEEXECUTEROLLBACKERROR,
+
+ FEHTTPLOGGINGERROR,
+ FEPORTALSERVLETERROR,
+ BEDAOCLOSESESSIONERROR,
+
+ BERESTAPIGENERALERROR,
+ FEHEALTHCHECKGENERALERROR,
+
+ INTERNALUNEXPECTEDINFO_ONE_ARGUMENT,
+ INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT,
+ INTERNALUNEXPECTEDERROR_ONE_ARGUMENT,
+ INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT,
+
+ ;
+
+ /**
+ * Static initializer to ensure the resource bundles for this class are loaded...
+ * Here this application loads messages from three bundles
+ */
+ //static {
+ // EELFResourceManager.loadMessageBundle("com/att/fusion/core/logging/format/ApplicationCodes");
+ //}
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.logging.format;
+
+public enum ErrorSeverityEnum {
+ INFO,
+ WARN,
+ ERROR,
+ FATAL,
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.logging.format;
+
+public enum ErrorTypeEnum {
+ RECOVERY,
+ CONFIG_ERROR,
+ SYSTEM_ERROR,
+ DATA_ERROR,
+ CONNECTION_PROBLEM,
+ AUTHENTICATION_PROBLEM
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.logging.logic;
+
+import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
+import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
+import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
+import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
+import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
+import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
+import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
+
+import java.net.InetAddress;
+import java.text.MessageFormat;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.aspect.EELFLoggerAdvice;
+import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.onap.portalsdk.core.logging.format.AppMessagesEnum;
+import org.onap.portalsdk.core.logging.format.ErrorSeverityEnum;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.slf4j.MDC;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.att.eelf.configuration.SLF4jWrapper;
+
+public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger {
+
+ public static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();
+ public static EELFLogger applicationLogger = EELFManager.getInstance().getApplicationLogger();
+ public static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
+ public static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
+ public static EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger();
+ private String className;
+ private static ConcurrentMap<String, EELFLoggerDelegate> classMap = new ConcurrentHashMap<String, EELFLoggerDelegate>();
+
+ public EELFLoggerDelegate(String _className) {
+ super(_className);
+ className = _className;
+ }
+
+ /**
+ * Convenience method that gets a logger for the specified class.
+ *
+ * @see #getLogger(String)
+ *
+ * @param clazz
+ * @return Instance of EELFLoggerDelegate
+ */
+ public static EELFLoggerDelegate getLogger(Class<?> clazz) {
+ return getLogger(clazz.getName());
+ }
+
+ /**
+ * Gets a logger for the specified class name. If the logger does not
+ * already exist in the map, this creates a new logger.
+ *
+ * @param className
+ * If null or empty, uses EELFLoggerDelegate as the class name.
+ * @return Instance of EELFLoggerDelegate
+ */
+ public static EELFLoggerDelegate getLogger(String className) {
+ if (className == null || className == "")
+ className = EELFLoggerDelegate.class.getName();
+ EELFLoggerDelegate delegate = classMap.get(className);
+ if (delegate == null) {
+ delegate = new EELFLoggerDelegate(className);
+ classMap.put(className, delegate);
+ }
+ return delegate;
+ }
+
+ /**
+ * Logs a message at the lowest level: trace.
+ *
+ * @param logger
+ * @param msg
+ */
+ public void trace(EELFLogger logger, String msg) {
+ if (logger.isTraceEnabled()) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.trace(msg);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+ }
+
+ /**
+ * Logs a message with parameters at the lowest level: trace.
+ *
+ * @param logger
+ * @param msg
+ * @param arguments
+ */
+ public void trace(EELFLogger logger, String msg, Object... arguments) {
+ if (logger.isTraceEnabled()) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.trace(msg, arguments);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+ }
+
+ /**
+ * Logs a message and throwable at the lowest level: trace.
+ *
+ * @param logger
+ * @param msg
+ * @param th
+ */
+ public void trace(EELFLogger logger, String msg, Throwable th) {
+ if (logger.isTraceEnabled()) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.trace(msg, th);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+ }
+
+ /**
+ * Logs a message at the second-lowest level: debug.
+ *
+ * @param logger
+ * @param msg
+ */
+ public void debug(EELFLogger logger, String msg) {
+ if (logger.isDebugEnabled()) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.debug(msg);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+ }
+
+ /**
+ * Logs a message with parameters at the second-lowest level: debug.
+ *
+ * @param logger
+ * @param msg
+ * @param arguments
+ */
+ public void debug(EELFLogger logger, String msg, Object... arguments) {
+ if (logger.isDebugEnabled()) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.debug(msg, arguments);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+ }
+
+ /**
+ * Logs a message and throwable at the second-lowest level: debug.
+ *
+ * @param logger
+ * @param msg
+ * @param th
+ */
+ public void debug(EELFLogger logger, String msg, Throwable th) {
+ if (logger.isDebugEnabled()) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.debug(msg, th);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+ }
+
+ /**
+ * Logs a message at info level.
+ *
+ * @param logger
+ * @param msg
+ */
+ public void info(EELFLogger logger, String msg) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.info(msg);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+
+ /**
+ * Logs a message with parameters at info level.
+ *
+ * @param logger
+ * @param msg
+ * @param arguments
+ */
+ public void info(EELFLogger logger, String msg, Object... arguments) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.info(msg, arguments);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+
+ /**
+ * Logs a message and throwable at info level.
+ *
+ * @param logger
+ * @param msg
+ * @param th
+ */
+ public void info(EELFLogger logger, String msg, Throwable th) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.info(msg, th);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+
+ /**
+ * Logs a message at warn level.
+ *
+ * @param logger
+ * @param msg
+ */
+ public void warn(EELFLogger logger, String msg) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.warn(msg);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+
+ /**
+ * Logs a message with parameters at warn level.
+ *
+ * @param logger
+ * @param msg
+ * @param arguments
+ */
+ public void warn(EELFLogger logger, String msg, Object... arguments) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.warn(msg, arguments);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+
+ /**
+ * Logs a message and throwable at warn level.
+ *
+ * @param logger
+ * @param msg
+ * @param th
+ */
+ public void warn(EELFLogger logger, String msg, Throwable th) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.warn(msg, th);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+
+ /**
+ * Logs a message at error level.
+ *
+ * @param logger
+ * @param msg
+ */
+ public void error(EELFLogger logger, String msg) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.error(msg);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+
+ /**
+ * Logs a message with parameters at error level.
+ *
+ * @param logger
+ * @param msg
+ * @param arguments
+ */
+ public void error(EELFLogger logger, String msg, Object... arguments) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.warn(msg, arguments);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+
+ /**
+ * Logs a message and throwable at error level.
+ *
+ * @param logger
+ * @param msg
+ * @param th
+ */
+ public void error(EELFLogger logger, String msg, Throwable th) {
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.warn(msg, th);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+
+ /**
+ * Logs a message with the associated alarm severity at error level.
+ *
+ * @param logger
+ * @param msg
+ * @param severtiy
+ */
+ public void error(EELFLogger logger, String msg, AlarmSeverityEnum severtiy) {
+ MDC.put(MDC_ALERT_SEVERITY, severtiy.name());
+ MDC.put(SystemProperties.MDC_CLASS_NAME, className);
+ logger.error(msg);
+ MDC.remove(MDC_ALERT_SEVERITY);
+ MDC.remove(SystemProperties.MDC_CLASS_NAME);
+ }
+
+ /**
+ * Initializes the logger context.
+ */
+ public void init() {
+ setGlobalLoggingContext();
+ final String msg = "############################ Logging is started. ############################";
+ // These loggers emit the current date-time without being told.
+ info(applicationLogger, msg);
+ error(errorLogger, msg);
+ debug(debugLogger, msg);
+ // Audit and metrics logger must be told start AND stop times
+ final String currentDateTime = EELFLoggerAdvice.getCurrentDateTimeUTC();
+ // Set the MDC with audit properties
+ MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, currentDateTime);
+ MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, currentDateTime);
+ info(auditLogger, msg);
+ MDC.remove(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+ MDC.remove(SystemProperties.AUDITLOG_END_TIMESTAMP);
+ // Set the MDC with metrics properties
+ MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, currentDateTime);
+ MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, currentDateTime);
+ info(metricsLogger, msg);
+ MDC.remove(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP);
+ MDC.remove(SystemProperties.METRICSLOG_END_TIMESTAMP);
+ }
+
+ /**
+ * Logs a standard message identified by the specified enum, using the
+ * specified parameters, at error level. Alarm and error severity are taken
+ * from the specified enum argument.
+ *
+ * @param epMessageEnum
+ * @param param
+ */
+ public void logEcompError(AppMessagesEnum epMessageEnum, String... param) {
+ try {
+ AlarmSeverityEnum alarmSeverityEnum = epMessageEnum.getAlarmSeverity();
+ ErrorSeverityEnum errorSeverityEnum = epMessageEnum.getErrorSeverity();
+
+ MDC.put(MDC_ALERT_SEVERITY, alarmSeverityEnum.name());
+ MDC.put("ErrorCode", epMessageEnum.getErrorCode());
+ MDC.put("ErrorDescription", epMessageEnum.getErrorDescription());
+
+ String resolution = this.formatMessage(epMessageEnum.getDetails() + " " + epMessageEnum.getResolution(),
+ (Object[]) param);
+ if (errorSeverityEnum == ErrorSeverityEnum.WARN) {
+ errorLogger.warn(resolution);
+ } else if (errorSeverityEnum == ErrorSeverityEnum.INFO) {
+ errorLogger.info(resolution);
+ } else {
+ errorLogger.error(resolution);
+ }
+ } catch (Exception e) {
+ errorLogger.error("Failed to log the error code. Details: " + UserUtils.getStackTrace(e));
+ } finally {
+ MDC.remove("ErrorCode");
+ MDC.remove("ErrorDescription");
+ MDC.remove(MDC_ALERT_SEVERITY);
+ }
+ }
+
+ /**
+ * Builds a message using a template string and the arguments.
+ *
+ * @param message
+ * @param args
+ * @return
+ */
+ private String formatMessage(String message, Object... args) {
+ StringBuilder sbFormattedMessage = new StringBuilder();
+ if (args != null && args.length > 0 && message != null && message != "") {
+ MessageFormat mf = new MessageFormat(message);
+ sbFormattedMessage.append(mf.format(args));
+ } else {
+ sbFormattedMessage.append(message);
+ }
+
+ return sbFormattedMessage.toString();
+ }
+
+ /**
+ * Loads all the default logging fields into the MDC context.
+ */
+ private void setGlobalLoggingContext() {
+ MDC.put(MDC_SERVICE_INSTANCE_ID, "");
+ MDC.put(MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.toString());
+ try {
+ MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
+ MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
+ MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID));
+ } catch (Exception e) {
+ }
+ }
+
+ public static void mdcPut(String key, String value) {
+ MDC.put(key, value);
+ }
+
+ public static String mdcGet(String key) {
+ return MDC.get(key);
+ }
+
+ public static void mdcRemove(String key) {
+ MDC.remove(key);
+ }
+
+ /**
+ * Loads the RequestId/TransactionId into the MDC which it should be
+ * receiving with an each incoming REST API request. Also, configures few
+ * other request based logging fields into the MDC context.
+ *
+ * @param req
+ * @param appName
+ */
+ public void setRequestBasedDefaultsIntoGlobalLoggingContext(HttpServletRequest req, String appName) {
+ // Load the default fields
+ setGlobalLoggingContext();
+
+ // Load the request based fields
+ if (req != null) {
+ // Load the Request into MDC context.
+ String requestId = UserUtils.getRequestId(req);
+ MDC.put(MDC_KEY_REQUEST_ID, requestId);
+
+ // Load user agent into MDC context, if available.
+ String accessingClient = "Unknown";
+ accessingClient = req.getHeader(SystemProperties.USERAGENT_NAME);
+ if (accessingClient != null && accessingClient != "" && (accessingClient.contains("Mozilla")
+ || accessingClient.contains("Chrome") || accessingClient.contains("Safari"))) {
+ accessingClient = appName + "_FE";
+ }
+ MDC.put(SystemProperties.PARTNER_NAME, accessingClient);
+
+ // Protocol, Rest URL & Rest Path
+ String restURL = "";
+ MDC.put(SystemProperties.FULL_URL, SystemProperties.UNKNOWN);
+ MDC.put(SystemProperties.PROTOCOL, SystemProperties.HTTP);
+ restURL = UserUtils.getFullURL(req);
+ if (restURL != null && restURL != "") {
+ MDC.put(SystemProperties.FULL_URL, restURL);
+ if (restURL.toLowerCase().contains("https")) {
+ MDC.put(SystemProperties.PROTOCOL, SystemProperties.HTTPS);
+ }
+ }
+
+ // Rest Path
+ MDC.put(MDC_SERVICE_NAME, req.getServletPath());
+
+ // Client IPAddress i.e. IPAddress of the remote host who is making
+ // this request.
+ String clientIPAddress = "";
+ clientIPAddress = req.getHeader("X-FORWARDED-FOR");
+ if (clientIPAddress == null) {
+ clientIPAddress = req.getRemoteAddr();
+ }
+ MDC.put(SystemProperties.CLIENT_IP_ADDRESS, clientIPAddress);
+
+ // Load loginId into MDC context.
+ MDC.put(SystemProperties.MDC_LOGIN_ID, "Unknown");
+
+ String loginId = "";
+ User user = UserUtils.getUserSession(req);
+ if (user != null) {
+ loginId = user.getLoginId();
+ }
+
+ if (loginId != null && loginId != "") {
+ MDC.put(SystemProperties.MDC_LOGIN_ID, loginId);
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.menu;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.FusionObject;
+import org.onap.portalsdk.core.domain.MenuData;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+
+@SuppressWarnings("rawtypes")
+public class MenuBuilder implements FusionObject {
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ public MenuBuilder() {
+ }
+
+ @SuppressWarnings("unchecked")
+ public Set getMenu(String menuSetName, DataAccessService dataAccessService) {
+
+ Set menu = null;
+ MenuData root = null;
+
+ HashMap params = new HashMap();
+
+ params.put("menu_set_cd", menuSetName);
+
+ // execute a query of the latest configuration of the FN_MENU table for the given menu_set_cd.
+ List menuItems = dataAccessService.executeNamedQuery(SystemProperties.getProperty(SystemProperties.MENU_QUERY_NAME), params, null);
+
+ Iterator i = menuItems.iterator();
+ if (i.hasNext()) {
+ root = (MenuData)i.next();
+ menu = root.getChildMenus();
+ }
+
+ return menu;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Set getMenu(String menuSetName) {
+
+ Set menu = null;
+ MenuData root = null;
+
+ HashMap params = new HashMap();
+
+ params.put("menu_set_cd", menuSetName);
+
+ // execute a query of the latest configuration of the FN_MENU table for the given menu_set_cd.
+ List menuItems = getDataAccessService().executeNamedQuery(SystemProperties.getProperty(SystemProperties.MENU_QUERY_NAME), params, null);
+
+ Iterator i = menuItems.iterator();
+ if (i.hasNext()) {
+ root = (MenuData)i.next();
+ menu = root.getChildMenus();
+ }
+
+ return menu;
+ }
+
+ public static Set filterMenu(Set menus, HttpServletRequest request) {
+ Iterator j = menus.iterator();
+
+ while (j.hasNext()) {
+ MenuData menuItem = (MenuData)j.next();
+
+ if (!UserUtils.isAccessible(request, menuItem.getFunctionCd())) {
+ // remove the menu if the user doesn't have access to it
+ j.remove();
+ }
+ else {
+ // if an accessible menu has a child menu, let's filter that recursively
+
+ Set childMenus = menuItem.getChildMenus();
+ if (childMenus != null && childMenus.size() > 0) {
+ filterMenu(childMenus, request);
+ }
+
+ }
+ }
+
+ return menus;
+ }
+
+
+ public static String getUrlHtml(MenuData menuData) {
+ String html = "";
+
+ if (menuData.getExternalUrl() != null && menuData.getExternalUrl().length() > 0) {
+ html = menuData.getExternalUrl();
+ }
+ else if (menuData.getServlet() != null && menuData.getServlet().length() > 0) {
+ html = "/" + menuData.getServlet();
+ }
+ else if (menuData.getAction() != null && menuData.getAction().length() > 0) {
+ html = "/" + menuData.getAction();
+ }
+
+ return html;
+ }
+
+
+ public static String getTargetHtml(MenuData menuData) {
+ String html = "";
+
+ if (menuData.getTarget() != null && menuData.getTarget().length() > 0) {
+ html = "target=\"" + menuData.getTarget() + "\"";
+ }
+
+ return html;
+ }
+
+
+ public static String getQueryStringHtml(MenuData menuData) {
+ String html = "";
+
+ if (menuData.getQueryString() != null && menuData.getQueryString().length() > 0) {
+ html = "?" + menuData.getQueryString();
+ }
+
+ return html;
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+}
+
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.menu;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Properties;
+
+import javax.servlet.ServletContext;
+
+import org.onap.portalsdk.core.util.SystemProperties;
+
+
+/*
+ MenuProperties contains a list of constants used during the creation,
+ privilege screening, and rendering of the application menu.
+*/
+public class MenuProperties {
+ private MenuProperties() {
+ // cannot instantiate
+ }
+
+ @SuppressWarnings("rawtypes")
+ private static HashMap menuProperties = new HashMap();
+
+ // keys used to reference values in the menu.properties file
+ public static final String WIDTH = "width";
+ public static final String LEFT_POSITION = "left_position";
+ public static final String TOP_POSITION = "top_position";
+ public static final String FONT_COLOR = "font_color";
+ public static final String MOUSEOVER_FONT_COLOR = "mouseover_font_color";
+ public static final String BACKGROUND_COLOR = "background_color";
+ public static final String MOUSEOVER_BACKGROUND_COLOR = "mouseover_background_color";
+ public static final String BORDER_COLOR = "border_color";
+ public static final String SEPARATOR_COLOR = "separator_color";
+ public static final String IMAGE_SRC = "image_src";
+ public static final String IMAGE_SRC_LEFT = "image_src_left";
+ public static final String IMAGE_SRC_OVER = "image_src_over";
+ public static final String IMAGE_SRC_LEFT_OVER = "image_src_left_over";
+ public static final String EVALUATE_UPON_TREE_SHOW = "evaluate_upon_tree_show";
+ public static final String EVALUATE_UPON_TREE_HIDE = "evaluate_upon_tree_hide";
+ public static final String TOP_IS_PERMANENT = "top_is_permanent";
+ public static final String TOP_IS_HORIZONTAL = "top_is_horizontal";
+ public static final String TREE_IS_HORIZONTAL = "tree_is_horizontal";
+ public static final String POSITION_UNDER = "position_under";
+ public static final String TOP_MORE_IMAGES_VISIBLE = "top_more_images_visible";
+ public static final String TREE_MORE_IMAGES_VISIBLE = "tree_more_images_visible";
+ public static final String RIGHT_TO_LEFT = "right_to_left";
+ public static final String DISPLAY_ON_CLICK = "display_on_click";
+ public static final String TOP_IS_VARIABLE_WIDTH = "top_is_variable_width";
+ public static final String TREE_IS_VARIABLE_WIDTH = "tree_is_variable_width";
+ public static final String TOP_KEEP_IN_WINDOW_X = "top_keep_in_window_x";
+ public static final String TOP_KEEP_IN_WINDOW_Y = "top_keep_in_window_y";
+ public static final String MENU_ID_ADMIN = "menu_id_admin";
+ public static final String MENU_ID_LOGOUT = "menu_id_logout";
+ public static final String MENU_FRAME = "menu_frame";
+ public static final String MAIN_FRAME = "main_frame";
+ public static final String NESTED_MAIN_FRAME = "nested_main_frame";
+ public static final String ROLE_FUNCTIONS_TAG = "role_functions_tag";
+
+ public static final String MAX_DISPLAYABLE_ADMIN_MENU_SORT_ORDER = "max_displayable_admin_menu_sort_order";
+ public static final String MENU_PROPERTIES_FILENAME_KEY = "menu_properties_filename";
+ public static final String DEFAULT_SERVLET_NAME = "dispatcher";
+ public static final String DEFAULT_TARGET = "_self";
+
+ public static final String TOP_MENU_CLASS = "top_menu_class";
+ public static final String TOP_MENU_LINK_CLASS = "top_menu_link_class";
+
+ public static final String ON_MOUSE_OUT_TRAILER = "on_mouse_out_trailer";
+ public static final String ON_MOUSE_OVER_TRAILER = "on_mouse_over_trailer";
+ public static final String ON_CLICK_TRAILER = "on_click_trailer";
+
+ public static final String MENU_ID_PREFIX = "menu_id_prefix";
+
+
+ @SuppressWarnings("unchecked")
+ public static void loadFromFile(ServletContext servletContext, String filename, String menuSetName) throws IOException {
+ Properties p = new Properties();
+
+ if (filename == null) {
+ filename = SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_PROPERTIES_NAME);
+ }
+
+ p.load(servletContext.getResourceAsStream(SystemProperties.getProperty(SystemProperties.MENU_PROPERTIES_FILE_LOCATION) + filename));
+ menuProperties.put(menuSetName, p);
+ } // loadMenuProperties
+
+ public static String getProperty(String key) {
+ return getProperty(key, SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME));
+ }
+
+ public static String getProperty(String key, String menuSetName) {
+ Properties p = (Properties)menuProperties.get(menuSetName);
+ return p.getProperty(key);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.objectcache;
+
+import java.io.*;
+
+import org.onap.portalsdk.core.objectcache.support.*;
+
+
+public abstract class AbstractCacheManager implements FusionCacheManager {
+ public AbstractCacheManager() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+
+ public Object getObject(String key) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public void putObject(String key, Object objectToCache) {
+ // TODO Auto-generated method stub
+ }
+
+ public boolean isObjectInCache(String key) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public void removeObject(String key) {
+ // TODO Auto-generated method stub
+ }
+
+ public void clearCache() {
+ // TODO Auto-generated method stub
+ }
+
+ public void configure() throws IOException {
+ // TODO Auto-generated method stub
+
+ }
+}
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.objectcache.jcs;
+
+import org.apache.jcs.engine.control.event.behavior.IElementEvent;
+import org.apache.jcs.engine.control.event.behavior.IElementEventConstants;
+import org.apache.jcs.engine.control.event.behavior.IElementEventHandler;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class JCSCacheEventHandler implements IElementEventHandler, IElementEventConstants {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JCSCacheEventHandler.class);
+
+ public JCSCacheEventHandler() {
+ super();
+ }
+
+ public void handleElementEvent(IElementEvent event) {
+ // Handle code for various event notifications on cached elements by JCS.
+ switch (event.getElementEvent()) {
+ case ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND:
+ logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND occurred for element " + event);
+ break;
+ case ELEMENT_EVENT_EXCEEDED_MAXLIFE_ONREQUEST:
+ logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_MAXLIFE_ONREQUEST occurred for element " + event);
+ break;
+ case ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND:
+ logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND occurred for element " + event);
+ break;
+ case ELEMENT_EVENT_EXCEEDED_IDLETIME_ONREQUEST:
+ logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_IDLETIME_ONREQUEST occurred for element " + event);
+ break;
+ case ELEMENT_EVENT_SPOOLED_DISK_AVAILABLE:
+ logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_SPOOLED_DISK_AVAILABLE occurred for element " + event);
+ break;
+ case ELEMENT_EVENT_SPOOLED_DISK_NOT_AVAILABLE:
+ logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_SPOOLED_DISK_NOT_AVAILABLE occurred for element " + event);
+ break;
+ case ELEMENT_EVENT_SPOOLED_NOT_ALLOWED:
+ logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_SPOOLED_NOT_ALLOWED occurred for element " + event);
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.objectcache.jcs;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+import java.util.Vector;
+
+import javax.annotation.PostConstruct;
+import javax.servlet.ServletContext;
+
+import org.apache.jcs.JCS;
+import org.apache.jcs.access.exception.CacheException;
+import org.apache.jcs.engine.CacheConstants;
+import org.apache.jcs.engine.behavior.IElementAttributes;
+import org.apache.jcs.engine.control.CompositeCacheManager;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.objectcache.AbstractCacheManager;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.web.context.ServletContextAware;
+
+public abstract class JCSCacheManager extends AbstractCacheManager implements CacheConstants, ServletContextAware {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JCSCacheManager.class);
+
+ public static String LOOKUP_OBJECT_CACHE_NAME = "lookUpObjectCache";
+ public static String JCS_CONFIG_FILE_PATH = "cache_config_file_path";
+ public static String CACHE_LOAD_ON_STARTUP = "cache_load_on_startup";
+ public static String CACHE_PROPERTY_VALUE_TRUE = "true";
+ public static String CACHE_CONTROL_SWITCH_ON = "1";
+ public static String CACHE_CONTROL_SWITCH_OFF = "0";
+ public static String CACHE_CONTROL_SWITCH = "cache_switch";
+
+ private static JCS lookUpCache;
+ private ServletContext servletContext;
+
+ private Properties cacheConfigProperties = null;
+ private final Vector<String> jscManagedCacheList = new Vector<String>();
+
+ private DataAccessService dataAccessService;
+
+ public JCSCacheManager() {
+ super();
+ jscManagedCacheList.add(LOOKUP_OBJECT_CACHE_NAME);
+ }
+
+ @PostConstruct
+ public void configure() throws IOException {
+ super.configure();
+
+ String jcsConfigFilePath = SystemProperties.getProperty(JCS_CONFIG_FILE_PATH);
+ // getProperty throws if the key is missing; but check anyhow.
+ if (jcsConfigFilePath == null || jcsConfigFilePath.length() == 0)
+ throw new IOException("configure: failed to get value for config property " + JCS_CONFIG_FILE_PATH);
+ InputStream jcsConfigInputStream = getServletContext().getResourceAsStream(jcsConfigFilePath);
+ if (jcsConfigInputStream == null)
+ throw new IOException("configure: failed to open stream for config property " + JCS_CONFIG_FILE_PATH
+ + " with name " + jcsConfigFilePath);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "configure: loading cache properties from classpath resource {} ", jcsConfigFilePath);
+ Properties p = new Properties();
+ p.load(jcsConfigInputStream);
+ jcsConfigInputStream.close();
+
+ CompositeCacheManager ccm = CompositeCacheManager.getUnconfiguredInstance();
+ ccm.configure(p);
+ setCacheConfigProperties(p);
+
+ try {
+ initializeLookUpCache();
+ } catch (CacheException ce) {
+ throw new IOException("configure: failed to initialize lookup cache", ce);
+ }
+
+ }
+
+ private void initializeLookUpCache() throws CacheException {
+ lookUpCache = JCS.getInstance(LOOKUP_OBJECT_CACHE_NAME);
+
+ JCSCacheEventHandler eventHandler = new JCSCacheEventHandler();
+ IElementAttributes elementAttributes = lookUpCache.getDefaultElementAttributes();
+
+ elementAttributes.addElementEventHandler(eventHandler);
+
+ lookUpCache.setDefaultElementAttributes(elementAttributes);
+
+ if (CACHE_PROPERTY_VALUE_TRUE.equalsIgnoreCase(SystemProperties.getProperty(CACHE_LOAD_ON_STARTUP))) {
+ loadDataOnStartUp();
+ }
+ }
+
+ public Object getObject(String key) {
+ if (CACHE_CONTROL_SWITCH_ON.equalsIgnoreCase(SystemProperties.getProperty(CACHE_CONTROL_SWITCH))) {
+ if (lookUpCache == null)
+ return null;
+ else
+ return lookUpCache.get(key);
+ } else
+ return null;
+ }
+
+ public void putObject(String key, Object objectToCache) {
+ try {
+ if (CACHE_CONTROL_SWITCH_ON.equalsIgnoreCase(SystemProperties.getProperty(CACHE_CONTROL_SWITCH))) {
+ if (lookUpCache != null) {
+ lookUpCache.put(key, objectToCache);
+ }
+ }
+ } catch (CacheException ce) {
+ logger.error(EELFLoggerDelegate.errorLogger, "putObject: failed to put the object with key " + key, ce);
+ }
+ }
+
+ public void clearCache(String region) {
+ try {
+ if (region.equals(LOOKUP_OBJECT_CACHE_NAME))
+ lookUpCache.clear();
+ } catch (CacheException ce) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "clearCache: failed to clear the cache for the region " + region, ce);
+ }
+ }
+
+ public void clearCache() {
+ clearCache(LOOKUP_OBJECT_CACHE_NAME);
+ }
+
+ private void loadDataOnStartUp() {
+ loadLookUpCache();
+ }
+
+ public abstract void loadLookUpCache();
+
+ public void refreshLookUpCache() {
+ clearCache(LOOKUP_OBJECT_CACHE_NAME);
+ loadLookUpCache();
+ }
+
+ public Properties getCacheConfigProperties() {
+ return cacheConfigProperties;
+ }
+
+ public void setCacheConfigProperties(Properties cacheConfigProperties) {
+ this.cacheConfigProperties = cacheConfigProperties;
+ }
+
+ public Vector<String> getJscManagedCacheList() {
+ return jscManagedCacheList;
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ public ServletContext getServletContext() {
+ return servletContext;
+ }
+
+ public void setServletContext(ServletContext servletContext) {
+ this.servletContext = servletContext;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.objectcache.support;
+
+import java.io.*;
+
+import org.onap.portalsdk.core.FusionObject;
+
+public interface FusionCacheManager extends FusionObject {
+
+ Object getObject(String key);
+ void putObject(String key, Object objectToCache);
+ boolean isObjectInCache(String key);
+
+ void removeObject(String key);
+ void clearCache();
+ void configure() throws IOException;
+}
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.client;
+
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.stereotype.Component;
+
+/**
+ *
+ *
+ * Use this class to get access to ApplicationContext for classes who were not created by Spring.
+ */
+
+
+@Component
+public class AppContextManager implements ApplicationContextAware{
+ private static ApplicationContext _appCtx;
+
+ @Override
+ public void setApplicationContext(ApplicationContext ctx){
+ _appCtx = ctx;
+ }
+
+ public static ApplicationContext getAppContext(){
+ return _appCtx;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.session;
+
+public class TestClass {
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.sso;
+
+public class TestClass {
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.ueb;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.util.LinkedList;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+
+import com.att.nsa.cambria.client.CambriaClientBuilders;
+import com.att.nsa.cambria.client.CambriaConsumer;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * Provides a consumer that reads messages from a UEB topic. Intended to be
+ * passed to a separate thread as its runnable object.
+ */
+public class Consumer implements Runnable {
+
+ private final Log logger = LogFactory.getLog(getClass());
+
+ private final LinkedList<String> urlList = Helper.uebUrlList();
+ private final ConcurrentLinkedQueue<UebMsg> queue;
+ private final WaitingRequestersQueueList waitingRequestersList;
+ private final String consumerKey, consumerSecret, topicName, consumerGroupName;
+
+ /**
+ * Accepts coordinates needed to subscribe to a UEB topic, as well as the
+ * queues for passing along messages that arrive.
+ *
+ * @param consumerKey
+ * UEB key used to subscribe to the topic
+ * @param consumerSecret
+ * UEB secret used to subscribe to the topic
+ * @param topicName
+ * UEB topic name
+ * @param queue
+ * Queue to receive UEB messages. All inbound messages are
+ * enqueued here; ignored if null.
+ * @param waitingRequestersList
+ * Collection of queues to receive UEB messages that arrive in
+ * response to requests; i.e., emulating a synchronous request
+ * via pub/sub.
+ */
+ public Consumer(String consumerKey, String consumerSecret, String topicName, String consumerGroupName,
+ ConcurrentLinkedQueue<UebMsg> queue, WaitingRequestersQueueList waitingRequestersList) {
+ this.consumerKey = consumerKey;
+ this.consumerSecret = consumerSecret;
+ this.topicName = topicName;
+ this.consumerGroupName = consumerGroupName;
+ this.queue = queue;
+ this.waitingRequestersList = waitingRequestersList;
+ }
+
+ /**
+ * Subscribes to a topic using credentials as supplied to the constructor.
+ * Distributes messages appropriately as they arrive:
+ * <UL>
+ * <LI>If the queue is not null, adds the message to the queue.
+ * <LI>If the message's getMsgId() method returns non-null and the ID is
+ * found in the collection of waiting requesters, adds the message in that
+ * requester's queue.
+ * </UL>
+ *
+ * This is intended to be called in a long running thread as a listener for
+ * any published messages on a topic. Typical async pub/sub model. We use a
+ * filter of "0" to prevent collisions with P2P messages with unique filter
+ * ids.
+ */
+ protected void consume() throws IOException, UebException, GeneralSecurityException {
+ final String id = UUID.randomUUID().toString();
+
+ CambriaConsumer cc = null;
+ cc = new CambriaClientBuilders.ConsumerBuilder()
+ .usingHosts(urlList)
+ .authenticatedBy(consumerKey, consumerSecret)
+ .onTopic (topicName)
+ .knownAs (consumerGroupName,id)
+ .waitAtServer (15*1000)
+ .receivingAtMost (1000)
+ .build();
+
+ while (true) {
+ for (String msg : cc.fetch()) {
+ logger.debug(" <== consume from topicName " + topicName + " msg: " + msg);
+ UebMsg uebMsg = new ObjectMapper().readValue(msg, UebMsg.class);
+ if (queue != null) {
+ // Add to general queue allowing listeners to act on any
+ // incoming messages. We don't know if a listener is
+ // also going to be a responder to a synchronous
+ // request. So put all received messages on the general
+ // listener queue.
+ queue.add(uebMsg);
+ if (logger.isDebugEnabled())
+ logger.debug("Added msg to queue " + this.queue + " queue count = " + queue.size() + " msg :"
+ + uebMsg.getPayload());
+ }
+ if (waitingRequestersList != null && uebMsg.getMsgId() != null) {
+ // If a msgId is present, this could be a synchronous
+ // reply. Here we add it to the waiting requester's
+ // queue if we find a requester waiting for this msgId.
+ if (!(uebMsg.getMsgId()
+ .equals(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_DEFAULT_MSG_ID)))) {
+ waitingRequestersList.addMsg(uebMsg.getMsgId(), uebMsg);
+ }
+ }
+ }
+ if (Thread.interrupted()) {
+ logger.warn(Thread.currentThread() + " interrupted, exiting");
+ break;
+ }
+ Helper.sleep(10);
+ }
+
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Runnable#run()
+ */
+ @Override
+ public void run() {
+ try {
+ consume();
+ } catch (Exception ex) {
+ Thread t = Thread.currentThread();
+ t.getUncaughtExceptionHandler().uncaughtException(t, ex);
+ }
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.ueb;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Provides a convenience method for fetching the functional menu for a user
+ * from the ECOMP Portal via UEB.
+ */
+public class FunctionalMenu {
+
+ private static final Log logger = LogFactory.getLog(FunctionalMenu.class);
+
+ /**
+ * Makes a synchronous call to ECOMP Portal to get JSON with the functional
+ * menu, which arrives as the payload of the returned UEB message.
+ *
+ * @param userId
+ * User ID as known on the ECOMP Portal for customizing the
+ * functional menu appropriately
+ * @return JSON with functional menu
+ * @throws UebException
+ */
+ public static String get(String userId) throws UebException {
+ String returnString = null;
+ logger.info("Making use of UEB communication and Requesting functional menu for user " + userId);
+ UebMsg funcMenuUebMsg = null;
+ UebMsg msg = new UebMsg();
+ msg.putMsgType(UebMsgTypes.UEB_MSG_TYPE_GET_FUNC_MENU);
+ msg.putUserId(userId);
+ funcMenuUebMsg = UebManager.getInstance().requestReply(msg);
+ if (funcMenuUebMsg != null) {
+ if (funcMenuUebMsg.getPayload().startsWith("Error:")) {
+ logger.error("getFunctionalMenu received an error in UEB msg = " + funcMenuUebMsg.getPayload());
+ } else {
+ returnString = funcMenuUebMsg.getPayload();
+ }
+ }
+ return returnString;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.ueb;
+
+import java.util.LinkedList;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+
+/**
+ * Provides utility methods.
+ */
+public class Helper {
+
+ private static final Log logger = LogFactory.getLog(Helper.class);
+
+ /**
+ * Parses a comma-separated list of UEB servers from properties file into a
+ * list.
+ *
+ * @return List of UEB server names
+ */
+ public static LinkedList<String> uebUrlList() {
+ LinkedList<String> urlList = null;
+ String url = PortalApiProperties.getProperty(PortalApiConstants.UEB_URL_LIST);
+ if (url == null) {
+ logger.error("uebUrlList: failed to get property " + PortalApiConstants.UEB_URL_LIST);
+ return null;
+ }
+ urlList = new LinkedList<String>();
+ for (String u : url.split(",")) {
+ urlList.add(u.trim());
+ }
+ return urlList;
+ }
+
+ public static void sleep(int milliseconds) {
+ try {
+ Thread.sleep(milliseconds);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.ueb;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.security.GeneralSecurityException;
+import java.util.LinkedList;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+
+import com.att.nsa.cambria.client.CambriaBatchingPublisher;
+import com.att.nsa.cambria.client.CambriaClientBuilders;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectWriter;
+
+/**
+ * Provides a publisher that sends messages to a UEB topic.
+ *
+ * Utilizes AT&T's UEB/Cambria subscriber/publisher messaging service.
+ */
+public class Publisher {
+
+ private final Log logger = LogFactory.getLog(getClass());
+
+ protected final LinkedList<String> urlList = Helper.uebUrlList();
+
+ private final String topicName;
+ private final String publisherKey;
+ private final String publisherSecret;
+
+ /**
+ * Accepts coordinates needed to publish to a UEB topic.
+ *
+ * @param publisherKey
+ * UEB key used to publish to the topic
+ * @param publisherSecret
+ * UEB secret used to publish to the topic
+ * @param topicName
+ * UEB topic name
+ */
+ public Publisher(String publisherKey, String publisherSecret, String topicName) {
+ this.publisherKey = publisherKey;
+ this.publisherSecret = publisherSecret;
+ this.topicName = topicName;
+ logger.info("Publisher instantiated for topic " + topicName);
+ }
+
+ /**
+ * Creates a publisher, subscribes to the topic, sends the specified message
+ * to the topic, then closes the publisher. This ensures that the single
+ * message goes immediately. UEB is designed for high throughput and tries
+ * to batch up multiple messages in each send, but this method wants the
+ * single message to go immediately.
+ *
+ * @param uebMsg
+ * Message object to send as the payload.
+ * @throws UebException
+ * If anything goes wrong, including JSON serialization of the
+ * specified message object.
+ */
+ public void send(UebMsg uebMsg) throws UebException {
+ String msg = null;
+
+ CambriaBatchingPublisher pub;
+ try {
+ pub = new CambriaClientBuilders.PublisherBuilder()
+ .authenticatedBy(publisherKey, publisherSecret).usingHosts(urlList).onTopic(topicName).build();
+ } catch (MalformedURLException e1) {
+ logger.error("pub.build Exception ", e1);
+ throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, e1, topicName, null, msg);
+ } catch (GeneralSecurityException e1) {
+ logger.error("pub.build Exception ", e1);
+ throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, e1, topicName, null, msg);
+ }
+
+ try {
+ ObjectWriter mapper = new ObjectMapper().writer().withDefaultPrettyPrinter();
+ msg = mapper.writeValueAsString(uebMsg);
+ } catch (JsonProcessingException e) {
+ throw new UebException(PortalApiConstants.ECOMP_UEB_INVALID_MSG, topicName, null, null);
+ }
+
+ try {
+ logger.debug("Publishing to " + topicName + " msg: " + msg);
+ int NumSent = pub.send(PortalApiConstants.ECOMP_GENERAL_UEB_PARTITION, msg);
+ if (NumSent == 0) {
+ throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, topicName, null, msg);
+ }
+ } catch (IOException ex) {
+ logger.error("Failed to publish", ex);
+ throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, ex, topicName, null, msg);
+ }
+
+ try {
+ // close the publisher to make sure everything's sent before exiting
+ pub.close(5, TimeUnit.SECONDS);
+ } catch (Exception ex) {
+ logger.error("pub.close Exception ", ex);
+ throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, ex, topicName, null, msg);
+ }
+
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.ueb;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * A thin wrapper around ConcurrentHashMap that stores a queue for each
+ * Requester that is waiting for a Reply. When a reply is received that has a
+ * matching msgId, that requesters queue is populated with the reply message.
+ *
+ * Primarily for Portal core to track the remote applications that have placed
+ * requests; never used by those applications.
+ */
+public class PublisherList {
+
+ private final Log logger = LogFactory.getLog(getClass());
+
+ private final Map<String, Publisher> map;
+
+ public PublisherList() {
+ map = new ConcurrentHashMap<>();
+ }
+
+ public void addPublisherToMap(String topicName, Publisher publisher) {
+ if (this.map.containsKey(topicName)) {
+ logger.error("Publisher already exists for " + topicName);
+ } else {
+ this.map.put(topicName, publisher);
+ }
+ }
+
+ public Publisher getPublisher(String topicName) {
+ return this.map.get(topicName);
+ }
+
+ public void removePublisherFromMap(String topicName) {
+ this.map.remove(topicName);
+ }
+
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.append("Map contains " + this.map.size() + " Publishers.");
+ for (Map.Entry<String, Publisher> entry : this.map.entrySet()) {
+ String key = entry.getKey().toString();
+ Publisher pub = entry.getValue();
+ sb.append("Entry msgId, " + key + " publisher" + pub);
+ }
+ return sb.toString();
+ }
+
+ public int size() {
+ return this.map.size();
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.ueb;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.util.LinkedList;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.att.nsa.apiClient.http.HttpClient;
+import com.att.nsa.apiClient.http.HttpException;
+import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
+import com.att.nsa.cambria.client.CambriaClientBuilders;
+import com.att.nsa.cambria.client.CambriaClientFactory;
+import com.att.nsa.cambria.client.CambriaTopicManager;
+
+/**
+ * Provides methods to facilitate creating topics, and adding publishers and
+ * subscribers to existing topics.
+ *
+ * Utilizes UEB/Cambria subscriber/publisher messaging service.
+ */
+public class TopicManager {
+
+ private final Log logger = LogFactory.getLog(getClass());
+
+ /**
+ * Creates a topic with the specified information.
+ *
+ * @param key
+ * Topic key
+ * @param secret
+ * Topic secret key
+ * @param topicName
+ * Topic name
+ * @param topicDescription
+ * Topic description
+ * @throws HttpException
+ * @throws CambriaApiException
+ * @throws IOException
+ */
+ public void createTopic(String key, String secret, String topicName, String topicDescription)
+ throws HttpException, CambriaApiException, IOException {
+ final LinkedList<String> urlList = Helper.uebUrlList();
+ if (logger.isInfoEnabled()) {
+ logger.info("==> createTopic");
+ logger.info("topicName: " + topicName);
+ logger.info("topicDescription: " + topicDescription);
+ }
+ CambriaTopicManager tm =null;
+ try {
+ tm = CambriaClientFactory.createTopicManager(null, urlList, key, secret);
+ } catch (GeneralSecurityException e) {
+ logger.error("pub.build Exception ", e);
+ throw new CambriaApiException(topicName);
+ }
+ tm.createTopic(topicName, topicDescription, 1, 1);
+ }
+
+ /**
+ * Modifies the specified topic to accept a subscriber using the specified
+ * key.
+ *
+ * @param topicOwnerKey
+ * @param topicOwnerSecret
+ * @param subscriberKey
+ * @param topicName
+ * @throws HttpException
+ * @throws CambriaApiException
+ * @throws IOException
+ */
+ public void addSubscriber(String topicOwnerKey, String topicOwnerSecret, String subscriberKey, String topicName)
+ throws HttpException, CambriaApiException, IOException {
+ logger.info("==> addSubscriber to topic " + topicName);
+ final LinkedList<String> urlList = Helper.uebUrlList();
+ CambriaTopicManager tm = null;
+ try {
+ tm = new CambriaClientBuilders.TopicManagerBuilder().usingHosts(urlList).authenticatedBy(topicOwnerKey, topicOwnerSecret).build();
+ tm.allowConsumer(topicName, subscriberKey);
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ logger.error("addSubscriber failed", e);
+ }
+ }
+
+ /**
+ * Modifies the specified topic to accept a publisher using the specified
+ * key.
+ *
+ * @param topicOwnerKey
+ * @param topicOwnerSecret
+ * @param publisherKey
+ * @param topicName
+ * @throws HttpException
+ * @throws CambriaApiException
+ * @throws IOException
+ */
+
+ @SuppressWarnings("deprecation")
+ public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey, String topicName)
+ throws HttpException, CambriaApiException, IOException {
+ logger.info("==> addPublisher to topic " + topicName);
+ final LinkedList<String> urlList = Helper.uebUrlList();
+ CambriaTopicManager tm =null;
+ try {
+ tm = CambriaClientFactory.createTopicManager(HttpClient.ConnectionType.HTTPS, urlList, topicOwnerKey,
+ topicOwnerSecret);
+ } catch (GeneralSecurityException e) {
+ logger.error("pub.build Exception ", e);
+ throw new CambriaApiException(topicName);
+ }
+ tm.allowProducer(topicName, publisherKey);
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.ueb;
+
+/**
+ * Stores UEB-specific information including topic, message ID and message body.
+ */
+public class UebException extends Exception {
+
+ private static final long serialVersionUID = 1L;
+ private String topicName = null;
+ private String msgId = null;
+ private String msg = null;
+
+ public UebException(String errorMsg, String topicName, String msgId, String msg) {
+ super(errorMsg);
+ this.topicName = topicName;
+ this.msgId = msgId;
+ this.msg = msg;
+ }
+
+ public UebException(String errorMsg, Throwable ex, String topicName, String msgId, String msg) {
+ super(errorMsg, ex);
+ this.topicName = topicName;
+ this.msgId = msgId;
+ this.msg = msg;
+ }
+
+ public UebException(String msg, Throwable ex) {
+ super(msg, ex);
+ }
+
+ public UebException(Throwable ex) {
+ super(ex);
+ }
+
+ public String getUebMsg() {
+ return this.msg;
+ }
+
+ public String getTopicName() {
+ return this.topicName;
+ }
+
+ public String getMsgId() {
+ return this.msgId;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.ueb;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+
+/**
+ * Manages UEB interactions and provides methods for publishing requests,
+ * replies and others.
+ */
+public class UebManager {
+
+ private final Log logger = LogFactory.getLog(getClass());
+
+ private WaitingRequestersQueueList waitingRequestersQueueList;
+ private PublisherList publisherList = new PublisherList();
+ private static UebManager uebManager = null;
+
+ private final String inTopicName;
+ private final String consumerGroupName;
+ private final String outTopicName;
+ private final String appUebKey;
+ private final String appUebSecret;
+
+ private Publisher appPublisher;
+ private Thread listenerThread;
+ private boolean bThisIsEcompPortalServer = false;
+
+ /**
+ * Constructor initializes fields and validates values obtained from
+ * properties.
+ *
+ * The picture below is a simplified view of the relationships among ECOMP
+ * Portal and applications communicating via UEB:
+ *
+ * <PRE>
+ * ECOMP out to many.
+ * App out to only ECOMP.
+ *
+ * |----------------|<---------------------------------------------
+ * | | | | |
+ * | |---------------------------> App 1 ------ | |
+ * | ECOMP Portal |---------------------------> App 2 --------- |
+ * | | ... |
+ * | |---------------------------> App n -----------
+ * |----------------|
+ * </PRE>
+ *
+ * @throws IOException
+ */
+ protected UebManager() throws UebException {
+ waitingRequestersQueueList = null;
+ listenerThread = null;
+ outTopicName = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME);
+ inTopicName = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME);
+ appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
+ appUebSecret = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET);
+ String consGrp = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_CONSUMER_GROUP_NAME);
+
+ if (outTopicName == null || outTopicName.length() == 0)
+ throw new UebException("Failed to get property " + PortalApiConstants.ECOMP_PORTAL_INBOX_NAME, null, null,
+ null);
+ if (inTopicName == null || inTopicName.length() == 0)
+ throw new UebException("Failed to get property " + PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME, null,
+ null, null);
+ if (consGrp == null || consGrp.length() == 0)
+ throw new UebException("Failed to get property " + PortalApiConstants.UEB_APP_CONSUMER_GROUP_NAME, null,
+ null, null);
+ if (appUebKey == null || appUebKey.length() == 0)
+ throw new UebException("Failed to get property " + PortalApiConstants.UEB_APP_KEY, null, null, null);
+ if (appUebSecret == null || appUebSecret.length() == 0)
+ throw new UebException("Failed to get property " + PortalApiConstants.UEB_APP_SECRET, null, null, null);
+ List<String> uebUrlList = Helper.uebUrlList();
+ if (uebUrlList == null || uebUrlList.size() == 0)
+ throw new UebException("Failed to get property" + PortalApiConstants.UEB_URL_LIST, null, null, null);
+ // A bit of magic: if consumer group is a magic token, generate one.
+ consumerGroupName = (PortalApiConstants.UEB_APP_CONSUMER_GROUP_NAME_GENERATOR.equals(consGrp)
+ ? UUID.randomUUID().toString() : consGrp);
+ }
+
+ /**
+ * Gets the static instance, creating it if necessary.
+ *
+ * @return Instance of UebManager
+ * @throws IOException
+ */
+ public static synchronized UebManager getInstance() throws UebException {
+ if (uebManager == null) {
+ uebManager = new UebManager();
+ }
+ return uebManager;
+ }
+
+ /**
+ * Answers whether the getInstance() method has previously been called.
+ *
+ * @return True if a static instance is available, else false.
+ */
+ public static boolean isInstanceAvailable() {
+ return uebManager != null;
+ }
+
+ /**
+ * Creates a list of waiting requesters, creates and a consumer using cached
+ * information, and starts a new thread to run the consumer that listens for
+ * messages published to the inbound topic configured in the constructor.
+ *
+ * @param inboxQueue
+ * Queue supplied to the consumer. If not null, the consumer will
+ * enqueue every message it receives.
+ */
+ public void initListener(ConcurrentLinkedQueue<UebMsg> inboxQueue) throws UebException {
+ waitingRequestersQueueList = new WaitingRequestersQueueList();
+ Consumer runnable = new Consumer(appUebKey, appUebSecret, inTopicName, consumerGroupName, inboxQueue,
+ waitingRequestersQueueList);
+ this.listenerThread = new Thread(runnable, "UEBConsumerThread");
+ this.listenerThread.start();
+ Helper.sleep(400); // UEB functions more reliably when we give this some
+ // time
+
+ logger.info("UEBManager instance starting... " + inTopicName + " listener thread "
+ + this.listenerThread.getName() + " state = " + this.listenerThread.getState());
+
+ /*
+ * ECOMP Portal manages a dynamic list of outbound topics and so the
+ * outTopicName is initialized in this logic with the same value as the
+ * inbound topic. The real outbound topics name will be added to the
+ * publisher list for ECOMP Portal. For an SDK/App instance only one
+ * publisher is needed, appPublisher.
+ */
+ if (inTopicName.equalsIgnoreCase(outTopicName)) {
+ this.bThisIsEcompPortalServer = true;
+ } else {
+ appPublisher = new Publisher(appUebKey, appUebSecret, outTopicName);
+ Helper.sleep(400);
+ }
+ }
+
+ /**
+ * Creates and adds a publisher to the list for the specified topic. This
+ * should only be called by the ECOMP Portal App, other Apps have just one
+ * publisher and use appPublisher
+ *
+ * @param topicName
+ */
+ public void addPublisher(String topicName) {
+ logger.info("UEBManager adding publisher for " + topicName);
+ Publisher outBoxToAppPublisher = new Publisher(appUebKey, appUebSecret, topicName);
+ publisherList.addPublisherToMap(topicName, outBoxToAppPublisher);
+ }
+
+ /**
+ * Removes a publisher from the list for the specified topic.
+ *
+ * This should only be called by the ECOMP Portal App, other Apps have just
+ * one publisher and use appPublisher
+ *
+ * @param topicName
+ */
+ public void removePublisher(String topicName) {
+ logger.info("UEBManager removing publisher for " + topicName);
+ publisherList.removePublisherFromMap(topicName);
+ }
+
+ /**
+ * Adds the default ECOMP message ID to the message and sends the message to
+ * the topic.
+ *
+ * @param msg
+ * @throws UebException
+ */
+ public void publish(UebMsg msg) throws UebException {
+ msg.putMsgId(PortalApiConstants.ECOMP_DEFAULT_MSG_ID);
+ appPublisher.send(msg);
+ }
+
+ /**
+ * Sends the message using the default publisher.
+ *
+ * @param msg
+ * @throws UebException
+ */
+ public void publishReply(UebMsg msg) throws UebException {
+ // Caller populates msgId with the echoed value from the request
+ appPublisher.send(msg);
+ }
+
+ /**
+ * Sends the message using the appropriate publisher for the specified
+ * topic.
+ *
+ * @param msg
+ * @param topicName
+ * @throws UebException
+ */
+ public void publishEP(UebMsg msg, String topicName) throws UebException {
+ Publisher publisher = publisherList.getPublisher(topicName);
+ if (publisher != null) {
+ msg.putMsgId(PortalApiConstants.ECOMP_DEFAULT_MSG_ID);
+ publisher.send(msg);
+ }
+ }
+
+ /**
+ * Publishes a reply using the appropriate publisher for the specified
+ * topic.
+ *
+ * @param msg
+ * @param topicName
+ * @throws UebException
+ */
+ public void publishReplyEP(UebMsg msg, String topicName) throws UebException {
+ // Caller populates msgId with the echoed value from the request
+ Publisher publisher = publisherList.getPublisher(topicName);
+ if (publisher != null) {
+ publisher.send(msg);
+ }
+ }
+
+ /**
+ * Sends the specified message using the specified publisher, and waits for
+ * a reply. Retransmits if no reply is received in 5 seconds; gives up after
+ * 3 retries.
+ *
+ * @param msg
+ * @param publisher
+ * @return Message from a remote publisher, or null if timeout happens.
+ * @throws UebException
+ */
+ public UebMsg requestReplyUsingPublisher(UebMsg msg, Publisher publisher) throws UebException {
+ UebMsg reply = null;
+ if (waitingRequestersQueueList == null) {
+ logger.error("requestReplyUsingPublisher called but listener thread not initialized");
+ } else {
+ // Storing a non-default message ID identifies this as a synchronous
+ // request
+ msg.putMsgId(UUID.randomUUID().toString());
+
+ /*
+ * Create a queue for this request, the consumer thread will insert
+ * the reply on this queue
+ */
+ LinkedBlockingQueue<UebMsg> replyQueue = new LinkedBlockingQueue<UebMsg>();
+ waitingRequestersQueueList.addQueueToMap(msg.getMsgId(), replyQueue);
+
+ /*
+ * Send the request
+ */
+ publisher.send(msg);
+
+ /*
+ * Wait for reply up to 3 * 5 = 15 seconds
+ */
+ int reTransmits = 0;
+ int maxRetransmits = 3;
+ int retransmitTimeMs = 5000;
+ long sendTimeStamp = System.currentTimeMillis();
+ while (reTransmits < maxRetransmits) {
+ if ((reply = replyQueue.poll()) != null)
+ break;
+
+ long now = System.currentTimeMillis();
+ if (now - sendTimeStamp > retransmitTimeMs) {
+ logger.debug("Retransmitting send... msg = " + msg.getPayload() + msg.getMsgId());
+ publisher.send(msg);
+ sendTimeStamp = System.currentTimeMillis();
+ reTransmits++;
+ }
+ }
+ waitingRequestersQueueList.removeQueueFromMap(msg.getMsgId());
+ if (reTransmits == maxRetransmits)
+ throw new UebException(PortalApiConstants.ECOMP_UEB_TIMEOUT_ERROR, inTopicName, null, msg.toString());
+
+ }
+ return reply;
+ }
+
+ /**
+ * Sends the specified message using the default publisher and waits for a
+ * reply.
+ *
+ * @param msg
+ * @return Message from a remote publisher, or null if timeout happens.
+ * @throws UebException
+ */
+ public UebMsg requestReply(UebMsg msg) throws UebException {
+ return requestReplyUsingPublisher(msg, appPublisher);
+ }
+
+ /**
+ * Sends the specified message using the publisher appropriate for the
+ * specified topic name, and waits for a reply.
+ *
+ * @param msg
+ * @param topicName
+ * @return Message from a remote publisher, or null if timeout happens.
+ * @throws UebException
+ */
+ public UebMsg requestReplyEP(UebMsg msg, String topicName) throws UebException {
+ UebMsg returnMsg = null;
+ Publisher publisher = publisherList.getPublisher(topicName);
+ if (publisher != null) {
+ returnMsg = requestReplyUsingPublisher(msg, publisher);
+ }
+ return returnMsg;
+ }
+
+ /**
+ * Publishes the payload as a UEB widget-notification message on the default
+ * publisher. Intended for use by Apps inter widget communication, not EP
+ * itself.
+ *
+ * @param payload
+ * @param userId
+ */
+ public void postWidgetNotification(String payload, String userId) throws UebException {
+ UebMsg msg = new UebMsg();
+ msg.putPayload(payload);
+ msg.putUserId(userId);
+ msg.putMsgType(UebMsgTypes.UEB_MSG_TYPE_WIDGET_NOTIFICATION);
+ this.publish(msg);
+ }
+
+ /**
+ * Interrupts the long-running thread that runs the consumer.
+ */
+ public void shutdown() {
+ if (this.listenerThread != null) {
+ this.listenerThread.interrupt();
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.ueb;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class UebMsg {
+
+ private final Log logger = LogFactory.getLog(getClass());
+
+ private String version;
+ private String msgId;
+ private long timeStamp;
+ private String payload;
+ private String msgType;
+ private String userId;
+ private String sourceTopicName;
+ private String sourceIP;
+ private String sourceHostName;
+
+ /**
+ * Creates a new object and populates the fields source IP, source topic,
+ * time stamp, version, and message id.
+ */
+ public UebMsg() {
+ InetAddress ip;
+ try {
+ ip = InetAddress.getLocalHost();
+ // Do not attempt to get name, why wait on DNS every time?
+ // sourceHostName = ip.getHostName();
+ sourceIP = ip.getHostAddress();
+ } catch (UnknownHostException e) {
+ sourceHostName = "unknown";
+ sourceIP = "unknown";
+ }
+
+ this.timeStamp = System.currentTimeMillis();
+ this.version = "1.0";
+ this.msgId = PortalApiConstants.ECOMP_DEFAULT_MSG_ID;
+ this.payload = "empty payload content";
+ this.sourceTopicName = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME);
+ if (this.sourceTopicName == null)
+ logger.error("Failed to get property " + PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME);
+ }
+
+ public void putMsgId(String msgId) {
+ this.msgId = msgId;
+ }
+
+ public String getMsgId() {
+ return msgId;
+ }
+
+ public void putPayload(String payload) {
+ this.payload = payload;
+ }
+
+ public String getPayload() {
+ return payload;
+ }
+
+ public void putMsgType(String msgType) {
+ this.msgType = msgType;
+ }
+
+ public String getMsgType() {
+ return this.msgType;
+ }
+
+ public void putUserId(String userId) {
+ this.userId = userId;
+ }
+
+ public String getUserId() {
+ return this.userId;
+ }
+
+ public void putSourceTopicName(String topic) {
+ this.sourceTopicName = topic;
+ }
+
+ public String getSourceTopicName() {
+ return this.sourceTopicName;
+ }
+
+ @Override
+ public String toString() {
+ return "UebMsg [version=" + version + ", msgId=" + msgId + ", timeStamp=" + timeStamp + ", msgType=" + msgType
+ + ", userId=" + userId + ", sourceTopicName=" + sourceTopicName + ", sourceIP=" + sourceIP
+ + ", sourceHostName=" + sourceHostName + "]" + System.lineSeparator() + "payload=" + payload;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.ueb;
+
+/**
+ * Publishes constants used in the UEB package.
+ */
+public interface UebMsgTypes {
+ public static final String UEB_MSG_TYPE_GET_FUNC_MENU = "uebMsgTypeGetFuncMenu";
+ public static final String UEB_MSG_TYPE_WIDGET_NOTIFICATION = "uebMsgTypeWidgetNotification";
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.ueb;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.LinkedBlockingQueue;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * A thin wrapper around ConcurrentHashMap that stores a queue for each
+ * Requester that is waiting for a Reply. When a reply is received that has a
+ * matching msgId, that requesters queue is populated with the reply message.
+ *
+ * Primarily for the UebManager to track requests while it waits for responses.
+ */
+public class WaitingRequestersQueueList {
+ private final Log logger = LogFactory.getLog(getClass());
+
+ private final Map<String, LinkedBlockingQueue<UebMsg>> map;
+
+ public WaitingRequestersQueueList() {
+ map = new ConcurrentHashMap<>();
+ }
+
+ public void addQueueToMap(String msgId, LinkedBlockingQueue<UebMsg> queue) {
+ this.map.put(msgId, queue);
+ }
+
+ public void addMsg(String msgId, UebMsg message) {
+ LinkedBlockingQueue<UebMsg> queue = this.map.get(msgId);
+ if (queue != null) {
+ queue.add(message);
+ } else {
+ logger.warn("Did not find entry in WaitingRequestersQueueList for msgId " + msgId);
+ }
+ }
+
+ public void removeQueueFromMap(String msgId) {
+ this.map.remove(msgId);
+ }
+
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.append("Map contains " + this.map.size() + " Publishers.");
+ for (Map.Entry<String, LinkedBlockingQueue<UebMsg>> entry : this.map.entrySet()) {
+ String key = entry.getKey().toString();
+ LinkedBlockingQueue<UebMsg> queue = entry.getValue();
+ sb.append("Entry msgId, " + key + " queue " + queue);
+ }
+ return sb.toString();
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.restful.client;
+
+/**
+ * Holds the status code and body that result from accessing an HTTP URL.
+ */
+public class HttpStatusAndResponse {
+
+ private int statusCode;
+ private String response;
+
+ public HttpStatusAndResponse(int status, String resp) {
+ this.statusCode = status;
+ this.response = resp;
+ }
+
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ public String getResponse() {
+ return response;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.restful.client;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.http.Consts;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.onap.portalsdk.core.domain.App;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+import org.onap.portalsdk.core.service.AppService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * Provides a basic client to access a REST endpoint at the Portal via get or
+ * post. Usage caveats:
+ * <OL>
+ * <LI>Must be auto-wired by Spring, because this in turn auto-wires a
+ * data-access service to read application credentials from the FN_APP table.
+ * <LI>If HTTP access is used and the server uses a self-signed certificate, the
+ * local trust store must be extended appropriately. The HTTP client throws
+ * exceptions if the JVM cannot validate the server certificate.
+ * </OL>
+ */
+@Component
+public class PortalRestClientBase {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalRestClientBase.class);
+
+ @Autowired
+ AppService appService;
+
+ /**
+ * Constructs and sends a GET request for the URI, with REST application
+ * credentials in the header as the Portal expects.
+ *
+ * @param uri
+ * URI of the service
+ * @return Result of the get; null if an error happens
+ * @throws Exception
+ */
+ public HttpStatusAndResponse getRestWithCredentials(final URI uri) throws Exception {
+
+ String uebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
+ App app = appService.getDefaultApp();
+ if (uebKey == null || app == null || app.getUsername() == null || app.getAppPassword() == null)
+ throw new IllegalArgumentException("Missing one or more required properties and/or database entries");
+ String decryptedPassword = CipherUtil.decrypt(app.getAppPassword());
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ HttpGet httpGet = new HttpGet(uri);
+ httpGet.setHeader("uebkey", uebKey);
+ httpGet.setHeader("username", app.getUsername());
+ httpGet.setHeader("password", decryptedPassword);
+
+ String responseJson = null;
+ CloseableHttpResponse response = null;
+ try {
+ logger.info(EELFLoggerDelegate.debugLogger, "GET from " + uri);
+ response = httpClient.execute(httpGet);
+ logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine());
+ if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
+ logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine().toString());
+ HttpEntity entity = response.getEntity();
+ if (entity == null) {
+ logger.info(EELFLoggerDelegate.debugLogger, "Entity is null!");
+ } else {
+ // entity content length is never set.
+ // this naively tries to read everything.
+ responseJson = EntityUtils.toString(entity);
+ logger.info(EELFLoggerDelegate.debugLogger, responseJson);
+ EntityUtils.consume(entity);
+ }
+ } finally {
+ if (response != null)
+ response.close();
+ if (httpClient != null)
+ httpClient.close();
+ }
+ if (response == null)
+ return null;
+ return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson);
+ }
+
+ /**
+ * Constructs and sends a POST request using the specified body, with REST
+ * application credentials in the header as the Portal expects.
+ *
+ * @param uri
+ * REST endpoint
+ * @param json
+ * Content to post
+ * @return Result of the post; null if an error happens
+ * @throws Exception
+ */
+ public HttpStatusAndResponse postRestWithCredentials(final URI uri, final String json) throws Exception {
+
+ String uebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
+ App app = appService.getDefaultApp();
+ if (uebKey == null || app == null || app.getUsername() == null || app.getAppPassword() == null)
+ throw new Exception("Missing one or more required properties and/or database entries");
+
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ HttpPost httpPost = new HttpPost(uri);
+ httpPost.setHeader("uebkey", uebKey);
+ httpPost.setHeader("username", app.getUsername());
+ httpPost.setHeader("password", app.getAppPassword());
+
+ StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));
+ httpPost.setEntity(postEntity);
+
+ String responseJson = null;
+ CloseableHttpResponse response = null;
+ try {
+ logger.info(EELFLoggerDelegate.debugLogger, "POST to " + uri);
+ response = httpClient.execute(httpPost);
+ logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine());
+ if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
+ throw new Exception("Status is " + response.getStatusLine().toString());
+
+ HttpEntity entity = response.getEntity();
+ if (entity == null) {
+ logger.info(EELFLoggerDelegate.debugLogger, "Entity is null!");
+ } else {
+ // entity content length is never set.
+ // this naively tries to read everything.
+ responseJson = EntityUtils.toString(entity);
+ logger.info(EELFLoggerDelegate.debugLogger, responseJson);
+ EntityUtils.consume(entity);
+ }
+ } finally {
+ if (response != null)
+ response.close();
+ if (httpClient != null)
+ httpClient.close();
+ }
+ return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.restful.client;
+
+import java.net.URI;
+import java.util.HashMap;
+import java.util.List;
+
+import org.apache.http.client.utils.URIBuilder;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+import org.onap.portalsdk.core.restful.domain.SharedContext;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * Provides convenience methods to use the shared-context service at Portal.
+ * This hides all JSON; instead it accepts and returns Java objects. Usage
+ * caveats (repeated from superclass):
+ * <OL>
+ * <LI>Must be auto-wired by Spring, because this in turn auto-wires a data
+ * access service to read application credentials from the FN_APP table.
+ * <LI>If HTTP access is used and the server uses a self-signed certificate, the
+ * local trust store must be extended appropriately. The HTTP client throws
+ * exceptions if the JVM cannot validate the server certificate.
+ * </OL>
+ */
+@Component
+public class SharedContextRestClient extends PortalRestClientBase {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestClient.class);
+
+ /**
+ * Reusable JSON (de)serializer
+ */
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ /**
+ * Builds the URl for the shared context service using the portal.properties
+ * value for the AUXAPI endpoint.
+ *
+ * @throws Exception
+ * if the ECOMP_REST_URL property is not found
+ */
+ private String getSharedContextUrl() throws Exception {
+ String restUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
+ if (restUrl == null || restUrl.length() == 0)
+ throw new Exception("getSharedContextUrl: no property " + PortalApiConstants.ECOMP_REST_URL);
+ String contextUrl = restUrl + (restUrl.endsWith("/") ? "" : "/") + "context/";
+ return contextUrl;
+ }
+
+ /**
+ * Gets the shared-context value for the specified context ID and key.
+ *
+ * @param contextId
+ * An Ecomp Portal session ID
+ * @param key
+ * Key for the shared-context entry; e.g., "lastName"
+ * @return SharedContext object; null if not found.
+ * @throws Exception
+ */
+ public SharedContext getContextValue(String contextId, String key) throws Exception {
+ HttpStatusAndResponse hsr = getContext("get", contextId, key);
+ logger.info(EELFLoggerDelegate.debugLogger, "getSharedContext: resp is " + hsr);
+ if (hsr == null) {
+ logger.error(EELFLoggerDelegate.applicationLogger, "getContextValue: unexpected null response");
+ return null;
+ }
+ SharedContext jsonObj = null;
+ try {
+ jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
+ } catch (JsonMappingException ex) {
+ logger.error(EELFLoggerDelegate.applicationLogger,
+ "getContextValue: failed to map response onto object" + ex.getMessage());
+ } catch (JsonParseException ex) {
+ logger.info(EELFLoggerDelegate.applicationLogger,
+ "getContextValue: failed to parse response" + ex.getMessage());
+ }
+ if (jsonObj != null && jsonObj.getResponse() != null)
+ return null;
+ return jsonObj;
+ }
+
+ /**
+ * Gets user information for the specified context ID.
+ *
+ * @param contextId
+ * An Ecomp Portal session ID
+ * @return List of SharedContext objects corresponding to the following
+ * keys: USER_FIRST_NAME, USER_LAST_NAME, USER_EMAIL and
+ * USER_ORGUSERID; empty if none were found; null if an error
+ * happens.
+ * @throws Exception
+ */
+ public List<SharedContext> getUserContext(String contextId) throws Exception {
+ HttpStatusAndResponse hsr = getContext("get_user", contextId, null);
+ logger.info(EELFLoggerDelegate.debugLogger, "getUserContext: resp is " + hsr);
+ if (hsr == null) {
+ logger.error(EELFLoggerDelegate.applicationLogger, "getUserContext: unexpected null response");
+ return null;
+ }
+ List<SharedContext> jsonList = null;
+ try {
+ TypeReference<List<SharedContext>> typeRef = new TypeReference<List<SharedContext>>() {
+ };
+ jsonList = mapper.readValue(hsr.getResponse(), typeRef);
+ } catch (JsonMappingException ex) {
+ logger.error(EELFLoggerDelegate.applicationLogger,
+ "getUserContext: failed to map response onto object" + ex.getMessage());
+ } catch (JsonParseException ex) {
+ logger.error(EELFLoggerDelegate.applicationLogger,
+ "getUserContext: failed to parse response" + ex.getMessage());
+ }
+ return jsonList;
+ }
+
+ /**
+ * Checks whether a shared-context entry exists for the specified context ID
+ * and key.
+ *
+ * @param contextId
+ * An Ecomp Portal session ID
+ * @param key
+ * Key for the shared-context entry; e.g., "lastName"
+ * @return True if the object exists, false otherwise; null on error.
+ * @throws Exception
+ */
+ public Boolean checkSharedContext(String contextId, String key) throws Exception {
+ HttpStatusAndResponse hsr = getContext("check", contextId, key);
+ logger.info(EELFLoggerDelegate.debugLogger, "checkSharedContext: resp is " + hsr);
+ if (hsr == null) {
+ logger.error(EELFLoggerDelegate.applicationLogger, "checkSharedContext: unexpected null response");
+ return null;
+ }
+ String response = null;
+ try {
+ SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
+ response = jsonObj.getResponse();
+ } catch (JsonMappingException ex) {
+ logger.error(EELFLoggerDelegate.applicationLogger,
+ "checkSharedContext: failed to map response onto object" + ex.getMessage());
+ } catch (JsonParseException ex) {
+ logger.error(EELFLoggerDelegate.applicationLogger,
+ "checkSharedContext: failed to parse response" + ex.getMessage());
+ }
+ if (response == null)
+ return null;
+ return ("exists".equals(response));
+ }
+
+ /**
+ * Removes a shared-context entry with the specified context ID and key.
+ *
+ * @param contextId
+ * An Ecomp Portal session ID
+ * @param key
+ * Key for the shared-context entry; e.g., "lastName"
+ * @return True if the entry was removed, false otherwise; null on error.
+ * @throws Exception
+ */
+ public Boolean removeSharedContext(String contextId, String key) throws Exception {
+ HttpStatusAndResponse hsr = getContext("remove", contextId, key);
+ logger.info(EELFLoggerDelegate.debugLogger, "removeSharedContext: resp is " + hsr);
+ if (hsr == null) {
+ logger.error(EELFLoggerDelegate.applicationLogger, "removeSharedContext: unexpected null response");
+ return null;
+ }
+ SharedContext jsonObj = null;
+ try {
+ jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
+ } catch (JsonMappingException ex) {
+ logger.error(EELFLoggerDelegate.applicationLogger,
+ "removeSharedContext: failed to map response onto object" + ex.getMessage());
+ } catch (JsonParseException ex) {
+ logger.error(EELFLoggerDelegate.applicationLogger,
+ "removeSharedContext: failed to parse response" + ex.getMessage());
+ }
+ if (jsonObj == null)
+ return null;
+ String response = jsonObj.getResponse();
+ return ("removed".equals(response));
+ }
+
+ /**
+ * Clears the shared context for the specified context ID; i.e., removes all
+ * key-value pairs.
+ *
+ * @param contextId
+ * An Ecomp Portal session ID
+ * @return Number of key-value pairs removed; -1 if not found or any
+ * problems occur.
+ * @throws Exception
+ */
+ public int clearSharedContext(String contextId) throws Exception {
+ HttpStatusAndResponse hsr = getContext("remove", contextId, null);
+ logger.info(EELFLoggerDelegate.debugLogger, "clearSharedContext: resp is " + hsr);
+ if (hsr == null) {
+ logger.error(EELFLoggerDelegate.applicationLogger, "clearSharedContext: unexpected null response");
+ return -1;
+ }
+ SharedContext jsonObj = null;
+ try {
+ jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
+ } catch (JsonMappingException ex) {
+ logger.error(EELFLoggerDelegate.applicationLogger,
+ "clearSharedContext: failed to map response onto object" + ex.getMessage());
+ } catch (JsonParseException ex) {
+ logger.error(EELFLoggerDelegate.applicationLogger,
+ "clearSharedContext: failed to parse response" + ex.getMessage());
+ }
+ if (jsonObj == null)
+ return -1;
+ String response = jsonObj.getResponse();
+ if (response == null)
+ return -1;
+ return Integer.parseInt(response);
+ }
+
+ /**
+ * Creates a shared-context entry.
+ *
+ * @param contextId
+ * An Ecomp Portal session ID
+ * @param key
+ * Key for the shared-context entry; e.g., "lastName"
+ * @param value
+ * Value for the entry
+ * @throws Exception
+ * @return True if the object previously existed, false otherwise; null if
+ * any problem happened.
+ */
+ public Boolean setSharedContext(String contextId, String key, String value) throws Exception {
+ String body = buildContext(contextId, key, value);
+ HttpStatusAndResponse hsr = postContext("set", body);
+ logger.info(EELFLoggerDelegate.debugLogger, "setSharedContext: resp is " + hsr);
+ if (hsr == null) {
+ logger.error(EELFLoggerDelegate.applicationLogger, "setSharedContext: unexpected null response");
+ return null;
+ }
+ SharedContext jsonObj = null;
+ try {
+ jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
+ } catch (JsonMappingException ex) {
+ logger.error(EELFLoggerDelegate.applicationLogger,
+ "setSharedContext: failed to map response onto object" + ex.getMessage());
+ } catch (JsonParseException ex) {
+ logger.error(EELFLoggerDelegate.applicationLogger,
+ "setSharedContext: failed to parse response" + ex.getMessage());
+ }
+ if (jsonObj == null)
+ return null;
+ String response = jsonObj.getResponse();
+ return ("replaced".equals(response));
+ }
+
+ /**
+ * Builds the full URL with the specified parameters, then calls the method
+ * that adds credentials and GETs.
+ *
+ * @param requestPath
+ * @param contextId
+ * @param contextKey
+ * @return HttpStatusAndResponse object; may be null.
+ * @throws Exception
+ */
+ private HttpStatusAndResponse getContext(String requestPath, String contextId, String contextKey) throws Exception {
+ URIBuilder uriBuilder = new URIBuilder(getSharedContextUrl() + requestPath);
+ uriBuilder.addParameter("context_id", contextId);
+ if (contextKey != null)
+ uriBuilder.addParameter("ckey", contextKey);
+ final URI uri = uriBuilder.build();
+ return getRestWithCredentials(uri);
+ }
+
+ /**
+ * Builds the full URL, then calls the method that adds credentials and
+ * POSTs.
+ *
+ * @param requestPath
+ * @param contextId
+ * @param contextKey
+ * @return HttpStatusAndResponse object; may be null.
+ * @throws Exception
+ */
+ private HttpStatusAndResponse postContext(String requestPath, String json) throws Exception {
+ URIBuilder uriBuilder = new URIBuilder(getSharedContextUrl() + requestPath);
+ URI uri = uriBuilder.build();
+ return postRestWithCredentials(uri, json);
+ }
+
+ /**
+ * Builds a JSON block with a single shared-context entry.
+ *
+ * @param cxid
+ * Context ID
+ * @param ckey
+ * Context Key
+ * @param cvalue
+ * Context value
+ * @return JSON block
+ */
+ private String buildContext(String cxid, String ckey, String cvalue) throws JsonProcessingException {
+ ObjectMapper mapper = new ObjectMapper();
+ HashMap<String, String> stringMap = new HashMap<String, String>();
+ stringMap.put("context_id", cxid);
+ stringMap.put("ckey", ckey);
+ stringMap.put("cvalue", cvalue);
+ String json = mapper.writeValueAsString(stringMap);
+ return json;
+ }
+
+ // Simple test scaffold
+ public static void main(String[] args) throws Exception {
+ // ObjectMapper mapper = new ObjectMapper();
+ // SharedContext cxt = mapper.readValue("{ \"response\":\"foo\" }",
+ // SharedContext.class);
+ SharedContextRestClient client = new SharedContextRestClient();
+ SharedContext get = client.getContextValue("abc", "123");
+ System.out.println("Get yields " + get.toString());
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.scheduler;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.quartz.CronTrigger;
+import org.quartz.Trigger;
+import org.springframework.context.annotation.DependsOn;
+import org.springframework.stereotype.Component;
+
+@Component
+@DependsOn({"systemProperties"})
+public class CoreRegister {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CoreRegister.class);
+
+ Trigger trigger[] = new Trigger[1];
+
+ protected List<Trigger> scheduleTriggers = new ArrayList<Trigger>();
+
+ public void registerTriggers() {
+ // we can use this method to add any schedules to the core
+
+ /*
+ try {
+ if(SystemProperties.getProperty(SystemProperties.SESSIONTIMEOUT_FEED_CRON) != null)
+ getScheduleTriggers().add(sessionMgtRegistry.getTrigger());
+
+ } catch(IllegalStateException ies) {
+ logger.info("Session Timout Cron not available");
+ }
+ */
+
+ }
+
+ protected void addTrigger(final String cron, final CronTrigger cronRegistryTrigger) {
+ // if the property value is not available; the cron will not be added and can be ignored. its safe to ignore the exceptions
+
+ try {
+
+ if(SystemProperties.getProperty(cron) != null) {
+ getScheduleTriggers().add(cronRegistryTrigger);
+ }
+
+ } catch(IllegalStateException ies) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Log Cron not available", AlarmSeverityEnum.MAJOR);
+ }
+ }
+
+
+
+
+ public List<Trigger> getScheduleTriggers() {
+ return scheduleTriggers;
+ }
+
+
+
+ public void setScheduleTriggers(List<Trigger> scheduleTriggers) {
+ this.scheduleTriggers = scheduleTriggers;
+ }
+
+
+
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.scheduler;
+
+import java.text.ParseException;
+import java.util.Map;
+
+import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.quartz.CronTrigger;
+import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
+import org.springframework.scheduling.quartz.JobDetailFactoryBean;
+import org.springframework.scheduling.quartz.QuartzJobBean;
+
+import com.mchange.v2.c3p0.ComboPooledDataSource;
+
+public abstract class CronRegistry {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CronRegistry.class);
+
+ protected JobDetailFactoryBean jobDetailFactory;
+ protected CronTriggerFactoryBean cronTriggerFactory;
+
+ private ComboPooledDataSource dataSource;
+
+ public CronRegistry() {
+ try {
+ jobDetailFactoryBean();
+ cronTriggerFactoryBean();
+ }
+ catch(Exception e) {
+ logger.error(EELFLoggerDelegate.debugLogger, e.getMessage());
+ }
+ }
+
+ //@Autowired
+ public CronRegistry(ComboPooledDataSource dataSource) {
+ try {
+ this.dataSource = dataSource;
+ jobDetailFactoryBean();
+ cronTriggerFactoryBean();
+ }
+ catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AlarmSeverityEnum.MAJOR);
+ }
+ }
+
+ //@Autowired
+ public CronRegistry(Object... initializeObjects) {
+ try {
+ initializeObjects(initializeObjects);
+ jobDetailFactoryBean();
+ cronTriggerFactoryBean();
+ }
+ catch(Exception e) {
+ logger.info(EELFLoggerDelegate.errorLogger, e.getMessage());
+ }
+ }
+
+ protected void initializeObjects(Object... initializeObjects) {
+ }
+
+ public abstract JobDetailFactoryBean jobDetailFactoryBean() throws ParseException;
+
+ protected JobDetailFactoryBean jobDetailFactoryBean(String groupName, String jobName,
+ Class<? extends QuartzJobBean> jobClass, Map<String, Object> map) {
+
+ jobDetailFactory = new JobDetailFactoryBean();
+ jobDetailFactory.setJobClass(jobClass);
+ jobDetailFactory.setJobDataAsMap(map);
+ jobDetailFactory.setGroup(groupName);
+ jobDetailFactory.setName(jobName);
+ jobDetailFactory.afterPropertiesSet();
+
+ return jobDetailFactory;
+ }
+
+ public abstract CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException;
+
+ protected CronTriggerFactoryBean cronTriggerFactoryBean(String groupName, String triggerName, String cronExpression) throws ParseException {
+ cronTriggerFactory = new CronTriggerFactoryBean();
+ cronTriggerFactory.setJobDetail(jobDetailFactory.getObject());
+ cronTriggerFactory.setStartDelay(3000);
+ cronTriggerFactory.setName(triggerName);
+ cronTriggerFactory.setGroup(groupName);
+ logger.info(EELFLoggerDelegate.applicationLogger, triggerName + " Scheduled: " + cronExpression);
+ cronTriggerFactory.setCronExpression( cronExpression); //"0 * * * * ? *"
+ cronTriggerFactory.afterPropertiesSet();
+ return cronTriggerFactory;
+ }
+
+ public CronTrigger getTrigger() {
+ return cronTriggerFactory.getObject();
+ }
+
+
+ public void setDataSource(ComboPooledDataSource dataSource) {
+ this.dataSource = dataSource;
+ }
+
+
+ public ComboPooledDataSource getDataSource() {
+ return dataSource;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.scheduler;
+
+import org.quartz.Trigger;
+
+public interface Registerable {
+
+ public void registerTriggers();
+
+ public Trigger[] getTriggers();
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.portalsdk.core.service;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Conditional;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class AccessConfiguration {
+
+ /**
+ *
+ * @return RoleServiceImpl bean if LocalAccessCondition is true
+ */
+ @Bean
+ @Conditional(LocalAccessCondition.class)
+ public RoleService roleServiceImpl() {
+ return new RoleServiceImpl();
+ }
+
+ /**
+ *
+ * @return RoleServiceCentralizedAccess bean if CentralAccessCondition is true
+ */
+ @Bean
+ @Conditional(CentralAccessCondition.class)
+ public RoleService roleServiceCentralizedAccess() {
+ return new RoleServiceCentralizedAccess();
+ }
+
+ /**
+ *
+ * @return LoginServiceImpl bean if LocalAccessCondition is true
+ */
+ @Bean
+ @Conditional(LocalAccessCondition.class)
+ public LoginService loginServiceImpl() {
+ return new LoginServiceImpl();
+ }
+
+ /**
+ *
+ * @return LoginServiceCentralizedImpl bean if CentralAccessCondition is true
+ */
+ @Bean
+ @Conditional(CentralAccessCondition.class)
+ public LoginService loginServiceCEntralizedImpl() {
+ return new LoginServiceCentralizedImpl();
+ }
+
+ /**
+ *
+ * @return UserProfileServiceImpl bean if LocalAccessCondition is true
+ */
+ @Bean
+ @Conditional(LocalAccessCondition.class)
+ public UserService userServiceImpl() {
+ return new UserServiceImpl();
+ }
+
+ /**
+ *
+ * @return returns UserProfileServiceCentalizedImpl bean if
+ * CentralAccessCondition is true
+ */
+ @Bean
+ @Conditional(CentralAccessCondition.class)
+ public UserService userServiceCentalizedImpl() {
+ return new UserServiceCentalizedImpl();
+ }
+
+ /**
+ *
+ * @return returns ProfileServiceImpl bean if LocalAccessCondition is true
+ */
+ @Bean
+ @Conditional(LocalAccessCondition.class)
+ public ProfileService profileServiceImpl() {
+ return new ProfileServiceImpl();
+ }
+
+ /**
+ *
+ * @return returns ProfileServiceCentralizedImpl bean if CentralAccessCondition
+ * is true
+ */
+
+ @Bean
+ @Conditional(CentralAccessCondition.class)
+ public ProfileService profileServiceCentralizedImpl() {
+ return new ProfileServiceCentralizedImpl();
+ }
+
+ /**
+ *
+ * @return returns RestApiRequestBuilder bean if CentralAccessCondition is true
+ */
+ @Bean
+ @Conditional(CentralAccessCondition.class)
+ public RestApiRequestBuilder restApiRequestBuilder() {
+ return new RestApiRequestBuilder();
+ }
+
+ /**
+ *
+ * @return returns FunctionalMenuListServiceImpl bean if LocalAccessCondition is
+ * true
+ */
+ @Bean
+ @Conditional(LocalAccessCondition.class)
+ public FunctionalMenuListService functionalMenuListService() {
+ return new FunctionalMenuListServiceImpl();
+ }
+
+ /**
+ *
+ * @return returns FunctionalMenuListServiceCentralizedImpl bean if
+ * CentralAccessCondition is true
+ */
+
+ @Bean
+ @Conditional(CentralAccessCondition.class)
+ public FunctionalMenuListService functionalMenuListServiceCentralizedImpl() {
+ return new FunctionalMenuListServiceCentralizedImpl();
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.List;
+
+import org.onap.portalsdk.core.domain.App;
+
+/**
+ * Defines methods to fetch App domain objects.
+ *
+ * Very thin interface; Portal defines a much richer interface.
+ */
+public interface AppService {
+
+ /**
+ * Gets all apps defined in the table.
+ *
+ * @return List of apps.
+ */
+ List<App> getApps();
+
+ /**
+ * Gets the app with the specified ID.
+ *
+ * @param appId
+ * @return App with the specified ID.
+ */
+ App getApp(Long appId);
+
+ /**
+ * Gets the singleton entry - applications should have exactly 1 row in the
+ * FN_APP table.
+ */
+ App getDefaultApp();
+
+ /**
+ * Fetches the application name once from database
+ * and keep refers to the same name later on as required.
+ * @return Default Application Name
+ */
+ String getDefaultAppName();
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.List;
+
+import org.onap.portalsdk.core.domain.App;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("appService")
+@Transactional
+public class AppServiceImpl implements AppService{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppServiceImpl.class);
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ /**
+ * Loads the appName once from database and
+ * keep refers to it as required.
+ */
+ private static String defaultAppName = "";
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<App> getApps() {
+ return getDataAccessService().getList(App.class, null);
+ }
+
+ @Override
+ public App getApp(Long appId) {
+ return (App)getDataAccessService().getDomainObject(App.class, appId, null);
+ }
+
+ @Override
+ public App getDefaultApp() {
+ return getApp(1L);
+ }
+
+ /**
+ * Gets the data access service.
+ * @return DataAccessService
+ */
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ /**
+ * Sets the data access service.
+ * @param dataAccessService
+ */
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ /**
+ * Fetches the application name once from database
+ * and keep refers to the same name later on as required.
+ * @return Default Application Name
+ */
+ @Override
+ public String getDefaultAppName() {
+ if (AppServiceImpl.defaultAppName==null || AppServiceImpl.defaultAppName=="") {
+ App app = getApp(1L);
+ if (app!=null) {
+ AppServiceImpl.defaultAppName = app.getName();
+ } else {
+ logger.warn(EELFLoggerDelegate.errorLogger, ("Unable to locate the app information from the database."));
+ }
+ }
+ return AppServiceImpl.defaultAppName;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.HashMap;
+
+import org.onap.portalsdk.core.domain.AuditLog;
+
+public interface AuditService {
+ /**
+ *
+ * Update log data in database
+ *
+ * @param auditLog
+ * @param additionalParams
+ */
+
+ @SuppressWarnings("rawtypes")
+ void logActivity(AuditLog auditLog, HashMap additionalParams);
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.HashMap;
+
+import org.onap.portalsdk.core.domain.AuditLog;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("auditService")
+@Transactional
+public class AuditServiceImpl implements AuditService {
+ public AuditServiceImpl() {}
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @SuppressWarnings("rawtypes")
+ public void logActivity(AuditLog auditLog, HashMap additionalParams) {
+ getDataAccessService().saveDomainObject(auditLog, additionalParams);
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.*;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.domain.BroadcastMessage;
+
+@SuppressWarnings("rawtypes")
+public interface BroadcastService {
+ HashMap getBcModel(HttpServletRequest request);
+ Hashtable getBroadcastMessages();
+ void loadMessages();
+ BroadcastMessage getBroadcastMessage(HttpServletRequest request);
+ void saveBroadcastMessage(BroadcastMessage broadcastMessage);
+ void removeBroadcastMessage(BroadcastMessage broadcastMessage);
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.domain.BroadcastMessage;
+import org.onap.portalsdk.core.domain.Lookup;
+import org.onap.portalsdk.core.service.support.FusionService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.AppUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.bind.ServletRequestBindingException;
+import org.springframework.web.bind.ServletRequestUtils;
+
+@SuppressWarnings("rawtypes")
+@Service("broadcastService")
+@Transactional
+public class BroadcastServiceImpl extends FusionService implements BroadcastService {
+
+ public BroadcastServiceImpl() {
+ }
+
+ @Autowired
+ private DataAccessService dataAccessService;
+ private static Hashtable broadcastMessages = new Hashtable();
+
+ @SuppressWarnings("unchecked")
+ public void loadMessages() {
+ List messageLocations = AppUtils.getLookupListNoCache("fn_lu_message_location", "message_location_id", "message_location_descr", "", "message_location_id");
+
+ for (int i=0; i < messageLocations.size(); i++) {
+ Lookup location = (Lookup)messageLocations.get(i);
+ String locationId = location.getValue();
+
+ broadcastMessages.put(locationId, getPersistedBroadcastMessages(locationId));
+ }
+ }
+
+ public HashMap getBcModel(HttpServletRequest request){
+ HashMap bcModel = new HashMap();
+
+ List items = null;
+ int messageId = ServletRequestUtils.getIntParameter(request, "message_id", 0);
+ String task = ServletRequestUtils.getStringParameter(request, "task", "get");
+
+ // delete or toggle activation on the selected record (if applicable)
+ if (messageId != 0 && (task.equals("delete") || task.equals("toggleActive"))) {
+ BroadcastMessage message = (BroadcastMessage)getDataAccessService().getDomainObject(BroadcastMessage.class, new Long(messageId), null);
+
+ if (task.equals("delete")) {
+ getDataAccessService().deleteDomainObject(message, null);
+ }
+ else if (task.equals("toggleActive")) {
+ HashMap additionalParams = new HashMap();
+ additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request);
+
+ message.setActive(new Boolean(!message.getActive().booleanValue()));
+ getDataAccessService().saveDomainObject(message, additionalParams);
+ }
+ loadMessages();
+ }
+
+ items = getDataAccessService().getList(BroadcastMessage.class, null);
+ Collections.sort(items);
+ bcModel.put("messagesList", packageMessages(items));
+
+ List locations = AppUtils.getLookupList("fn_lu_message_location", "message_location_id", "message_location_descr", "", "message_location_id");
+ bcModel.put("messageLocations", locations);
+
+ if ("true".equals(SystemProperties.getProperty(SystemProperties.CLUSTERED))) {
+ List sites = AppUtils.getLookupList("fn_lu_broadcast_site", "broadcast_site_cd", "broadcast_site_descr", "", "broadcast_site_descr");
+ bcModel.put("broadcastSites", sites);
+ }
+
+ return bcModel;
+ }
+
+ @SuppressWarnings("unchecked")
+ private HashMap packageMessages(List messages) {
+ HashMap messagesList = new HashMap();
+ Set locationMessages = null;
+
+ Integer previousLocationId = null;
+
+ for (int i=0; i < messages.size(); i++) {
+ BroadcastMessage message = (BroadcastMessage)messages.get(i);
+
+ if (!message.getLocationId().equals(previousLocationId)) {
+ if (previousLocationId != null) {
+ messagesList.put(previousLocationId.toString(), locationMessages);
+ }
+
+ locationMessages = new TreeSet();
+ previousLocationId = message.getLocationId();
+ }
+
+ locationMessages.add(message);
+ }
+
+ if (previousLocationId != null) {
+ messagesList.put(previousLocationId.toString(), locationMessages);
+ }
+
+ return messagesList;
+ }
+
+
+ @SuppressWarnings("unchecked")
+ private List getPersistedBroadcastMessages(String locationId) {
+ HashMap params = new HashMap();
+
+
+
+ params.put("location_id", new Integer(locationId));
+
+ Calendar calInstanceToday = Calendar.getInstance();
+ calInstanceToday.set(Calendar.HOUR, 0);
+ calInstanceToday.set(Calendar.MINUTE, 0);
+ calInstanceToday.set(Calendar.SECOND, 0);
+ params.put("today_date", calInstanceToday.getTime());
+
+ return getDataAccessService().executeNamedQuery("broadcastMessages", params, null);
+ }
+
+ public Hashtable getBroadcastMessages() {
+ return broadcastMessages;
+ }
+
+ public static List getBroadcastMessages(String locationId) {
+ return (List)broadcastMessages.get(locationId);
+ }
+
+ public static String displayMessages(String locationId) {
+ return displayServerMessages(locationId, null);
+ }
+
+ public static String displayServerMessages(String locationId, String siteCd) {
+ StringBuffer html = new StringBuffer();
+
+ List messages = getBroadcastMessages(locationId);
+
+ for (int i=0; i < messages.size(); i++) {
+ BroadcastMessage message = (BroadcastMessage)messages.get(i);
+
+ if ((message.getSiteCd() == null) || ((message.getSiteCd() != null) && message.getSiteCd().equals(siteCd))) {
+ html.append("<li class=\"broadcastMessage\">")
+ .append(message.getMessageText());
+ }
+ }
+
+ if (html.length() > 0) {
+ html.insert(0, "<ul class=\"broadcastMessageList\">");
+ html.append("</ul>");
+ }
+
+ return html.toString();
+ }
+
+ public static boolean hasMessages(String locationId) {
+ return hasServerMessages(locationId, null);
+ }
+
+ public static boolean hasServerMessages(String locationId, String siteCd) {
+ List messages = getBroadcastMessages(locationId);
+ boolean messagesExist = !((messages == null) || messages.size() == 0);
+ if (!messagesExist)
+ return false;
+
+ if (siteCd == null) {
+ return messagesExist;
+ }
+ else {
+ for (int i=0; i < messages.size(); i++) {
+ BroadcastMessage message = (BroadcastMessage)messages.get(i);
+
+ if ((message.getSiteCd() == null) || message.getSiteCd().equals(siteCd)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ dataAccessService = dataAccessService;
+ }
+
+ public BroadcastMessage getBroadcastMessage(HttpServletRequest request) {
+ long messageId = ServletRequestUtils.getLongParameter(request, "message_id", 0);
+
+ BroadcastMessage message = new BroadcastMessage();
+ if(messageId!=0)
+ message = (BroadcastMessage)getDataAccessService().getDomainObject(BroadcastMessage.class, new Long(messageId), null);
+
+ if (message.getLocationId() == null) {
+ try {
+ message.setLocationId(new Integer(ServletRequestUtils.getStringParameter(request, "message_location_id")));
+ } catch (NumberFormatException e) {
+ e.printStackTrace();
+ } catch (ServletRequestBindingException e) {
+ e.printStackTrace();
+ }
+ message.setActive(Boolean.TRUE);
+ }
+
+ return message;
+ }
+
+ @Override
+ public void saveBroadcastMessage(BroadcastMessage broadcastMessage) {
+ dataAccessService.saveDomainObject(broadcastMessage, null);
+ }
+
+ @Override
+ public void removeBroadcastMessage(BroadcastMessage broadcastMessage) {
+ dataAccessService.deleteDomainObject(broadcastMessage, null);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+import org.springframework.context.annotation.Condition;
+import org.springframework.context.annotation.ConditionContext;
+import org.springframework.core.type.AnnotatedTypeMetadata;
+
+public class CentralAccessCondition implements Condition {
+
+ /**
+ * returns true if the application is centralized
+ */
+ @Override
+ public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
+ boolean isRemote = false;
+
+ if(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) == null)
+ {
+ isRemote = false;
+ }
+ else if(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) != null && PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED).equals("remote")){
+ isRemote = true;
+ }
+
+ return isRemote;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.hibernate.FetchMode;
+import org.hibernate.criterion.Criterion;
+import org.hibernate.criterion.Order;
+import org.hibernate.criterion.ProjectionList;
+import org.onap.portalsdk.core.domain.support.DomainVo;
+
+@SuppressWarnings("rawtypes")
+public interface DataAccessService {
+
+ // generic view, save, delete methods
+ DomainVo getDomainObject(Class domainClass, Serializable id, HashMap additionalParams);
+ void deleteDomainObject(DomainVo domainObject, HashMap additionalParams);
+ void deleteDomainObjects(Class domainClass, String whereClause, HashMap additionalParams);
+ void saveDomainObject(DomainVo domainObject, HashMap additionalParams);
+
+ // generic get list method(s)
+ List getList(Class domainClass, HashMap additionalParams);
+ List getList(Class domainClass, String filter, String orderBy, HashMap additionalParams);
+ List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy, HashMap additionalParams);
+ List<?> getList(Class<?> domainClass, ProjectionList projectionsList , List<Criterion> restrictionsList , List<Order> orderByList);
+ public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList, List<Order> orderByList,HashMap<String,FetchMode> fetchModeMap);
+
+ List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, HashMap additionalParams);
+
+ // generic native-SQL execution methods
+ List executeSQLQuery(String sql, Class domainClass, HashMap additionalParams);
+ List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex,HashMap additionalParams);
+
+ // generic HQL execution methods
+ List executeQuery(String hql, HashMap additionalParams);
+ List executeQuery(String hql, Integer fromIndex, Integer toIndex, HashMap additionalParams);
+
+ // generic named query execution methods
+ List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, HashMap additionalParams);
+ List executeNamedQuery(String queryName, Map params, HashMap additionalParams);
+ List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex, HashMap additionalParams);
+
+ //with Where Clause for RAPTOR ZK
+ List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams);
+ List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params);
+ List executeNamedQuery(Class entity, String queryName, String whereClause, Map params, Integer fromIndex, Integer toIndex, HashMap additionalParams);
+ List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams);
+
+ // generic update query execution method
+ int executeUpdateQuery(String sql, HashMap additionalParams) throws RuntimeException;
+
+ // generic named update query execution method
+ int executeNamedUpdateQuery(String queryName, Map params, HashMap additionalParams) throws RuntimeException;
+
+ // synchronizes the local updates with the database (and vice versa)
+ void synchronize(HashMap additionalParams);
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.hibernate.Criteria;
+import org.hibernate.FetchMode;
+import org.hibernate.Query;
+import org.hibernate.SQLQuery;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.criterion.Criterion;
+import org.hibernate.criterion.Order;
+import org.hibernate.criterion.ProjectionList;
+import org.onap.portalsdk.core.domain.Lookup;
+import org.onap.portalsdk.core.domain.support.DomainVo;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.support.FusionService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ * Provides implementations of methods in {@link DataAccessService}.
+ */
+@Transactional
+public class DataAccessServiceImpl extends FusionService implements DataAccessService {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DataAccessServiceImpl.class);
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ @Override
+ public DomainVo getDomainObject(Class domainClass, Serializable id, HashMap additionalParams) {
+ DomainVo vo = null;
+ Session session = sessionFactory.getCurrentSession();
+ logger.info(EELFLoggerDelegate.debugLogger, "Getting " + domainClass.getName() + " record for id - " + id.toString());
+ vo = (DomainVo) session.get(domainClass, id);
+
+ if (vo == null) {
+ try {
+ vo = (DomainVo) domainClass.newInstance();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "An error occured while instantiating a class of " + domainClass.getName() + e.getMessage());
+ }
+ }
+ return vo;
+ }
+
+ @Override
+ public void deleteDomainObject(DomainVo domainObject, HashMap additionalParams) {
+ Session session = sessionFactory.getCurrentSession();
+ session.delete(domainObject);
+ }
+
+ @Override
+ public void deleteDomainObjects(Class domainClass, String whereClause, HashMap additionalParams) {
+ int rowsAffected = 0;
+ Session session = sessionFactory.getCurrentSession();
+
+ StringBuffer sql = new StringBuffer("delete from ");
+
+ sql.append(domainClass.getName()).append(" where ").append(whereClause);
+
+ rowsAffected = session.createQuery(sql.toString()).executeUpdate();
+ /* return rowsAffected; */
+ }
+
+ @Override
+ public void saveDomainObject(DomainVo vo, HashMap additionalParams) {
+ Integer userId = 1;
+ if (additionalParams != null) {
+ // look for a passed user id
+ // userId = (Integer)additionalParams.get(Parameters.PARAM_USERID);
+ Object uid = additionalParams.get(Parameters.PARAM_USERID);
+ if (uid instanceof Integer) {
+ userId = (Integer) uid;
+ } else if (uid instanceof Long) {
+ userId = ((Long) uid).intValue();
+ }
+ // if (userId == null) {
+ // look for a passed request to get the user id from
+ // userId = new
+ // Integer(UserUtils.getUserId((HttpServletRequest)additionalParams.get(Parameters.PARAM_HTTP_REQUEST)));
+ // }
+ }
+ _update(vo, userId);
+ }
+
+ /**
+ * Creates or updates the specified virtual object. Uses the specified user
+ * ID as the creator and modifier if a new object is created; uses ID only
+ * as modifier if an object already exists.
+ *
+ * @param vo
+ * @param userId
+ * Ignored if value is zero.
+ */
+ protected final void _update(DomainVo vo, int userId) {
+ Date timestamp = new Date();
+
+ Session session = sessionFactory.getCurrentSession();
+
+ if (vo.getId() == null || vo.getId().intValue() == 0) { // add new
+ vo.setCreated(timestamp);
+ vo.setModified(timestamp);
+
+ if (userId != 0
+ && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
+ vo.setCreatedId(new Long(userId));
+ vo.setModifiedId(new Long(userId));
+ }
+ } else { // update existing
+ vo.setModified(timestamp);
+
+ if (userId != 0
+ && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
+ vo.setModifiedId(new Long(userId));
+ }
+ }
+
+ session.saveOrUpdate(vo);
+ }
+
+ /**
+ * generic get list method
+ *
+ * @param domainClass
+ * @param filterClause
+ * @param fromIndex
+ * @param toIndex
+ * @param orderBy
+ * @return
+ */
+ private List getListCommon(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex,
+ String orderBy) {
+ List list = null;
+ String className = domainClass.getName();
+ Session session = sessionFactory.getCurrentSession();
+
+ if (logger.isInfoEnabled()) {
+ logger.info(EELFLoggerDelegate.debugLogger, "Getting " + className.toLowerCase() + " records"
+ + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "")
+ + "...");
+ if (filterClause != null && filterClause.length() > 0)
+ logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause);
+ }
+
+ list = session.createQuery("from " + className + Utilities.nvl(filterClause, "")
+ + ((orderBy != null) ? " order by " + orderBy : "")).list();
+ list = (fromIndex != null) ? list.subList(fromIndex.intValue() - 1, toIndex.intValue()) : list;
+
+ if (orderBy == null && list != null)
+ Collections.sort(list);
+
+ return list;
+ }
+
+ @Override
+ public List getList(Class domainClass, HashMap additionalParams) {
+ return getListCommon(domainClass, null, null, null, null);
+ }
+
+ @Override
+ public List getList(Class domainClass, String filter, String orderBy, HashMap additionalParams) {
+ return getListCommon(domainClass, filter, null, null, orderBy);
+ }
+
+ @Override
+ public List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy,
+ HashMap additionalParams) {
+ return getListCommon(domainClass, filter, new Integer(fromIndex), new Integer(toIndex), orderBy);
+ }
+
+ @Override
+ public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
+ List<Order> orderByList) {
+
+ Session session = sessionFactory.getCurrentSession();
+
+ Criteria criteria = session.createCriteria(domainClass);
+
+ if (projectionsList != null) {
+ criteria.setProjection(projectionsList);
+ }
+
+ if (restrictionsList != null && !restrictionsList.isEmpty()) {
+ for (Criterion criterion : restrictionsList)
+ criteria.add(criterion);
+ }
+
+ if (orderByList != null && !orderByList.isEmpty()) {
+ for (Order order : orderByList)
+ criteria.addOrder(order);
+ }
+ /*
+ * if(fetchModeMap!=null){ Iterator<String> itr =
+ * fetchModeMap.keySet().iterator(); String key=null;
+ * while(itr.hasNext()){ key = itr.next();
+ * criteria.setFetchMode(key,fetchModeMap.get(key)); } }
+ */
+ return criteria.list();
+ }
+
+ @Override
+ public List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy,
+ HashMap additionalParams) {
+ if (logger.isInfoEnabled())
+ logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list...");
+ String dbOrderByCol = dbOrderBy;
+
+ Session session = sessionFactory.getCurrentSession();
+
+ // default the orderBy if null;
+ if (Utilities.nvl(dbOrderBy).length() == 0) {
+ dbOrderByCol = dbLabelCol;
+ dbOrderBy = dbLabelCol;
+ } else {
+ if (dbOrderBy.lastIndexOf(" ") > -1) {
+ dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" "));
+ }
+ }
+
+ StringBuffer sql = new StringBuffer();
+
+ sql.append("select distinct ").append(dbLabelCol).append(" as lab, ").append(dbValueCol).append(" as val, ")
+ .append(dbOrderByCol).append(" as sortOrder ").append("from ").append(dbTable).append(" ")
+ .append((Utilities.nvl(dbFilter).length() == 0) ? "" : (" where " + dbFilter)).append(" order by ")
+ .append(dbOrderBy);
+
+ List list = null;
+ try {
+ list = session.createSQLQuery(sql.toString()).addEntity(Lookup.class).list();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.debugLogger, "Failed to create SQL lookup query for [" + sql + "]" + e.getMessage());
+ }
+ return list;
+ }
+
+ /*
+ * methods accepting a Map of additional params to passed to the DAO (for
+ * extensibility, just in case)
+ */
+
+ @Override
+ public List executeSQLQuery(String sql, Class domainClass, HashMap additionalParams) {
+ return executeSQLQuery(sql, domainClass, null, null, additionalParams);
+ }
+
+ @Override
+ public List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex,
+ HashMap additionalParams) {
+ Session session = sessionFactory.getCurrentSession();
+
+ SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass);
+
+ if (fromIndex != null && toIndex != null) {
+ query.setFirstResult(fromIndex.intValue());
+ int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
+ query.setMaxResults(pageSize);
+ }
+
+ return query.list();
+ }
+
+ @Override
+ public List executeQuery(String sql, HashMap additionalParams) {
+ return executeQuery(sql, null, null, additionalParams);
+ }
+
+ @Override
+ public List executeQuery(String sql, Integer fromIndex, Integer toIndex, HashMap additionalParams) {
+ Session session = sessionFactory.getCurrentSession();
+
+ Query query = session.createQuery(sql);
+
+ if (fromIndex != null && toIndex != null) {
+ query.setFirstResult(fromIndex.intValue());
+ int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
+ query.setMaxResults(pageSize);
+ }
+
+ return query.list();
+ }
+
+ @Override
+ public List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, HashMap additionalParams) {
+ return executeNamedQuery(queryName, null, fromIndex, toIndex, additionalParams);
+ }
+
+ @Override
+ public List executeNamedQuery(String queryName, Map params, HashMap additionalParams) {
+ return executeNamedQuery(queryName, params, null, null, additionalParams);
+ }
+
+ @Override
+ public List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex,
+ HashMap additionalParams) {
+ Session session = sessionFactory.getCurrentSession();
+ Query query = session.getNamedQuery(queryName);
+ bindQueryParameters(query, params);
+ if (fromIndex != null && toIndex != null) {
+ query.setFirstResult(fromIndex.intValue());
+ int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
+ query.setMaxResults(pageSize);
+ }
+ return query.list();
+ }
+
+ /**
+ * Stores parameters into the query using String keys from the map. Gives
+ * special treatment to map values of Collection and array type.
+ *
+ * @param query
+ * Query with parameters
+ * @param params
+ * Map of String to Object.
+ */
+ private void bindQueryParameters(Query query, Map params) {
+ if (params != null) {
+ for (Iterator i = params.entrySet().iterator(); i.hasNext();) {
+ Map.Entry entry = (Map.Entry) i.next();
+
+ Object parameterValue = entry.getValue();
+
+ if (!(parameterValue instanceof Collection) && !(parameterValue instanceof Object[])) {
+ query.setParameter((String) entry.getKey(), parameterValue);
+ } else if (parameterValue instanceof Collection) {
+ query.setParameterList((String) entry.getKey(), (Collection) parameterValue);
+ } else if (parameterValue instanceof Object[]) {
+ query.setParameterList((String) entry.getKey(), (Object[]) parameterValue);
+ }
+ }
+ }
+ }
+
+ // With Where Clause & RAPTOR's ZK
+
+ @Override
+ public List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy, boolean asc,
+ Integer fromIndex, Integer toIndex, HashMap additionalParams) {
+ // TODO Auto-generated method stub
+ logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
+ return null;
+ }
+
+ @Override
+ public List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params) {
+ // TODO Auto-generated method stub
+ logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
+ return null;
+ }
+
+ @Override
+ public List executeNamedQuery(Class entity, String queryName, String whereClause, Map params, Integer fromIndex,
+ Integer toIndex, HashMap additionalParams) {
+ // TODO Auto-generated method stub
+ logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
+ return null;
+ }
+
+ @Override
+ public List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params,
+ String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams) {
+ // TODO Auto-generated method stub
+ logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
+ return null;
+ }
+
+ @Override
+ public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
+ List<Order> orderByList, HashMap<String, FetchMode> fetchModeMap) {
+ // TODO Auto-generated method stub
+ logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
+ return null;
+ }
+
+ @Override
+ public int executeUpdateQuery(String sql, HashMap additionalParams) throws RuntimeException {
+ // TODO Auto-generated method stub
+ logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
+ return 0;
+ }
+
+ @Override
+ public int executeNamedUpdateQuery(String queryName, Map params, HashMap additionalParams) throws RuntimeException {
+ // TODO Auto-generated method stub
+ logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
+ return 0;
+ }
+
+ @Override
+ public void synchronize(HashMap additionalParams) {
+ // TODO Auto-generated method stub
+ logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.util.YamlUtils;
+
+public class ElementLinkService {
+
+ /**
+ * Builds renderable model of element links in the network map. Parses YAML
+ * files with metadata and builds input for JoinJS to render in the browser
+ * as SVG.
+ *
+ * @param args
+ * arg 0 - realPath; arg 1 - callFlowName; arg 2 - callFlowStep.
+ * @return Renderable model of element links
+ * @throws Exception
+ */
+ public String buildElementLinkYaml(String[] args) throws Exception {
+ String relFilePath;
+ if (args[1].startsWith("custom"))
+ relFilePath = SystemProperties.getProperty("customCallFlow_path");
+ else
+ relFilePath = SystemProperties.getProperty("element_map_file_path");
+ final String yamlDirPath = new File(args[0], relFilePath).getPath();
+
+ String callFlowBusinessYml = "";
+ String callFlowStep = "";
+
+ if (args != null && args.length > 0) {
+ if (args[1] != null)
+ callFlowBusinessYml = args[1] + ".yml";
+ if (args[2] != null)
+ callFlowStep = args[2];
+ }
+
+ ElementLinkService mapper = new ElementLinkService();
+ String linkYaml = mapper.createLinkFile(yamlDirPath, callFlowBusinessYml, callFlowStep);
+ return linkYaml;
+ }
+
+ /*
+ * public String main2(String[] args) throws Exception {
+ *
+ * String filePath = SystemProperties.getProperty("element_map_file_path") +
+ * File.separator; String callFlowBusinessYml = ""; String callFlowStep =
+ * "";
+ *
+ * if (args != null && args.length > 0) {
+ *
+ * if (args[0] != null) { callFlowBusinessYml = args[0] + "-Override.yml"; }
+ *
+ * if (args[1] != null) { callFlowStep = args[1]; } }
+ *
+ * ElementLinkService mapper = new ElementLinkService();
+ *
+ * return mapper.createLinkFileAdditional(filePath, callFlowBusinessYml,
+ * callFlowStep); }
+ */
+
+ public static void main(String[] args) throws Exception {
+
+ String filePath = "\\D2Platform\\war\\WEB-INF\\resources\\trisim_files";
+ String callFlowBusinessYml = "call_flow_hc-origination-termination-to-volteue-3.3.16-Override.yml";
+
+ ElementLinkService mapper = new ElementLinkService();
+
+ // System.out.print(mapper.createLinkFile(filePath, networkToscaYml,
+ // networkToscaUeYml, networkLayoutYml, callFlowBusinessYml,"Step_1"));
+ System.out.print(mapper.createLinkFileAdditional(filePath, callFlowBusinessYml, "Step_2"));
+ }
+
+ @SuppressWarnings("unchecked")
+ protected String createLinkFile(String resourceFilePath, String callFLowBsFileName, String callFlowStep)
+ throws Exception {
+
+ Map<String, Object> callFlowBs = YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName);
+
+ List<Map<String, Object>> callSteps = (List<Map<String, Object>>) callFlowBs.get("callSequenceSteps");
+ String callFlowName = (String) callFlowBs.get("shortName");
+ return addLinks(resourceFilePath, callFlowName, callSteps, callFlowStep);
+
+ }
+
+ @SuppressWarnings("unchecked")
+ protected String createLinkFileAdditional(String resourceFilePath, String callFLowBsFileName, String callFlowStep)
+ throws Exception {
+
+ // Map<String, Object> callFlowBs =
+ // YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName);
+
+ // return YamlUtils.returnYaml(callFlowBs);
+
+ Map<String, Object> callFlowBs;
+
+ try {
+ callFlowBs = YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName);
+
+ List<Map<String, Object>> callSteps = (List<Map<String, Object>>) callFlowBs.get("callSequenceSteps");
+ String callFlowName = (String) callFlowBs.get("shortName");
+ return addLinksAdditional(resourceFilePath, callFlowName, callSteps, callFlowStep);
+
+ } catch (Exception e) {
+
+ return "";
+ }
+
+ }
+
+ @SuppressWarnings("unchecked")
+ protected String addLinks(String filePath, String callFlowName, List<Map<String, Object>> callSteps,
+ String callFlowStep) throws IOException {
+
+ Map<String, List<String>> checkDuplicateMap = new HashMap<String, List<String>>();
+
+ for (Map<String, Object> callStep : callSteps) {
+
+ if (((String) callStep.get("name")).split(":")[0].trim().replace(" ", "_").equals(callFlowStep)) {
+
+ // String callFlowStepName = callFlowName + "_" +
+ // ((String)callStep.get("name")).split("-")[0].trim().replace("
+ // ", "_")+".yml";
+
+ List<Map<String, Object>> links = new ArrayList<Map<String, Object>>();
+
+ List<Map<String, Object>> subSteps = (List<Map<String, Object>>) callStep.get("subSteps");
+
+ for (Map<String, Object> subStep : subSteps) {
+ Map<String, Object> link = new HashMap<String, Object>();
+
+ String source = (String) subStep.get("source_tosca_id");
+ String destination = (String) subStep.get("destination_tosca_id");
+
+ if ((checkDuplicateMap.get(source) == null || checkDuplicateMap.get(source).isEmpty()
+ || !checkDuplicateMap.get(source).contains(destination)) && !source.equals(destination)) {
+ if (checkDuplicateMap.get(destination) == null) {
+ List<String> toscaList = new ArrayList<String>();
+ checkDuplicateMap.put(destination, toscaList);
+ }
+
+ if (checkDuplicateMap.get(source) == null) {
+ List<String> toscaList = new ArrayList<String>();
+ checkDuplicateMap.put(source, toscaList);
+ }
+
+ List<String> toscaSourceList = checkDuplicateMap.get(destination);
+ toscaSourceList.add(source);
+
+ List<String> toscaDestinationList = checkDuplicateMap.get(source);
+ toscaDestinationList.add(destination);
+
+ link.put("s", source);
+ link.put("d", destination);
+ links.add(link);
+
+ /*
+ * may be needed in future but nnot currently
+ *
+ * if((String) subStep.get("link_visibility")!=null){
+ * if(((String)
+ * subStep.get("link_visibility")).equals("No")){
+ *
+ * } }else{
+ *
+ * links.add(link); }
+ */
+
+ }
+
+ }
+
+ Map<String, Object> callFlowUI = new HashMap<String, Object>();
+ callFlowUI.put("linkList", links);
+
+ return YamlUtils.returnYaml(callFlowUI);
+
+ // YamlUtils.writeYamlFile(filePath, callFlowStepName,
+ // callFlowUI);
+ }
+
+ }
+ return "";
+ }
+
+ protected String addLinksAdditional(String filePath, String callFlowName, List<Map<String, Object>> callSteps,
+ String callFlowStep) throws IOException {
+
+ for (Map<String, Object> callStep : callSteps) {
+
+ if (((String) callStep.get("name")).split(":")[0].trim().replace(" ", "_").equals(callFlowStep)) {
+
+ // String callFlowStepName = callFlowName + "_" +
+ // ((String)callStep.get("name")).split("-")[0].trim().replace("
+ // ", "_")+".yml";
+
+ Map<String, Object> callFlowUI = new HashMap<String, Object>();
+ try {
+ List<Map<String, Object>> links = addLinkVertices(callStep);
+ callFlowUI.put("linkList", links);
+ } catch (Exception e) {
+ }
+ try {
+ List<String> activeIds = addActiveNodes(callStep);
+ callFlowUI.put("activeIds", activeIds);
+ } catch (Exception e) {
+ }
+ try {
+ List<Map<String, Object>> disconnectLinks = addDisconnectLinks(callStep);
+ callFlowUI.put("disconnectLinks", disconnectLinks);
+ } catch (Exception e) {
+ }
+
+ return YamlUtils.returnYaml(callFlowUI);
+ }
+ }
+
+ return "";
+ }
+
+ @SuppressWarnings("unchecked")
+ List<String> addActiveNodes(Map<String, Object> callStep) {
+ List<String> activeIds = (List<String>) callStep.get("activeIds");
+ return activeIds;
+ }
+
+ @SuppressWarnings("unchecked")
+ List<Map<String, Object>> addDisconnectLinks(Map<String, Object> callStep) {
+ List<Map<String, Object>> disconnectLinks = (List<Map<String, Object>>) callStep.get("disconnectLinks");
+ return disconnectLinks;
+ }
+
+ @SuppressWarnings("unchecked")
+ List<Map<String, Object>> addLinkVertices(Map<String, Object> callStep) {
+ List<Map<String, Object>> links = new ArrayList<Map<String, Object>>();
+
+ List<Map<String, Object>> vertices = (List<Map<String, Object>>) callStep.get("vertices");
+
+ for (int i = 0; i < vertices.size() - 1; i++) {
+ Map<String, Object> vertex = (Map<String, Object>) vertices.get(i);
+ Map<String, Object> vertexNext = (Map<String, Object>) vertices.get(i + 1);
+
+ Integer sourceX = (Integer) vertex.get("x");
+ Integer sourceY = (Integer) vertex.get("y");
+ String sourceD = (String) vertex.get("D");
+ String sourceL = (vertex.get("L") != null) ? (String) vertex.get("L") : "-";
+
+ if (sourceX == -999) // there is a break in the linkage
+ continue;
+
+ Integer destinationX = (Integer) vertexNext.get("x");
+ Integer destinationY = (Integer) vertexNext.get("y");
+ String destinationD = (String) vertexNext.get("D");
+
+ if (destinationX == -999) // there is a break in the linkage
+ continue;
+
+ Map<String, Object> link = new HashMap<String, Object>();
+
+ link.put("s", sourceX + "," + sourceY + "," + sourceD + "," + sourceL);
+ link.put("d", destinationX + "," + destinationY + "," + destinationD);
+ links.add(link);
+ }
+ return links;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.apache.commons.lang.StringUtils;
+import org.onap.portalsdk.core.domain.support.Container;
+import org.onap.portalsdk.core.domain.support.Domain;
+import org.onap.portalsdk.core.domain.support.Element;
+import org.onap.portalsdk.core.domain.support.ElementDetails;
+import org.onap.portalsdk.core.domain.support.Layout;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.util.YamlUtils;
+import org.yaml.snakeyaml.Yaml;
+import org.yaml.snakeyaml.nodes.Tag;
+import org.yaml.snakeyaml.representer.Representer;
+
+public class ElementMapService {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ElementMapService.class);
+
+ /**
+ *
+ * @param contextRealPath
+ * @param layout
+ * @return
+ * @throws Exception
+ */
+ private String convertToYAML(String contextRealPath, Layout layout) throws Exception {
+
+ // Used to build image file relative URLs
+ final String iconRelPath = SystemProperties.getProperty("element_map_icon_path"); // "static/img/map/icons/";
+
+ Map<String, Domain> resultAICDomain = layout.domainRowCol;
+ Map<String, List<Domain>> domainMap = new HashMap<String, List<Domain>>();
+ List<Domain> domainList = new ArrayList<Domain>();
+ for (Domain d : resultAICDomain.values()) {
+ d.setWidth(10 * d.computeSize().getWidth());
+ d.setHeight(10 * d.computeSize().getHeight());
+ d.setLeft(10 * d.getP().getX());
+ d.setTop(10 * d.getP().getY());
+
+ List<Container> containerList = new ArrayList<Container>();
+ for (Container c : d.getContainerRowCol().values()) {
+ c.setWidth(10 * c.computeSize().getWidth());
+ c.setHeight(10 * c.computeSize().getHeight());
+ c.setLeft(10 * c.getP().getX());
+ c.setTop(10 * c.getP().getY());
+ Element ue = (Element) c.getElementRowCol().values().toArray()[0];
+ if (ue.getName().equals("ue1") || ue.getName().equals("ue2") || ue.getName().equals("ue3")
+ || ue.getName().equals("ue4") || ue.getName().equals("ue5") || ue.getName().equals("ue6")) {
+ c.setVisibilityType("invisible");
+ }
+
+ if (c.getContainerRowCol() != null) {
+ List<Container> innerContainerList = new ArrayList<Container>();
+ for (Container innerC : c.getContainerRowCol().values()) {
+ innerC.setName(innerC.getName());
+ innerC.setWidth(10 * innerC.computeSize().getWidth());
+ innerC.setHeight(10 * innerC.computeSize().getHeight());
+ innerC.setLeft(10 * innerC.getP().getX());
+ innerC.setTop(10 * innerC.getP().getY());
+
+ if (innerC.getElementRowCol() != null) {
+ List<Element> innerContainerEList = new ArrayList<Element>();
+ for (Element ele : innerC.getElementRowCol().values()) {
+ // ele.setName(ele.getName());
+ ele.setWidth(10 * ele.computeSize().getWidth());
+ ele.setHeight(10 * ele.computeSize().getHeight());
+ ele.setLeft(10 * ele.getP().getX());
+ ele.setTop(10 * ele.getP().getY() - 10);
+ ele.setImgFileName(iconRelPath + "/" + ele.getImgFileName());
+ if (ele.getBorderType().equals("V"))
+ ele.setBorderType("dashed");
+ else
+ ele.setBorderType("solid");
+ innerContainerEList.add(ele);
+ }
+ innerC.setElementList(innerContainerEList);
+ }
+ innerContainerList.add(innerC);
+ }
+ c.setInnerCList(innerContainerList);
+ }
+
+ if (c.getElementRowCol() != null) {
+ List<Element> elementList = new ArrayList<Element>();
+ for (Element e : c.getElementRowCol().values()) {
+ // e.setName(e.getName());
+ e.setWidth(10 * e.computeSize().getWidth());
+ e.setHeight(10 * e.computeSize().getHeight());
+ e.setLeft(10 * e.getP().getX());
+ e.setTop(10 * e.getP().getY() - 10);
+ e.setImgFileName(iconRelPath + "/" + e.getImgFileName());
+
+ if (e.getBorderType().equals("V"))
+ e.setBorderType("dashed");
+ else
+ e.setBorderType("solid");
+
+ if (e.getName().equals("ue1") || e.getName().equals("ue2") || e.getName().equals("ue3")
+ || e.getName().equals("ue4") || e.getName().equals("ue5") || e.getName().equals("ue6"))
+ e.setBgColor("white");
+ elementList.add(e);
+ }
+ c.setElementList(elementList);
+ }
+ containerList.add(c);
+ }
+ d.setContainerList(containerList);
+ domainList.add(d);
+
+ }
+ domainMap.put("domainList", domainList);
+
+ List<Domain> collapsedDomains = new ArrayList<Domain>();
+
+ // nline
+ for (Domain collapsed : layout.getCollapsedDomainsNewList()) {
+ collapsed.setWidth(10 * collapsed.computeSize().getWidth());
+ collapsed.setHeight(10 * collapsed.computeSize().getHeight());
+ collapsed.setLeft(10 * collapsed.getP().getX());
+ collapsed.setTop(10 * collapsed.getP().getY());
+ // nline
+ collapsed.setNewXafterColl(10 * collapsed.getNewXafterColl());
+ collapsed.setYafterColl(10 * collapsed.getYafterColl());
+ collapsedDomains.add(collapsed);
+ }
+
+ domainMap.put("collapsedDomainList", collapsedDomains);
+
+ Representer representer = new Representer();
+ representer.addClassTag(Domain.class, Tag.MAP);
+
+ Yaml yaml = new Yaml(representer);
+ String output = yaml.dump(domainMap);
+
+ return output;
+
+ }
+
+ private static HashMap<String, Object> toscaElementsMap = new HashMap<String, Object>();
+ private static HashMap<String, Element> elementMap = new HashMap<String, Element>();
+ private static HashMap<String, Element> miscElementMap = new HashMap<String, Element>();
+ private static HashMap<String, Container> outercontainers = new HashMap<String, Container>();
+ private static HashMap<String, Container> innercontainers = new HashMap<String, Container>();
+ private static HashMap<String, Domain> domainMap = new HashMap<String, Domain>();
+
+ private static String filePath = SystemProperties.getProperty("element_map_file_path");
+ private static String networkToscaYml = null;// "NetworkMap_topology_composition.yml";
+ private static String networkLayoutYml = null;// "network_map_layout.yml";
+
+ /**
+ * Builds renderable model of elements in the network map. Parses YAML files
+ * with metadata and builds input for JoinJS to render in the browser as
+ * SVG.
+ *
+ * @param args
+ * arg 0 - collapsedDomains; arg 1 - expandedDomains; arg 2 -
+ * context real path; arg 3 - contentFileName; arg 4 -
+ * layoutFileName
+ * @return Renderable model of elements
+ * @throws Exception
+ */
+ public String buildElementMapYaml(String args[]) throws Exception {
+
+ final String yamlDirPath = new File(args[2], filePath).getPath();
+ if (args != null && args.length > 4) {
+ if (args[3] != null)
+ networkToscaYml = args[3] + ".yml";
+ if (args[4] != null)
+ networkLayoutYml = args[4] + ".yml";
+ }
+
+ Map<String, Object> toscaYaml = YamlUtils.readYamlFile(yamlDirPath, networkToscaYml);
+ Map<String, Object> networkMapLayoutYaml = YamlUtils.readYamlFile(yamlDirPath, networkLayoutYml);
+
+ toscaElementsMap = new HashMap<String, Object>();
+ elementMap = new HashMap<String, Element>();
+ domainMap = new HashMap<String, Domain>();
+ outercontainers = new HashMap<String, Container>();
+ innercontainers = new HashMap<String, Container>();
+ miscElementMap = new HashMap<String, Element>();
+
+ if (toscaYaml != null) {
+ for (String key : toscaYaml.keySet()) {
+ if ("topology_template".equalsIgnoreCase(key) && toscaYaml.get(key) instanceof HashMap) {
+ HashMap<String, Object> toscaTopologyDetails = (HashMap<String, Object>) toscaYaml.get(key);
+
+ for (String detailsKey : toscaTopologyDetails.keySet()) {
+
+ if ("node_templates".equalsIgnoreCase(detailsKey)
+ && toscaTopologyDetails.get(detailsKey) instanceof HashMap) {
+
+ toscaElementsMap = (HashMap<String, Object>) toscaTopologyDetails.get(detailsKey);
+
+ // for (String toscaElementKey :
+ // toscaElementsMap.keySet()) {
+ //// System.out.println("Element - "+ "key :" +
+ //// toscaElementKey);
+ // }
+
+ }
+ }
+ }
+
+ }
+ }
+
+ if (networkMapLayoutYaml != null) {
+ if (networkMapLayoutYaml.containsKey("toscaNetworkMapElementStyleList")
+ && networkMapLayoutYaml.get("toscaNetworkMapElementStyleList") instanceof ArrayList) {
+
+ ArrayList<Object> elementlist = (ArrayList<Object>) networkMapLayoutYaml
+ .get("toscaNetworkMapElementStyleList");
+ String elementName;
+ String elementID;
+ String imgPath;
+ String row;
+ String column;
+ String mapKey;
+ int i = 0;
+
+ if (elementlist != null) {
+ for (Object eachElement : elementlist) {
+ // System.out.println("toscaNetworkMapElementStyleList
+ // Container : " +eachElement);
+ if (eachElement != null && eachElement instanceof HashMap) {
+ HashMap<String, String> elementDetails = (HashMap<String, String>) eachElement;
+ if (elementDetails != null) {
+ elementName = "NA" + i;
+ elementID = "NA" + i;
+ imgPath = "NA" + i;
+ row = "0";
+ column = "0";
+ for (String detailsKey : elementDetails.keySet()) {
+ if ("tosca_id".equalsIgnoreCase(detailsKey))
+ elementName = elementDetails.get(detailsKey).toString();
+ if ("id".equalsIgnoreCase(detailsKey)) {
+ elementID = String.valueOf(elementDetails.get(detailsKey));
+ }
+ if ("row".equalsIgnoreCase(detailsKey)) {
+ row = String.valueOf(elementDetails.get(detailsKey));
+ }
+ if ("column".equalsIgnoreCase(detailsKey)) {
+ column = String.valueOf(elementDetails.get(detailsKey));
+ }
+ if ("icon".equalsIgnoreCase(detailsKey))
+ imgPath = elementDetails.get(detailsKey).toString();
+ }
+
+ if (elementMap.containsKey(elementName.concat("/").concat(row).concat(column))) {
+ if (elementMap.containsKey(elementName.concat("/").concat(String.valueOf(i))
+ .concat(String.valueOf(i)))) {
+ mapKey = elementName;
+ } else
+ mapKey = elementName.concat("/").concat(String.valueOf(i))
+ .concat(String.valueOf(i));
+
+ } else
+ mapKey = elementName.concat("/").concat(row).concat(column);
+
+ elementMap.put(mapKey, fetchElementObject(elementID, elementName, imgPath));
+ }
+ }
+ i++;
+ }
+ }
+
+ for (String elementkey : elementMap.keySet()) {
+ Element c = (Element) elementMap.get(elementkey);
+ // System.out.println("Element - "+ "key :" +elementkey +" -
+ // " + "value :" + c.getName());
+ }
+
+ if (!elementMap.isEmpty()) {
+ miscElementMap = new HashMap<String, Element>(elementMap);
+ }
+ }
+
+ if (networkMapLayoutYaml.containsKey("containerStyleList")
+ && networkMapLayoutYaml.get("containerStyleList") instanceof ArrayList) {
+
+ ArrayList<Object> containerstylelist = (ArrayList<Object>) networkMapLayoutYaml
+ .get("containerStyleList");
+ String containerName;
+ String containerID;
+ String domain;
+ String row;
+ String column;
+ String mapKey;
+ int i = 0;
+
+ if (containerstylelist != null) {
+ // Inner Containers
+ for (Object eachContainer : containerstylelist) {
+ if (eachContainer != null && eachContainer instanceof HashMap) {
+ HashMap<String, String> containerDetails = (HashMap<String, String>) eachContainer;
+ if (containerDetails != null) {
+ containerName = "NA" + i;
+ containerID = "NA" + i;
+ domain = "NA" + i;
+ row = "0";
+ column = "0";
+
+ for (String detailsKey : containerDetails.keySet()) {
+ if ("logical_group_name".equalsIgnoreCase(detailsKey))
+ containerName = containerDetails.get(detailsKey).toString();
+ if ("id".equalsIgnoreCase(detailsKey)) {
+ containerID = String.valueOf(containerDetails.get(detailsKey));
+ }
+ if ("domain".equalsIgnoreCase(detailsKey)) {
+ domain = containerDetails.get(detailsKey).toString();
+ }
+ if ("row".equalsIgnoreCase(detailsKey)) {
+ row = String.valueOf(containerDetails.get(detailsKey));
+ }
+ if ("column".equalsIgnoreCase(detailsKey)) {
+ column = String.valueOf(containerDetails.get(detailsKey));
+ }
+ }
+ if (containerName.contains("/")) {
+
+ if (innercontainers.containsKey(
+ (domain + ":" + containerName).concat("/").concat(row).concat(column))) {
+ if (elementMap.containsKey((domain + ":" + containerName).concat("/")
+ .concat(String.valueOf(i)).concat(String.valueOf(i)))) {
+ mapKey = (domain + ":" + containerName);
+ } else
+ mapKey = (domain + ":" + containerName).concat("/")
+ .concat(String.valueOf(i)).concat(String.valueOf(i));
+
+ } else
+ mapKey = (domain + ":" + containerName).concat("/").concat(row).concat(column);
+
+ innercontainers.put(mapKey,
+ fetchContainerObject(containerID,
+ containerName.substring(containerName.indexOf("/") + 1), true,
+ containerName, domain));
+ }
+ }
+ }
+ i++;
+ }
+
+ // OuterContainers
+ i = 0;
+ for (Object eachContainer : containerstylelist) {
+ if (eachContainer != null && eachContainer instanceof HashMap) {
+ HashMap<String, String> containerDetails = (HashMap<String, String>) eachContainer;
+ if (containerDetails != null) {
+ containerName = "NA" + i;
+ containerID = "NA" + i;
+ domain = "NA" + i;
+ row = "0";
+ column = "0";
+
+ for (String detailsKey : containerDetails.keySet()) {
+ if ("logical_group_name".equalsIgnoreCase(detailsKey))
+ containerName = containerDetails.get(detailsKey).toString();
+ if ("id".equalsIgnoreCase(detailsKey)) {
+ containerID = String.valueOf(containerDetails.get(detailsKey));
+ }
+ if ("domain".equalsIgnoreCase(detailsKey)) {
+ domain = containerDetails.get(detailsKey).toString();
+ }
+ if ("row".equalsIgnoreCase(detailsKey)) {
+ row = String.valueOf(containerDetails.get(detailsKey));
+ }
+ if ("column".equalsIgnoreCase(detailsKey)) {
+ column = String.valueOf(containerDetails.get(detailsKey));
+ }
+ }
+ if (!containerName.contains("/")) {
+ if (outercontainers.containsKey(
+ (domain + ":" + containerName).concat("/").concat(row).concat(column))) {
+ if (outercontainers.containsKey((domain + ":" + containerName).concat("/")
+ .concat(String.valueOf(i)).concat(String.valueOf(i)))) {
+ mapKey = (domain + ":" + containerName);
+ } else
+ mapKey = (domain + ":" + containerName).concat("/")
+ .concat(String.valueOf(i)).concat(String.valueOf(i));
+
+ } else
+ mapKey = (domain + ":" + containerName).concat("/").concat(row).concat(column);
+ outercontainers.put(mapKey, fetchContainerObject(containerID, containerName, false,
+ containerName, domain));
+ }
+ // else innercontainers.put(domain +":"+
+ // containerName,
+ // fetchContainerObject(containerID,containerName.substring(containerName.indexOf("/")+1),false,containerName,domain));
+
+ }
+ }
+ i++;
+ }
+ }
+
+ for (String innerContainerkey : innercontainers.keySet()) {
+ Container c = (Container) innercontainers.get(innerContainerkey);
+ }
+
+ for (String outerContainerkey : outercontainers.keySet()) {
+ Container c = (Container) outercontainers.get(outerContainerkey);
+ }
+
+ }
+
+ if (networkMapLayoutYaml.containsKey("domainList")
+ && networkMapLayoutYaml.get("domainList") instanceof ArrayList) {
+
+ ArrayList<Object> domainlist = (ArrayList<Object>) networkMapLayoutYaml.get("domainList");
+ String domainName;
+ String domainID;
+ String row;
+ String column;
+ String mapKey;
+ int i = 0;
+
+ if (domainlist != null) {
+
+ HashMap<String, String> domainStagingMap = new HashMap<String, String>();
+ for (Object eachDomain : domainlist) {
+ // System.out.println("domainlist Container : "
+ // +eachDomain);
+ if (eachDomain != null && eachDomain instanceof HashMap) {
+ HashMap<String, String> domainDetails = (HashMap<String, String>) eachDomain;
+ if (domainDetails != null) {
+ domainName = "NA" + i;
+ domainID = "NA" + i;
+ row = "0";
+ column = "0";
+ for (String detailsKey : domainDetails.keySet()) {
+ if ("name".equalsIgnoreCase(detailsKey))
+ domainName = domainDetails.get(detailsKey).toString();
+ if ("id".equalsIgnoreCase(detailsKey)) {
+ domainID = String.valueOf(domainDetails.get(detailsKey));
+ }
+ if ("row".equalsIgnoreCase(detailsKey)) {
+ row = String.valueOf(domainDetails.get(detailsKey));
+ }
+ if ("column".equalsIgnoreCase(detailsKey)) {
+ column = String.valueOf(domainDetails.get(detailsKey));
+ }
+ }
+
+ if (domainStagingMap.containsKey(row.concat(column))) {
+ mapKey = domainName;
+ } else
+ mapKey = row.concat(column);
+
+ domainStagingMap.put(mapKey, domainID + "%" + domainName);
+ }
+ }
+ i++;
+ }
+
+ if (domainStagingMap != null && !domainStagingMap.isEmpty()) {
+ for (String domainsKey : new TreeSet<String>(domainStagingMap.keySet())) {
+ String value = domainStagingMap.get(domainsKey);
+ if (value.contains("%")) {
+ domainMap.put(domainsKey, fetchDomainObject(value.substring(0, value.indexOf("%")),
+ value.substring(value.indexOf("%") + 1)));
+ }
+ }
+ }
+ }
+
+ // for (String domainkey : domainMap.keySet()) {
+ // Domain c = (Domain) domainMap.get(domainkey);
+ // System.out.println("Domain - "+ "key :" +domainkey +" - "
+ // + "value :" + c.getName());
+ // }
+ }
+
+ }
+
+ Layout dynamicLayout = new Layout(domainMap, 2, 10, 1, 5);
+ dynamicLayout.computeDomainPositionsModified();
+
+ /*
+ * Map<String, Domain> resultAICDomain2 = dynamicLayout.domainRowCol;
+ * for (String key : resultAICDomain2.keySet()) { if
+ * (resultAICDomain2.get(key).getP() != null) {
+ * System.out.println(resultAICDomain2.get(key).name+" "+"x:"+
+ * resultAICDomain2.get(key).getP().getX()+","+"y:"+
+ * resultAICDomain2.get(key).getP().getY()+","+"width:"+
+ * resultAICDomain2.get(key).computeSize().getWidth()
+ * +","+"height:"+resultAICDomain2.get(key).computeSize(). getHeight());
+ *
+ * } }
+ */
+
+ ElementMapService cm2 = new ElementMapService();
+ try {
+
+ if (args != null && args.length > 0) {
+
+ if (args[0] != null) {
+ String collapsedDomains[] = args[0].split(",");
+ for (String collapsedDomain : collapsedDomains)
+ // dynamicLayout.collapseDomainModified(collapsedDomain);
+ dynamicLayout.collapseDomainNew(collapsedDomain);
+ }
+
+ if (args[1] != null) {
+ String expandedDomains[] = args[1].split(",");
+ for (String expandedDomain : expandedDomains)
+ // dynamicLayout.uncollapseDomainNew(expandedDomain);
+ dynamicLayout.uncollapseDomainNew1(expandedDomain);
+ }
+
+ return cm2.convertToYAML(args[2], dynamicLayout);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "buildElementMapYaml failed", e);
+ }
+
+ return "";
+ }
+
+ private static int computeRows(Set<String> keys) {
+ int i = 0;
+ if (keys != null && !keys.isEmpty()) {
+ for (String s : keys) {
+ String r = s.substring(0, 1);
+ if (StringUtils.isNumeric(r)) {
+ int j = Integer.parseInt(r);
+ if (i <= j) {
+ i = j;
+ }
+
+ }
+ }
+
+ return i + 1;
+ }
+
+ return 1;
+ }
+
+ private static int computeColumns(Set<String> keys) {
+ int i = 0;
+ if (keys != null && !keys.isEmpty()) {
+ for (String s : keys) {
+ String r = s.substring(1, 2);
+ if (StringUtils.isNumeric(r)) {
+ int j = Integer.parseInt(r);
+ if (i <= j) {
+ i = j;
+ }
+
+ }
+ }
+
+ return i + 1;
+ }
+
+ return 1;
+ }
+
+ private static Container fetchContainerObject(String id, String name, boolean isInner, String logicalGroupName,
+ String domain) {
+ Map<String, Element> containerElementsMap = new HashMap<String, Element>();
+
+ containerElementsMap = fetchElementsMapForContainer(name, isInner, logicalGroupName, domain);
+ int rows = 1;
+ int columns = 1;
+
+ if (isInner) {
+
+ if (containerElementsMap != null && !containerElementsMap.isEmpty()) {
+ rows = computeRows(containerElementsMap.keySet());
+ columns = computeColumns(containerElementsMap.keySet());
+ }
+
+ Container thisContainer = new Container(id, name, rows, columns, 1, 4, 8, 12, 1, 2);
+ thisContainer.setElements(containerElementsMap);
+ // thisContainer.setVisibilityType("");
+
+ return thisContainer;
+ } else {
+ Map<String, Container> innerContainersMap = fetchInnerContainersMapForOuter(name, isInner, logicalGroupName,
+ domain);
+
+ if (innerContainersMap != null && !innerContainersMap.isEmpty()) {
+ if (containerElementsMap != null && !containerElementsMap.isEmpty()) {
+ Set<String> keys = new HashSet<String>(innerContainersMap.keySet());
+ keys.addAll(containerElementsMap.keySet());
+ rows = computeRows(keys);
+ columns = computeColumns(keys);
+ } else {
+ rows = computeRows(innerContainersMap.keySet());
+ columns = computeColumns(innerContainersMap.keySet());
+ }
+ } else if (containerElementsMap != null && !containerElementsMap.isEmpty()) {
+ rows = computeRows(containerElementsMap.keySet());
+ columns = computeColumns(containerElementsMap.keySet());
+ }
+
+ Container thisContainer = new Container(id, name, rows, columns, 2, 6, 2, 5, 0, 0);
+ thisContainer.setElements(containerElementsMap);
+ thisContainer.setInnerContainer(innerContainersMap);
+
+ if (containerElementsMap != null && !containerElementsMap.isEmpty()) {
+ for (Element thisElement : containerElementsMap.values()) {
+ if (thisElement.getId() != null
+ ) {
+ thisContainer.setVisibilityType("invisible");
+ }
+ }
+ }
+ return thisContainer;
+ }
+
+ }
+
+ private static Domain fetchDomainObject(String id, String name) {
+ HashMap<String, Container> domainContainersMap = fetchContainersForDomain(name);
+
+ int rows = 1;
+ int columns = 1;
+ if (domainContainersMap != null && !domainContainersMap.isEmpty()) {
+ rows = computeRows(domainContainersMap.keySet());
+ columns = computeColumns(domainContainersMap.keySet());
+ }
+
+ double domainWidth = 11;
+ Domain thisDomain;
+
+ if (domainMap != null && !domainMap.isEmpty()) {
+ int domainsCountSoFar = domainMap.size();
+ switch (domainsCountSoFar) {
+ case 1: {
+ domainWidth = 12.1;
+ break;
+ }
+ case 2: {
+ domainWidth = 13.3;
+ break;
+ }
+ case 3: {
+ domainWidth = 14.5;
+ break;
+ }
+ case 4: {
+ domainWidth = 15.6;
+ break;
+ }
+ default: {
+ domainWidth = 11;
+ break;
+ }
+ }
+
+ for (String domainsKey : new TreeSet<String>(domainMap.keySet())) {
+ Domain eachDomain = domainMap.get(domainsKey);
+ domainWidth += eachDomain.computeSize().getWidth();
+ }
+ thisDomain = new Domain(id, name, 2, 2, domainWidth, 10, 3, rows, columns);
+ } else {
+
+ thisDomain = new Domain(id, name, 2, 1, 11, 10, 3, rows, columns);
+ }
+
+ // Domain thisDomain = new Domain(id, name, 2, 1, leftPosition, 10, 3,
+ // rows, columns);
+ thisDomain.setContainers(domainContainersMap);
+
+ thisDomain.computeConatinerPositions();
+ if (domainContainersMap != null && !domainContainersMap.isEmpty()) {
+ for (Container thisContainer : domainContainersMap.values()) {
+ thisContainer.computeSize();
+ thisContainer.computeElementPositions();
+ Map<String, Element> resultElementMap = thisContainer.elementRowCol;
+ for (String key : resultElementMap.keySet()) {
+ if (resultElementMap.get(key) == null || resultElementMap.get(key).getP() == null) {
+ // System.out.println("culprit " +key);
+ }
+ /*
+ * System.out.println(resultElementMap.get(key).name+" "
+ * +"x:"+resultElementMap.get(key).getP().getX()+","+"y:"+
+ * resultElementMap.get(key).getP().getY()+","+"width:"+
+ * resultElementMap.get(key).computeSize().getWidth()
+ * +","+"height:"+resultElementMap.get(key).computeSize().
+ * getHeight());
+ */
+
+ }
+
+ HashMap<String, Container> innerContainersMap = (HashMap<String, Container>) thisContainer
+ .getContainerRowCol();
+ if (innerContainersMap != null && !innerContainersMap.isEmpty()) {
+ for (Container thisInnerContainer : innerContainersMap.values()) {
+ // thisInnerContainer.computeSize();
+ thisInnerContainer.computeElementPositions();
+ /*
+ * Map<String,Element> resultInnerElementMap =
+ * thisContainer.elementRowCol; for (String key :
+ * resultElementMap.keySet()) { //
+ * System.out.println(resultElementMap.get(key).name+" "
+ * +"x:"+resultElementMap.get(key).getP().getX()+","+
+ * "y:"+
+ * resultElementMap.get(key).getP().getY()+","+"width:"+
+ * resultElementMap.get(key).computeSize().getWidth()
+ * +","+"height:"+resultElementMap.get(key).computeSize(
+ * ).getHeight());
+ *
+ * }
+ */
+ }
+ }
+ }
+ }
+
+ return thisDomain;
+ }
+
+ private static HashMap<String, Container> fetchContainersForDomain(String domain) {
+ HashMap<String, Container> domainContainersMap = new HashMap<String, Container>();
+
+ domainContainersMap = fetchFromOuterContainers(domain);
+
+ return domainContainersMap;
+
+ }
+
+ private static Element fetchElementObject(String id, String name, String imgPath) {
+ String bgColor = "bgColor";
+ String logical_group;
+ String display_longname;
+ String display_shortname;
+ String description;
+ String primary_function;
+ String key_interfaces;
+ String location;
+ String vendor;
+ String vendor_shortname;
+ String enclosingContainer;
+ String borderType;
+ String network_function;
+
+ if (toscaElementsMap.containsKey(name)) {
+
+ if (toscaElementsMap.get(name) != null && toscaElementsMap.get(name) instanceof HashMap) {
+ HashMap<String, Object> toscaElementDetails = (HashMap<String, Object>) toscaElementsMap.get(name);
+
+ for (String detailsKey : toscaElementDetails.keySet()) {
+ if ("properties".equalsIgnoreCase(detailsKey)
+ && toscaElementDetails.get(detailsKey) instanceof HashMap) {
+ HashMap<String, String> elementDetails = (HashMap<String, String>) toscaElementDetails
+ .get(detailsKey);
+
+ if (elementDetails != null) {
+ logical_group = elementDetails.get("logical_group") == null ? ""
+ : elementDetails.get("logical_group").toString();
+ display_longname = elementDetails.get("display_longname") == null ? ""
+ : elementDetails.get("display_longname").toString();
+ display_shortname = elementDetails.get("display_shortname") == null ? ""
+ : elementDetails.get("display_shortname").toString();
+ description = elementDetails.get("description") == null ? ""
+ : elementDetails.get("description").toString();
+ primary_function = elementDetails.get("primary_function") == null ? ""
+ : elementDetails.get("primary_function").toString();
+ key_interfaces = elementDetails.get("key_interfaces") == null ? ""
+ : elementDetails.get("key_interfaces").toString();
+ location = elementDetails.get("location") == null ? ""
+ : elementDetails.get("location").toString();
+ vendor = elementDetails.get("vendor") == null ? ""
+ : elementDetails.get("vendor").toString();
+ vendor_shortname = elementDetails.get("vendor_shortname") == null ? ""
+ : elementDetails.get("vendor_shortname").toString();
+ enclosingContainer = logical_group.replace("/", "-");
+ network_function = elementDetails.get("network_function");
+ borderType = elementDetails.get("network_function") == null ? "P"
+ : elementDetails.get("network_function").toString().toUpperCase();
+ bgColor = elementDetails.get("background_color") == null ? "bgColor"
+ : elementDetails.get("background_color").toString();
+
+ ElementDetails details = new ElementDetails(logical_group, display_longname, description,
+ primary_function, network_function, key_interfaces, location, vendor,
+ vendor_shortname, enclosingContainer);
+
+ return new Element(name, display_shortname, imgPath, bgColor, borderType, details);
+ }
+
+ }
+ }
+
+ }
+
+ // Element(id, name, imgPath, bgColor, logical_group,
+ // display_longname,
+ // description, primary_function, key_interfaces, location, vendor,
+ // vendor_shortname);
+ } else {
+ return new Element(id, name);
+ }
+
+ return new Element(id, name);
+ }
+
+ private static String fetchDomainNameOfElement(String name) {
+ if (toscaElementsMap.containsKey(name)) {
+
+ if (toscaElementsMap.get(name) != null && toscaElementsMap.get(name) instanceof HashMap) {
+ HashMap<String, Object> toscaElementDetails = (HashMap<String, Object>) toscaElementsMap.get(name);
+
+ for (String detailsKey : toscaElementDetails.keySet()) {
+ if ("properties".equalsIgnoreCase(detailsKey)
+ && toscaElementDetails.get(detailsKey) instanceof HashMap) {
+ HashMap<String, String> elementDetails = (HashMap<String, String>) toscaElementDetails
+ .get(detailsKey);
+
+ if (elementDetails != null) {
+ return elementDetails.get("domain") == null ? "" : elementDetails.get("domain").toString();
+ }
+
+ }
+ }
+
+ }
+
+ } else {
+ return "";
+ }
+
+ return "";
+ }
+
+ private static HashMap<String, Container> fetchInnerContainersMapForOuter(String name, boolean isInner,
+ String logicalGroupName, String domain) {
+ return fetchInnerContainersMap(name, logicalGroupName, domain);
+ }
+
+ private static HashMap<String, Element> fetchElementsMapForContainer(String name, boolean isInner,
+ String logicalGroupName, String domain) {
+ return fetchElementsMap(logicalGroupName, domain);
+ }
+
+ private static HashMap<String, Container> fetchInnerContainersMap(String name, String logicalGroupName,
+ String domain) {
+ HashMap<String, Container> containersMap = new HashMap<String, Container>();
+ String rowColumnKey = "";
+ int count = 0;
+
+ if (innercontainers != null && !innercontainers.isEmpty()) {
+ for (String key : innercontainers.keySet()) {
+
+ Container eachContainer = innercontainers.get(key);
+
+ if (key.toUpperCase().contains((domain + ":" + name).toUpperCase())) {
+ if (key.contains("/")) {
+ rowColumnKey = key.substring(key.lastIndexOf("/") + 1);
+ }
+
+ if (rowColumnKey.isEmpty() || containersMap.containsKey(rowColumnKey)) {
+ count = 0;
+ while (count <= 9) {
+ if (containersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) {
+ count++;
+ } else {
+ rowColumnKey = String.valueOf(count).concat(String.valueOf(count));
+ break;
+ }
+ }
+
+ }
+
+ containersMap.put(rowColumnKey, eachContainer);
+ }
+
+ }
+ }
+ return containersMap.isEmpty() ? null : containersMap;
+
+ }
+
+ private static HashMap<String, Container> fetchFromOuterContainers(String domain) {
+ HashMap<String, Container> thisContainersMap = new HashMap<String, Container>();
+ String rowColumnKey = "";
+ int count = 0;
+
+ if (outercontainers != null && !outercontainers.isEmpty()) {
+ for (String key : outercontainers.keySet()) {
+ Container eachContainer = outercontainers.get(key);
+
+ if (key.toUpperCase().contains((domain + ":").toUpperCase())) {
+ if (key.contains("/")) {
+ rowColumnKey = key.substring(key.lastIndexOf("/") + 1);
+ }
+
+ if (rowColumnKey.isEmpty() || thisContainersMap.containsKey(rowColumnKey)) {
+ count = 0;
+ while (count <= 9) {
+ if (thisContainersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) {
+ count++;
+ } else {
+ rowColumnKey = String.valueOf(count).concat(String.valueOf(count));
+ break;
+ }
+ }
+
+ }
+
+ thisContainersMap.put(rowColumnKey, eachContainer);
+ }
+ }
+
+ }
+
+ // Misc Elements Containers
+
+ if (miscElementMap != null && !miscElementMap.isEmpty()) {
+ for (String key : miscElementMap.keySet()) {
+ Element eachElement = miscElementMap.get(key);
+ String elementName = eachElement.getName();
+ String domainName = fetchDomainNameOfElement(elementName);
+
+ if (domain.equalsIgnoreCase(domainName)) {
+ Container eachContainer = new Container(domainName + ":" + elementName, elementName, 1, 1, 3, 6, 2,
+ 5, 0, 0);
+ count = 0;
+ while (count <= 9) {
+ if (thisContainersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) {
+ count++;
+ } else {
+ rowColumnKey = String.valueOf(count).concat(String.valueOf(count));
+ break;
+ }
+ }
+
+ thisContainersMap.put(rowColumnKey, eachContainer);
+ }
+
+ }
+
+ }
+
+ return thisContainersMap.isEmpty() ? null : thisContainersMap;
+ }
+
+ private static HashMap<String, Container> addOuterContainersForMiscElements(String domain) {
+ HashMap<String, Container> containerElementsMap = new HashMap<String, Container>();
+ if (miscElementMap != null && !miscElementMap.isEmpty()) {
+ for (String key : miscElementMap.keySet()) {
+ Element eachElement = miscElementMap.get(key);
+ String elementName = eachElement.getName();
+ String domainName = fetchDomainNameOfElement(elementName);
+
+ if (domain.equalsIgnoreCase(domainName)) {
+ Container newContainer = new Container(domainName + ":" + elementName, elementName, 1, 1, 3, 6, 2,
+ 5, 0, 0);
+ containerElementsMap.put(domainName + ":" + elementName, newContainer);
+ }
+
+ }
+
+ }
+ return containerElementsMap.isEmpty() ? null : containerElementsMap;
+ }
+
+ private static HashMap<String, Element> fetchElementsMap(String logicalGroupName, String domain) {
+ HashMap<String, Element> innerElementMap = new HashMap<String, Element>();
+ String rowColumnKey = "";
+ int count = 0;
+
+ if (elementMap != null && !elementMap.isEmpty()) {
+ for (String key : elementMap.keySet()) {
+ Element eachElement = elementMap.get(key);
+
+ String elementName = eachElement.getId();
+ String elementLogicalGroup = eachElement.details == null ? "" : eachElement.details.logical_group;
+ if (elementLogicalGroup.equalsIgnoreCase(logicalGroupName)
+ && domain.equalsIgnoreCase(fetchDomainNameOfElement(elementName))) {
+ if (key.contains("/")) {
+ rowColumnKey = key.substring(key.indexOf("/") + 1);
+ }
+
+ if (rowColumnKey.isEmpty() || innerElementMap.containsKey(rowColumnKey)) {
+ count = 0;
+ while (count <= 9) {
+ if (innerElementMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) {
+ count++;
+ } else {
+ rowColumnKey = String.valueOf(count).concat(String.valueOf(count));
+ break;
+ }
+ }
+
+ }
+
+ innerElementMap.put(rowColumnKey, eachElement);
+ miscElementMap.remove(key);
+ }
+
+ }
+ }
+
+ return innerElementMap.isEmpty() ? null : innerElementMap;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.List;
+import java.util.Set;
+
+import org.onap.portalsdk.core.domain.Menu;
+import org.onap.portalsdk.core.domain.MenuData;
+
+/**
+ * Defines services for admin user to add/edit/delete menu items from FN_MENU.
+ */
+public interface FnMenuService {
+ List<MenuData> getFnMenuItems();
+
+ void saveFnMenuData(MenuData domainFnMenu);
+
+ void saveFnMenu(Menu domainFnMenu);
+
+ void removeMenuItem(MenuData domainFnMenu);
+
+ MenuData getMenuItemRow(Long id);
+
+ Menu getMenuItem(Long id);
+
+ List<Long> getParentId(String label);
+
+ @SuppressWarnings("rawtypes")
+ List<List> getParentList();
+
+ void removeMenuItem(Menu domainFnMenu);
+
+ void setMenuDataStructure(List<List<MenuData>> childItemList, List<MenuData> parentList, Set<MenuData> menuResult);
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.onap.portalsdk.core.domain.Menu;
+import org.onap.portalsdk.core.domain.MenuData;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("fnMenuService")
+@Transactional
+public class FnMenuServiceImpl implements FnMenuService {
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @SuppressWarnings("unchecked")
+ public List<MenuData> getFnMenuItems() {
+ return getDataAccessService().getList(MenuData.class, null, "1", null);
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ @Override
+ public void saveFnMenuData(MenuData domainFnMenu) {
+ getDataAccessService().saveDomainObject(domainFnMenu, null);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<Long> getParentId(String label) {
+ Map<String, String> params = new HashMap<String, String>();
+ params.put("paramLabel", label);
+ return getDataAccessService().executeNamedQuery("IdForLabelList", params, null);
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @Override
+ public List<List> getParentList() {
+ return getDataAccessService().executeNamedQuery("parentList", null, null);
+ }
+
+ @Override
+ public void removeMenuItem(MenuData domainFnMenu) {
+ getDataAccessService().deleteDomainObject(domainFnMenu, null);
+ }
+
+ @Override
+ public void removeMenuItem(Menu domainFnMenu) {
+ getDataAccessService().deleteDomainObject(domainFnMenu, null);
+ }
+
+ public MenuData getMenuItemRow(Long id) {
+ return (MenuData) getDataAccessService().getDomainObject(MenuData.class, id, null);
+ }
+
+ @Override
+ public Menu getMenuItem(Long id) {
+ return (Menu) getDataAccessService().getDomainObject(Menu.class, id, null);
+ }
+
+ @Override
+ public void saveFnMenu(Menu domainFnMenu) {
+ getDataAccessService().saveDomainObject(domainFnMenu, null);
+ }
+
+ @Override
+ public void setMenuDataStructure(List<List<MenuData>> childItemList, List<MenuData> parentList,
+ Set<MenuData> menuResult) {
+ for (MenuData menu : menuResult) {
+ MenuData parentData = new MenuData();
+ parentData.setLabel(menu.getLabel());
+ parentData.setAction(menu.getAction());
+ parentData.setImageSrc(menu.getImageSrc());
+ parentList.add(parentData);
+ List<MenuData> tempList = new ArrayList<MenuData>();
+ for (Object o : menu.getChildMenus()) {
+ MenuData m = (MenuData) o;
+ MenuData data = new MenuData();
+ data.setLabel(m.getLabel());
+ data.setAction(m.getAction());
+ data.setImageSrc(m.getImageSrc());
+ tempList.add(data);
+ }
+ childItemList.add(tempList);
+ }
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.io.IOException;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.domain.RoleFunction;
+
+public interface FunctionalMenuListService {
+
+ List<RoleFunction> getFunctionCDList(HttpServletRequest request) throws IOException;
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.io.IOException;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.domain.RoleFunction;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+
+public class FunctionalMenuListServiceCentralizedImpl implements FunctionalMenuListService{
+
+ @Autowired
+ private RestApiRequestBuilder restApiRequestBuilder;
+
+ @Override
+ public List<RoleFunction> getFunctionCDList(HttpServletRequest request) throws IOException {
+ User user = UserUtils.getUserSession(request);
+ ObjectMapper mapper = new ObjectMapper();
+ String menuList = restApiRequestBuilder.getViaREST("/menuFunctions", true, user.getOrgUserId());
+ List<RoleFunction> roleFunctionFinalList = mapper.readValue(menuList,
+ TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
+ return roleFunctionFinalList;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.io.IOException;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.domain.RoleFunction;
+import org.springframework.beans.factory.annotation.Autowired;
+
+public class FunctionalMenuListServiceImpl implements FunctionalMenuListService{
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<RoleFunction> getFunctionCDList(HttpServletRequest request) throws IOException {
+ return getDataAccessService().executeNamedQuery("functionCDlist", null, null);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import org.onap.portalsdk.core.command.support.SearchResult;
+import org.onap.portalsdk.core.domain.support.DomainVo;
+
+
+public interface LdapService {
+
+ // search POST for users based on the criteria selected in the Request
+ SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, int pageNo, int dataSize, int userId) throws Exception;
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.SearchControls;
+
+import org.onap.portalsdk.core.command.support.SearchResult;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.domain.support.DomainVo;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.support.FusionService;
+import org.onap.portalsdk.core.service.support.ServiceLocator;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("ldapService")
+@Transactional
+public class LdapServiceImpl extends FusionService implements LdapService {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LdapServiceImpl.class);
+
+ @Autowired
+ private ServiceLocator serviceLocator;
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3,
+ int pageNo, int dataSize, int userId) throws Exception {
+
+ // initialize the directory context to access POST
+ DirContext dirContext = serviceLocator.getDirContext(SystemProperties.getProperty(SystemProperties.POST_INITIAL_CONTEXT_FACTORY),
+ SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL),
+ SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL));
+
+ SearchResult searchResult = new SearchResult();
+
+ try {
+
+ String[] postAttributes = {"nickname","givenName","initials","sn","employeeNumber","mail","telephoneNumber",
+ "departmentNumber","a1","street","roomNumber","l","st","postalCode","zip4","physicalDeliveryOfficeName","bc",
+ "friendlyCountryName","bd","bdname","bu","buname","jtname","mgrid","a2","compcode","compdesc",
+ "costcenter","silo","b2"};
+
+ SearchControls searchControls = new SearchControls();
+ searchControls.setTimeLimit(5000);
+ searchControls.setReturningAttributes(postAttributes);
+
+ StringBuffer filterClause = new StringBuffer("(&(objectClass=*)");
+
+ User user = (User)searchCriteria;
+
+ if(Utilities.nvl(user.getFirstName()).length() > 0) {
+ filterClause.append("(givenName=").append(user.getFirstName()).append("*)");
+ }
+ if(Utilities.nvl(user.getLastName()).length() > 0) {
+ filterClause.append("(sn=").append(user.getLastName()).append("*)");
+ }
+ if(Utilities.nvl(user.getHrid()).length() > 0) {
+ filterClause.append("(employeeNumber=").append(user.getHrid()).append("*)");
+ }
+ if(Utilities.nvl(user.getOrgManagerUserId()).length() > 0) {
+ filterClause.append("(mgrid=").append(user.getOrgManagerUserId()).append("*)");
+ }
+ if(Utilities.nvl(user.getOrgCode()).length() > 0) {
+ filterClause.append("(departmentNumber=").append(user.getOrgCode()).append("*)");
+ }
+ if(Utilities.nvl(user.getEmail()).length() > 0) {
+ filterClause.append("(mail=").append(user.getEmail()).append("*)");
+ }
+ if(Utilities.nvl(user.getOrgUserId()).length() > 0) {
+ filterClause.append("(a1=").append(user.getOrgUserId()).append("*)");
+ }
+ filterClause.append("(c3=N)"); // this has been added to filter CP09 entries on the LDAP server that are duplicates of existing individuals
+ filterClause.append(")");
+
+ List list = new ArrayList();
+ if (!filterClause.toString().equals("(&(objectClass=*))")) {
+ NamingEnumeration e = dirContext.search(SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL) + "/" +
+ SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL),
+ filterClause.toString(),
+ searchControls);
+
+ list = processResults(e);
+ }
+
+ Collections.sort(list);
+
+ searchResult = new SearchResult(list);
+ searchResult.setPageNo(pageNo);
+ if(dataSize >= 0) {
+ searchResult.setDataSize(dataSize);
+ }
+ else {
+ searchResult.setDataSize(list.size());
+ } // else
+
+ }
+ catch(NamingException ne) {
+ logger.error(EELFLoggerDelegate.errorLogger,ne.getMessage());
+ }
+ finally {
+ dirContext.close();
+ }
+
+ return searchResult;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private ArrayList processResults(NamingEnumeration e) throws NamingException {
+ ArrayList results = new ArrayList();
+ int count = 0;
+
+ while (e.hasMore()) {
+ javax.naming.directory.SearchResult searchResult = (javax.naming.directory.SearchResult)e.next();
+ results.add(processAttributes(searchResult.getAttributes()));
+ count++;
+
+ if(count > Integer.parseInt(SystemProperties.getProperty(SystemProperties.POST_MAX_RESULT_SIZE))) {
+ break;
+ }
+
+ }
+
+ return results;
+ }
+
+ @SuppressWarnings("rawtypes")
+ private DomainVo processAttributes(Attributes resultAttributes) throws NamingException {
+ User user = new User();
+
+ try {
+ if (resultAttributes == null) {
+ // System.out.println("This result has no attributes");
+ } else {
+ for (NamingEnumeration e = resultAttributes.getAll(); e.hasMore();) { //why the nested loop?
+ Attribute attribute = (Attribute)e.next();
+ for (NamingEnumeration ie = attribute.getAll(); ie.hasMore();) {
+ if (attribute.getID().equalsIgnoreCase("nickname")) {
+ user.setFirstName((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("initials")) {
+ user.setMiddleInitial((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("sn")) {
+ user.setLastName((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("employeeNumber")) {
+ user.setHrid((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("mail")) {
+ user.setEmail((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("telephoneNumber")) {
+ user.setPhone((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("departmentNumber")) {
+ user.setOrgCode((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("a1")) {
+ user.setOrgUserId((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("street")) {
+ user.setAddress1((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("roomNumber")) {
+ user.setAddress2((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("l")) {
+ user.setCity((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("st")) {
+ user.setState((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("postalCode")) {
+ user.setZipCode((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("zip4")) {
+ user.setZipCodeSuffix((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("physicalDeliveryOfficeName")) {
+ user.setLocationClli((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("bc")) {
+ user.setBusinessCountryCode((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("friendlyCountryName")) {
+ user.setBusinessCountryName((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("bd")) {
+ user.setDepartment((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("bdname")) {
+ user.setDepartmentName((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("jtname")) {
+ user.setJobTitle((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("mgrid")) {
+ user.setOrgManagerUserId((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("a2")) {
+ user.setCommandChain((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("compcode")) {
+ user.setCompanyCode((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("compdesc")) {
+ user.setCompany((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("bu")) {
+ user.setBusinessUnit((String)ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("buname")) {
+ user.setBusinessUnitName((String)ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("silo")) {
+ user.setSiloStatus((String)ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("costcenter")) {
+ user.setCostCenter((String)ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("b2")) {
+ user.setFinancialLocCode((String)ie.next());
+ }
+ else { //we don't care about returned attribute, let's move on
+ ie.next();
+ }
+
+ }
+ }
+ }
+ } catch (NamingException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "An error occurred while processing the following user from POST with an ORGUSERID of " + user.getOrgUserId() + e.getMessage());
+ }
+
+ return user;
+
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+import org.springframework.context.annotation.Condition;
+import org.springframework.context.annotation.ConditionContext;
+import org.springframework.core.type.AnnotatedTypeMetadata;
+
+public class LocalAccessCondition implements Condition{
+
+ /**
+ * returns true if the application is not centralized
+ */
+ @Override
+ public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
+ return PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) == null || (PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) != null && ! PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED).equals("remote"));
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+
+import java.util.*;
+
+import org.onap.portalsdk.core.command.*;
+
+
+public interface LoginService {
+
+ /**
+ *
+ * @param bean
+ * @param menuPropertiesFilename
+ * @param additionalParams
+ * @return returns login user bean
+ * @throws Exception
+ */
+ // validate user exists in the system
+ @SuppressWarnings("rawtypes")
+ LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams) throws Exception;
+
+
+ /**
+ *
+ * @param bean
+ * @param menuPropertiesFilename
+ * @param additionalParams
+ * @param matchPassword
+ * @return returns login user bean
+ * @throws Exception
+ */
+ @SuppressWarnings("rawtypes")
+ LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception;
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.onap.portalsdk.core.command.LoginBean;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.menu.MenuBuilder;
+import org.onap.portalsdk.core.service.support.FusionService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.AppUtils;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.annotation.Transactional;
+
+
+@Transactional
+public class LoginServiceCentralizedImpl extends FusionService implements LoginService {
+
+ @Autowired
+ private AppService appService;
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @Autowired
+ private RestApiRequestBuilder restApiRequestBuilder;
+
+ @Autowired
+ private UserService userService;
+
+ @SuppressWarnings("unused")
+ private MenuBuilder menuBuilder;
+
+ @Override
+ public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams)
+ throws Exception {
+ return findUser(bean, menuPropertiesFilename, additionalParams, true);
+ }
+
+ @SuppressWarnings("rawtypes")
+ public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams,
+ boolean matchPassword) throws Exception {
+ User user = null;
+ User userCopy = null;
+
+ if (bean.getUserid() != null && bean.getUserid() != null) {
+ user = (User) findUser(bean);
+ } else {
+ if (matchPassword)
+ user = (User) findUser(bean.getLoginId(), bean.getLoginPwd());
+ else
+ user = (User) findUserWithoutPwd(bean.getLoginId());
+ }
+
+ if (user != null) {
+
+ if (AppUtils.isApplicationLocked()
+ && !UserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) {
+ bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED);
+ }
+
+ // raise an error if the user is inactive
+ if (!user.getActive()) {
+ bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
+ }
+
+ if (!userHasActiveRoles(user)) {
+ bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
+ }
+ // only login the user if no errors have occurred
+ if (bean.getLoginErrorMessage() == null) {
+
+ // this will be a snapshot of the user's information as
+ // retrieved from the database
+ userCopy = (User) user.clone();
+
+ User appuser = getUser(userCopy);
+
+ appuser.setLastLoginDate(new Date());
+
+ // update the last logged in date for the user
+ // user.setLastLoginDate(new Date());
+ getDataAccessService().saveDomainObject(appuser, additionalParams);
+
+ // update the audit log of the user
+ // Check for the client device type and set log attributes
+ // appropriately
+
+ // save the above changes to the User and their audit trail
+
+ // create the application menu based on the user's privileges
+
+ Set appMenu = getMenuBuilder().getMenu(
+ SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME), dataAccessService);
+ bean.setMenu(appMenu != null ? appMenu : new HashSet());
+ Set businessDirectMenu = getMenuBuilder().getMenu(
+ SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_SET_NAME),
+ dataAccessService);
+ bean.setBusinessDirectMenu(businessDirectMenu != null ? businessDirectMenu : new HashSet());
+
+ bean.setUser(userCopy);
+ }
+ }
+
+ return bean;
+ }
+
+ private boolean userHasActiveRoles(User user) {
+ boolean hasActiveRole = false;
+ Iterator roles = user.getRoles().iterator();
+ while (roles.hasNext()) {
+ Role role = (Role) roles.next();
+ if (role.getActive()) {
+ hasActiveRole = true;
+ break;
+ }
+ }
+ return hasActiveRole;
+ }
+
+ @SuppressWarnings("null")
+ public User findUser(LoginBean bean) throws Exception {
+ User user = null;
+ String repsonse = restApiRequestBuilder.getViaREST("/user/" + bean.getUserid(), true, bean.getUserid());
+ user = userService.userMapper(repsonse);
+ user.setId(getUserIdByOrgUserId(user.getOrgUserId()));
+ return user;
+ }
+
+ public Long getUserIdByOrgUserId(String orgUserId) {
+ Map<String, String> params = new HashMap<String, String>();
+ params.put("orgUserId", orgUserId);
+ @SuppressWarnings("rawtypes")
+ List list = getDataAccessService().executeNamedQuery("getUserIdByorgUserId", params, null);
+ Long userId = null;
+ if (list != null && !list.isEmpty())
+ userId = (Long) list.get(0);
+ return userId;
+ }
+
+
+ public User findUser(String loginId, String password) {
+
+ List list = null;
+
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where login_id = '").append(loginId).append("'").append(" and login_pwd = '").append(password)
+ .append("'");
+
+ list = getDataAccessService().getList(User.class, criteria.toString(), null, null);
+ return (list == null || list.size() == 0) ? null : (User) list.get(0);
+ }
+
+ private User findUserWithoutPwd(String loginId) {
+ List list = null;
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where login_id = '").append(loginId).append("'");
+ list = getDataAccessService().getList(User.class, criteria.toString(), null, null);
+ return (list == null || list.size() == 0) ? null : (User) list.get(0);
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ public MenuBuilder getMenuBuilder() {
+ return new MenuBuilder();
+ }
+
+ public void setMenuBuilder(MenuBuilder menuBuilder) {
+ this.menuBuilder = menuBuilder;
+ }
+
+ public User getUser(User user) {
+ List list = null;
+
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where login_id = '").append(user.getLoginId()).append("'");
+
+ list = getDataAccessService().getList(User.class, criteria.toString(), null, null);
+ return (list == null || list.size() == 0) ? null : (User) list.get(0);
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.onap.portalsdk.core.command.LoginBean;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.menu.MenuBuilder;
+import org.onap.portalsdk.core.service.support.FusionService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.AppUtils;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.annotation.Transactional;
+
+@Transactional
+public class LoginServiceImpl extends FusionService implements LoginService {
+
+ @SuppressWarnings("unused")
+ private MenuBuilder menuBuilder;
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @SuppressWarnings("rawtypes")
+ public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams ) throws Exception {
+ return findUser(bean, menuPropertiesFilename, additionalParams, true);
+ }
+
+ @SuppressWarnings("rawtypes")
+ public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception {
+ User user = null;
+ User userCopy = null;
+
+ if (bean.getUserid() != null && bean.getUserid() != null) {
+ user = (User)findUser(bean);
+ }
+ else {
+ if (matchPassword)
+ user = (User)findUser(bean.getLoginId(), bean.getLoginPwd());
+ else
+ user = (User)findUserWithoutPwd(bean.getLoginId());
+ }
+
+ if (user != null) {
+
+ // raise an error if the application is locked and the user does not have system administrator privileges
+ if (AppUtils.isApplicationLocked() && !UserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) {
+ bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED);
+ }
+
+ // raise an error if the user is inactive
+ if (!user.getActive()) {
+ bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
+ }
+
+ // raise an error if no active roles exist for the user
+// boolean hasActiveRole = false;
+// Iterator roles = user.getRoles().iterator();
+// while (roles.hasNext()) {
+// Role role = (Role)roles.next();
+// if (role.getActive()) {
+// hasActiveRole = true;
+// break;
+// }
+// }
+
+// if (!hasActiveRole) {
+// bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
+// }
+ if (!userHasActiveRoles(user)) {
+ bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
+ }
+ // only login the user if no errors have occurred
+ if (bean.getLoginErrorMessage() == null) {
+
+ // this will be a snapshot of the user's information as retrieved from the database
+ userCopy = (User)user.clone();
+
+ // update the last logged in date for the user
+ user.setLastLoginDate(new Date());
+ getDataAccessService().saveDomainObject(user, additionalParams);
+
+ // update the audit log of the user
+ //Check for the client device type and set log attributes appropriately
+
+
+ // save the above changes to the User and their audit trail
+
+ // create the application menu based on the user's privileges
+ Set appMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME),dataAccessService);
+ bean.setMenu(appMenu != null?appMenu:new HashSet());
+ Set businessDirectMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_SET_NAME),dataAccessService);
+ bean.setBusinessDirectMenu(businessDirectMenu != null?businessDirectMenu:new HashSet());
+
+ bean.setUser(userCopy);
+ }
+
+ }
+
+ return bean;
+ }
+
+ private boolean userHasActiveRoles(User user) {
+ boolean hasActiveRole = false;
+ @SuppressWarnings("rawtypes")
+ Iterator roles = user.getRoles().iterator();
+ while (roles.hasNext()) {
+ Role role = (Role)roles.next();
+ if (role.getActive()) {
+ hasActiveRole = true;
+ break;
+ }
+ }
+ return hasActiveRole;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public User findUser(String loginId, String password) {
+ List list = null;
+
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where login_id = '").append(loginId).append("'")
+ .append(" and login_pwd = '").append(password).append("'");
+
+ list = getDataAccessService().getList(User.class, criteria.toString(), null, null);
+
+ return (list == null || list.size() == 0) ? null : (User)list.get(0);
+ }
+
+ @SuppressWarnings("rawtypes")
+ private User findUserWithoutPwd(String loginId) {
+ List list = null;
+
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where login_id = '").append(loginId).append("'");
+
+ list = getDataAccessService().getList(User.class, criteria.toString(), null, null);
+
+ return (list == null || list.size() == 0) ? null : (User)list.get(0);
+ }
+
+ @SuppressWarnings("rawtypes")
+ public User findUser(LoginBean bean) {
+ List list = null;
+
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where org_user_id = '").append(bean.getUserid()).append("'");
+
+ list = getDataAccessService().getList(User.class, criteria.toString(), null, null);
+
+ return (list == null || list.size() == 0) ? null : (User)list.get(0);
+ }
+
+
+ public MenuBuilder getMenuBuilder() {
+ return new MenuBuilder();
+ }
+
+
+ public void setMenuBuilder(MenuBuilder menuBuilder) {
+ this.menuBuilder = menuBuilder;
+ }
+
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.List;
+
+import org.onap.portalsdk.core.command.PostDroolsBean;
+
+public interface PostDroolsService {
+
+ String execute(String droolsFile, String className, String selectedRules);
+
+ List<PostDroolsBean> fetchDroolBeans();
+
+ String retrieveClass(String droolsFile);
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.DirectoryIteratorException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.kie.api.io.ResourceType;
+import org.kie.internal.KnowledgeBase;
+import org.kie.internal.KnowledgeBaseFactory;
+import org.kie.internal.builder.KnowledgeBuilder;
+import org.kie.internal.builder.KnowledgeBuilderFactory;
+import org.kie.internal.definition.KnowledgePackage;
+import org.kie.internal.io.ResourceFactory;
+import org.kie.internal.runtime.StatefulKnowledgeSession;
+import org.onap.portalsdk.core.command.PostDroolsBean;
+import org.onap.portalsdk.core.drools.DroolsRuleService;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * TODO REFACTOR
+ *
+ */
+@Service("postDroolsService")
+@Transactional
+public class PostDroolsServiceImpl implements PostDroolsService{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostDroolsServiceImpl.class);
+
+ @Override
+ public String execute(String droolsFile, String className, String selectedRules) {
+ logger.info(EELFLoggerDelegate.applicationLogger, "Executing Drools...");
+ String resultsString = executeDemoRules(droolsFile, className, selectedRules);
+ return resultsString;
+ }
+
+
+ public List<PostDroolsBean> fetchDroolBeans() {
+
+ List<PostDroolsBean> beanList = new ArrayList<PostDroolsBean>();
+ Path path = FileSystems.getDefault().getPath(SystemProperties.getProperty(SystemProperties.FILES_PATH));
+ try (DirectoryStream<Path> stream = Files.newDirectoryStream(path,"*.{drl}")) {
+ for (Path entry: stream) {
+
+ PostDroolsBean postDroolsBean = new PostDroolsBean();
+ String fileName = entry.getName(entry.getNameCount()-1).toString();
+ postDroolsBean.setDroolsFile(fileName);//sample populated
+ postDroolsBean.setClassName(retrieveClass(fileName));
+ //postDroolsBean.setSelectedRules("[\"NJ\",\"NY\",\"KY\"]");
+ beanList.add(postDroolsBean);
+ }
+ } catch (DirectoryIteratorException ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage());
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
+ }
+ return beanList;
+ }
+
+ @Override
+ public String retrieveClass(String fileName) {
+ String resultsString = "";
+ try {
+ // load up the knowledge base
+ final KnowledgeBuilder kbuilder = loadKBuilder(fileName);
+ final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
+ return pkgs.iterator().next().getFactTypes().iterator().next().getFactClass().getName();
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "retrieveClass failed", e);
+ }
+
+ return resultsString;
+ }
+
+ protected static KnowledgeBuilder loadKBuilder(String fileName) {
+ final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
+
+ // this will parse and compile in one step
+ kbuilder.add(ResourceFactory.newFileResource(SystemProperties.getProperty(SystemProperties.FILES_PATH) + File.separator + fileName),
+ //kbuilder.add(ResourceFactory.newClassPathResource(SystemProperties.getProperty(SystemProperties.FILES_PATH) + File.separator + drl_file_path, DroolsRuleService.class),
+ ResourceType.DRL);
+ // kbuilder.add(ResourceFactory.newClassPathResource("rules.drl",DroolsRuleService.class),
+ // ResourceType.DRL);
+
+ // Check the builder for errors
+ if (kbuilder.hasErrors()) {
+
+ logger.error(EELFLoggerDelegate.errorLogger, kbuilder.getErrors().toString());
+
+ throw new RuntimeException("Unable to compile \".drl\".");
+
+ }
+ return kbuilder;
+ }
+
+
+ @SuppressWarnings({ "deprecation", "unchecked" })
+ public static String executeDemoRules(String fileName, String className, String ruleValue) {
+ String resultsString = "";
+ try {
+ // load up the knowledge base
+ // KieServices ks = KieServices.Factory.get();
+ // KieContainer kContainer = ks.getKieClasspathContainer();
+ // KieSession kSession = kContainer.newKieSession("ksession-rules");
+
+ final KnowledgeBuilder kbuilder = loadKBuilder(fileName);
+
+ // get the compiled packages (which are serializable)
+
+ final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
+
+ // add the packages to a knowledgebase (deploy the knowledge
+ // packages).
+
+ final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
+
+ kbase.addKnowledgePackages(pkgs);
+
+ final StatefulKnowledgeSession kSession = kbase.newStatefulKnowledgeSession();
+
+ ObjectMapper mapper = new ObjectMapper();
+ if(ruleValue == null || ruleValue.equals("")) {
+ resultsString = "Please enter valid rule";
+ return resultsString;
+ }
+ List<String> selectedRules = mapper.readValue(ruleValue, List.class);
+ List<String> ruleResponse = new ArrayList<String>();
+
+ for(String rule : selectedRules){
+ Class<DroolsRuleService> clazz = (Class<DroolsRuleService>) Class.forName(className);
+ DroolsRuleService droolsIntroduction =clazz.newInstance();
+ droolsIntroduction.init(rule);
+ kSession.insert(droolsIntroduction);
+ kSession.fireAllRules();
+ ruleResponse.add(droolsIntroduction.getResultsString());
+ }
+
+ resultsString = mapper.writeValueAsString(ruleResponse);
+
+// kSession.insert(new DroolsRuleService("KY"));
+// kSession.fireAllRules();
+//
+// kSession.setGlobal("age", "25");
+// kSession.insert(new DroolsRuleService("NY"));
+// kSession.fireAllRules();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "executeDemoRules failed", e);
+ }
+
+ return resultsString;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.command.PostSearchBean;
+
+public interface PostSearchService {
+
+ /**
+ * Imports the selected users in the search results as new users.
+ *
+ * @param request
+ * @param postSearch
+ * @return the number of users successfully imported
+ */
+ int process(HttpServletRequest request, PostSearchBean postSearch);
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.FusionObject.Parameters;
+import org.onap.portalsdk.core.command.PostSearchBean;
+import org.onap.portalsdk.core.domain.Lookup;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("postSearchService")
+@Transactional
+public class PostSearchServiceImpl implements PostSearchService {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostSearchServiceImpl.class);
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @Override
+ public int process(HttpServletRequest request, PostSearchBean postSearch) {
+ HashMap additionalParams = new HashMap();
+ additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request);
+ int numUsersImported = 0;
+
+ if (postSearch.getSelected() != null) {
+ // sort the selected users for quick validation
+
+ Arrays.sort(postSearch.getSelected());
+ // import the users that have been selected
+ for (int i = 0; i < postSearch.getPostOrgUserId().length; i++) {
+ if (Arrays.binarySearch(postSearch.getSelected(), postSearch.getPostOrgUserId()[i]) >= 0) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "Adding ORGUSERID - " + postSearch.getPostOrgUserId()[i]);
+ logger.debug(EELFLoggerDelegate.auditLogger,
+ "Import new user from webphone " + postSearch.getPostOrgUserId()[i]);
+
+ User user = new User();
+ user.setLastName(postSearch.getPostLastName()[i]);
+ user.setFirstName(postSearch.getPostFirstName()[i]);
+
+ if (postSearch.getPostHrid() != null && postSearch.getPostHrid().length > 0) {
+ user.setHrid(postSearch.getPostHrid()[i]);
+ }
+
+ if (postSearch.getPostPhone() != null && postSearch.getPostPhone().length > 0) {
+ user.setPhone(postSearch.getPostPhone()[i]);
+ }
+
+ if (postSearch.getPostEmail() != null && postSearch.getPostEmail().length > 0) {
+ user.setEmail(postSearch.getPostEmail()[i]);
+ }
+
+ if (postSearch.getPostOrgUserId() != null && postSearch.getPostOrgUserId().length > 0) {
+ user.setOrgUserId(postSearch.getPostOrgUserId()[i]);
+ user.setLoginId(postSearch.getPostOrgUserId()[i]);
+ }
+
+ if (postSearch.getPostAddress1() != null && postSearch.getPostAddress1().length > 0) {
+ user.setAddress1(postSearch.getPostAddress1()[i]);
+ }
+
+ if (postSearch.getPostAddress2() != null && postSearch.getPostAddress2().length > 0) {
+ user.setAddress2(postSearch.getPostAddress2()[i]);
+ }
+
+ if (postSearch.getPostCity() != null && postSearch.getPostCity().length > 0) {
+ user.setCity(postSearch.getPostCity()[i]);
+ }
+
+ if (postSearch.getPostState() != null && postSearch.getPostState().length > 0) {
+ user.setState(postSearch.getPostState()[i]);
+ }
+
+ if (postSearch.getPostZipCode() != null && postSearch.getPostZipCode().length > 0) {
+ user.setZipCode(postSearch.getPostZipCode()[i]);
+ }
+
+ if (postSearch.getPostLocationClli() != null && postSearch.getPostLocationClli().length > 0) {
+ user.setLocationClli(postSearch.getPostLocationClli()[i]);
+ }
+
+ if (postSearch.getPostBusinessCountryCode() != null
+ && postSearch.getPostBusinessCountryCode().length > 0) {
+ user.setBusinessCountryCode(postSearch.getPostBusinessCountryCode()[i]);
+ }
+
+ if (postSearch.getPostBusinessCountryName() != null
+ && postSearch.getPostBusinessCountryName().length > 0) {
+
+ // find the country cd for the indicated country
+ List countries = dataAccessService.getLookupList("fn_lu_country", "country_cd", "country",
+ "country = '" + postSearch.getPostBusinessCountryName()[i] + "'", null, null);
+
+ if (countries != null && countries.size() == 1) {
+ Lookup country = (Lookup) countries.get(0);
+ user.setCountry(country.getValue());
+ } else {
+ logger.info(EELFLoggerDelegate.debugLogger,
+ "No countries or more than one country was found matching the country returned from WEBPHONE. "
+ + "Therefore, no country was set for this user.");
+ }
+
+ }
+
+ if (postSearch.getPostDepartment() != null && postSearch.getPostDepartment().length > 0) {
+ user.setDepartment(postSearch.getPostDepartment()[i]);
+ }
+
+ if (postSearch.getPostDepartmentName() != null && postSearch.getPostDepartmentName().length > 0) {
+ user.setDepartmentName(postSearch.getPostDepartmentName()[i]);
+ }
+
+ if (postSearch.getPostBusinessUnit() != null && postSearch.getPostBusinessUnit().length > 0) {
+ user.setBusinessUnit(postSearch.getPostBusinessUnit()[i]);
+ }
+
+ if (postSearch.getPostBusinessUnitName() != null
+ && postSearch.getPostBusinessUnitName().length > 0) {
+ user.setBusinessUnitName(postSearch.getPostBusinessUnitName()[i]);
+ }
+
+ if (postSearch.getPostJobTitle() != null && postSearch.getPostJobTitle().length > 0) {
+ user.setJobTitle(postSearch.getPostJobTitle()[i]);
+ }
+
+ if (postSearch.getPostOrgManagerUserId() != null
+ && postSearch.getPostOrgManagerUserId().length > 0) {
+ user.setOrgManagerUserId(postSearch.getPostOrgManagerUserId()[i]);
+ }
+
+ if (postSearch.getPostCommandChain() != null && postSearch.getPostCommandChain().length > 0) {
+ user.setCommandChain(postSearch.getPostCommandChain()[i]);
+ }
+
+ if (postSearch.getPostCompanyCode() != null && postSearch.getPostCompanyCode().length > 0) {
+ user.setCompanyCode(postSearch.getPostCompanyCode()[i]);
+ }
+
+ if (postSearch.getPostCompany() != null && postSearch.getPostCompany().length > 0) {
+ user.setCompany(postSearch.getPostCompany()[i]);
+ }
+
+ if (postSearch.getPostCostCenter() != null && postSearch.getPostCostCenter().length > 0) {
+ user.setCostCenter(postSearch.getPostCostCenter()[i]);
+ }
+
+ if (postSearch.getPostSiloStatus() != null && postSearch.getPostSiloStatus().length > 0) {
+ user.setSiloStatus(postSearch.getPostSiloStatus()[i]);
+ }
+
+ if (postSearch.getPostFinancialLocCode() != null
+ && postSearch.getPostFinancialLocCode().length > 0) {
+ user.setFinancialLocCode(postSearch.getPostFinancialLocCode()[i]);
+ }
+
+ user.setActive(true);
+
+ try {
+ dataAccessService.saveDomainObject(user, additionalParams);
+ Role role = (Role) dataAccessService.getDomainObject(Role.class,
+ Long.valueOf(SystemProperties.getProperty(SystemProperties.POST_DEFAULT_ROLE_ID)),
+ null);
+ user.addRole(role);
+ numUsersImported++;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "process: saveDomainObject failed on user " + user.getLoginId(), e);
+ }
+ }
+ }
+
+ }
+
+ return numUsersImported;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.List;
+
+import org.onap.portalsdk.core.domain.Profile;
+import org.onap.portalsdk.core.domain.User;
+
+
+public interface ProfileService {
+
+ /**
+ *
+ * @return returns list of profiles
+ * @throws Exception
+ */
+ List<Profile> findAll() throws Exception;
+
+ /**
+ *
+ * @param id
+ * @return returns profile of requested ID
+ * @throws Exception
+ */
+ Profile getProfile(int id) throws Exception;
+
+
+ /**
+ *
+ * @param id loginId
+ * @return returns User info of requested ID
+ * @throws Exception
+ */
+ User getUser(String id) throws Exception;
+
+ /**
+ *
+ * @param user
+ *saveUser method saves the user object
+ */
+ void saveUser(User user);
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.List;
+
+import org.onap.portalsdk.core.domain.Profile;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.annotation.Transactional;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Transactional
+public class ProfileServiceCentralizedImpl implements ProfileService{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProfileServiceCentralizedImpl.class);
+
+ @Autowired
+ AppService appService;
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ @Autowired
+ RestApiRequestBuilder restApiRequestBuilder ;
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<Profile> findAll() throws Exception{
+ return getDataAccessService().getList(Profile.class, null);
+ }
+
+ @Override
+ public Profile getProfile(int id) throws Exception{
+ ObjectMapper mapper = new ObjectMapper();
+ Profile user = null;
+ String responseString = restApiRequestBuilder.getViaREST("/getProfile/" + id, true,Integer.toString(id));
+ user = mapper.readValue(responseString, Profile.class);
+ return user;
+ }
+
+ @Override
+ public User getUser(String id) throws Exception{
+ ObjectMapper mapper = new ObjectMapper();
+ User user = new User();
+ String responseString =restApiRequestBuilder.getViaREST("/user/" + id, true,id);
+ user = mapper.readValue(responseString, User.class);
+
+ return user;
+ }
+
+ @Override
+ public void saveUser(User user) {
+ try {
+ getDataAccessService().saveDomainObject(user, null);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "saveUser failed", e);
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.List;
+
+import org.onap.portalsdk.core.dao.ProfileDao;
+import org.onap.portalsdk.core.domain.Profile;
+import org.onap.portalsdk.core.domain.User;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.annotation.Transactional;
+
+@Transactional
+public class ProfileServiceImpl implements ProfileService{
+
+ @Autowired
+ private ProfileDao profileDao;
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @SuppressWarnings("unchecked")
+ public List<Profile> findAll() {
+ //List msgDB = getDataAccessService().getList(Profile.class, null);
+ return getDataAccessService().getList(Profile.class, null);
+ }
+
+ public User getUser(String userId){
+ return (User) getDataAccessService().getDomainObject(User.class, Long.parseLong(userId), null);
+ }
+
+ public void saveUser(User user){
+
+ getDataAccessService().saveDomainObject(user, null);
+ }
+
+
+ public Profile getProfile(int id) {
+ return profileDao.getProfile(id);
+ }
+
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
+
+import java.io.IOException;
+
+import org.onap.portalsdk.core.domain.App;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
+import org.onap.portalsdk.core.onboarding.rest.RestWebServiceClient;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+
+public class RestApiRequestBuilder {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestApiRequestBuilder.class);
+
+ @Autowired
+ private AppService appService;
+
+ private static final String content_type = "application/json";
+
+ /**
+ *
+ * @param restEndPoint
+ * @param isBasicAuth
+ * @param userId
+ * @return
+ * @throws IOException
+ */
+ public String getViaREST(String restEndPoint, boolean isBasicAuth, String userId) throws IOException {
+ logger.info(EELFLoggerDelegate.debugLogger, "getViaRest: endpoint {}", restEndPoint);
+ String appName = "";
+ String appUserName = "";
+ String decryptedPwd = "";
+ App app = appService.getDefaultApp();
+ if (app != null) {
+ appName = app.getName();
+ appUserName = app.getUsername();
+ try {
+ decryptedPwd = CipherUtil.decrypt(app.getAppPassword(),
+ SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ } catch (CipherUtilException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getViaREST failed", e);
+ throw new IOException(e.toString());
+ }
+ } else {
+ logger.warn(EELFLoggerDelegate.errorLogger,
+ "getViaREST: Unable to locate the app information from the database.");
+ appName = SystemProperties.SDK_NAME;
+ }
+ String requestId = MDC.get(MDC_KEY_REQUEST_ID);
+ String response = RestWebServiceClient.getInstance().getPortalContent(restEndPoint, userId, appName, requestId,
+ appUserName, decryptedPwd, isBasicAuth);
+ logger.debug(EELFLoggerDelegate.errorLogger, "getViaREST response: {}", response);
+ return response;
+ }
+
+ /**
+ *
+ * @param restEndPoint
+ * @param isBasicAuth
+ * @param content
+ * @param userId
+ * @throws IOException
+ */
+ public void postViaREST(String restEndPoint, boolean isBasicAuth, String content, String userId)
+ throws IOException {
+ logger.info(EELFLoggerDelegate.debugLogger, "postViaRest: endpoint {}", restEndPoint);
+ String appName = "";
+ String appUserName = "";
+ String decryptedPwd = "";
+ App app = appService.getDefaultApp();
+ if (app != null) {
+ appName = app.getName();
+ appUserName = app.getUsername();
+ try {
+ decryptedPwd = CipherUtil.decrypt(app.getAppPassword(),
+ SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ } catch (CipherUtilException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "postViaREST failed", e);
+ throw new IOException(e.toString());
+ }
+ } else {
+ logger.warn(EELFLoggerDelegate.errorLogger,
+ "postViaRest: Unable to locate the app information from the database.");
+ appName = SystemProperties.SDK_NAME;
+ }
+ String requestId = MDC.get(MDC_KEY_REQUEST_ID);
+ String response = RestWebServiceClient.getInstance().postPortalContent(restEndPoint, userId, appName, requestId,
+ appUserName, decryptedPwd, content_type, content, isBasicAuth);
+ logger.debug(EELFLoggerDelegate.debugLogger, "postViaRest response: {}", response);
+ }
+
+ /**
+ *
+ * @param restEndPoint
+ * @param isBasicAuth
+ * @param content
+ * @param userId
+ * @throws IOException
+ */
+ public void deleteViaRest(String restEndPoint, boolean isBasicAuth, String content, String userId)
+ throws IOException {
+ logger.info(EELFLoggerDelegate.debugLogger, "deleteViaRest: endpoint {}", restEndPoint);
+ String appName = "";
+ String appUserName = "";
+ String decryptedPwd = "";
+ App app = appService.getDefaultApp();
+ if (app != null) {
+ appName = app.getName();
+ appUserName = app.getUsername();
+ try {
+ decryptedPwd = CipherUtil.decrypt(app.getAppPassword(),
+ SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ } catch (CipherUtilException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "postViaREST failed", e);
+ throw new IOException(e.toString());
+ }
+ } else {
+ logger.warn(EELFLoggerDelegate.errorLogger,
+ "deleteViaRest: Unable to locate the app information from the database.");
+ appName = SystemProperties.SDK_NAME;
+ }
+ String requestId = MDC.get(MDC_KEY_REQUEST_ID);
+ String response = RestWebServiceClient.getInstance().deletePortalContent(restEndPoint, userId, appName,
+ requestId, appUserName, decryptedPwd, content_type, content, isBasicAuth);
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteViaRest response: {}", response);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.List;
+
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.RoleFunction;
+
+
+public interface RoleService {
+ /**
+ *
+ * @param requestedLoginId loginId
+ * @return returns List of RoleFunction
+ * @throws Exception
+ * Method getRoleFunctions returns list of Role Functions
+ */
+ List<RoleFunction> getRoleFunctions(String requestedLoginId) throws Exception;
+
+
+ /**
+ *
+ * @param requestedLoginId
+ * @param roleId
+ * @return returns List of Role
+ * @throws Exception
+ * Method getAvailableChildRoles returns list of avialable child roles
+ */
+ List<Role> getAvailableChildRoles(String requestedLoginId,Long roleId) throws Exception;
+
+
+ /**
+ *
+ * @param requestedLoginId
+ * @param id roleId
+ * @return returns role
+ * @throws Exception
+ * Method getRole returns Role object if requested roleID
+ */
+ Role getRole(String requestedLoginId,Long id) throws Exception;
+
+ /**
+ *
+ * @param requestedLoginId
+ * @param domainRole Object to be saved
+ * Method saveRole saves the Role Object
+ */
+ void saveRole(String requestedLoginId,Role domainRole) throws Exception;
+
+ /**
+ *
+ * @param requestedLoginId
+ * @param domainRole Object to be removed
+ * Method deleteRole deletes the requested Role Object
+ */
+ void deleteRole(String requestedLoginId,Role domainRole) throws Exception;
+
+ /**
+ *
+ * @param requestedLoginId
+ * @return returns list of available roles
+ * @throws Exception
+ * Method getAvailableRoles gets the list of available roles
+ */
+
+ List<Role> getAvailableRoles(String requestedLoginId) throws Exception;
+
+ /**
+ *
+ * @param requestedLoginId
+ * @return List of active roles
+ * @throws Exception
+ * Method getActiveRoles gets the list of active roles of application
+ *
+ */
+ List<Role> getActiveRoles(String requestedLoginId) throws Exception;
+
+ /**
+ *
+ * @param requestedLoginId
+ * @param code function code
+ * @return RoleFunction of requested function code
+ * @throws Exception
+ * Method getRoleFunction returns RoleFunction of requested function code
+ */
+ RoleFunction getRoleFunction(String requestedLoginId,String code) throws Exception;
+
+ /**
+ *
+ * @param requestedLoginId
+ * @param domainRoleFunction
+ * Method saveRoleFunction saves the requested RoleFunction object
+ */
+ void saveRoleFunction(String requestedLoginId,RoleFunction domainRoleFunction) throws Exception;
+
+ /**
+ *
+ * @param requestedLoginId
+ * @param domainRoleFunction
+ * Method deleteRoleFunction deletes the requested RoleFunction object
+ */
+ void deleteRoleFunction(String requestedLoginId,RoleFunction domainRoleFunction) throws Exception;
+
+ /**
+ *
+ * @param requestedLoginId
+ * @param id
+ * Method deleteDependcyRoleRecord deletes the requested object
+ */
+ void deleteDependcyRoleRecord(String requestedLoginId,Long id);
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.RoleFunction;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.annotation.Transactional;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+
+@Transactional
+public class RoleServiceCentralizedAccess implements RoleService {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleServiceCentralizedAccess.class);
+
+ @Autowired
+ private RestApiRequestBuilder restApiRequestBuilder;
+
+ @Override
+ public List<RoleFunction> getRoleFunctions(String loginId) throws Exception {
+
+ List<RoleFunction> roleFunctionList = null;
+ String role_function_list = "";
+ role_function_list = restApiRequestBuilder.getViaREST("/functions", true, loginId);
+ ObjectMapper mapper = new ObjectMapper();
+ roleFunctionList = mapper.readValue(role_function_list,
+ TypeFactory.defaultInstance().constructCollectionType(List.class, RoleFunction.class));
+ return roleFunctionList;
+ }
+
+ @Override
+ public List<Role> getAvailableChildRoles(String loginId, Long roleId) throws Exception {
+ List<Role> availableChildRoles = getAvailableRoles(loginId);
+ if (roleId == null || roleId == 0) {
+ return availableChildRoles;
+ }
+
+ Role currentRole = getRole(loginId, roleId);
+ Set<Role> allParentRoles = new TreeSet<Role>();
+ allParentRoles = getAllParentRolesAsList(loginId, currentRole, allParentRoles);
+
+ Iterator<Role> availableChildRolesIterator = availableChildRoles.iterator();
+ while (availableChildRolesIterator.hasNext()) {
+ Role role = availableChildRolesIterator.next();
+ if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
+ availableChildRolesIterator.remove();
+ }
+ }
+ return availableChildRoles;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Set<Role> getAllParentRolesAsList(String loginId, Role role, Set<Role> allParentRoles) {
+ Set<Role> parentRoles = role.getParentRoles();
+ allParentRoles.addAll(parentRoles);
+ Iterator<Role> parentRolesIterator = parentRoles.iterator();
+ while (parentRolesIterator.hasNext()) {
+ getAllParentRolesAsList(loginId, parentRolesIterator.next(), allParentRoles);
+ }
+ return allParentRoles;
+ }
+
+ @Override
+ public Role getRole(String loginId, Long id) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ String roleString = restApiRequestBuilder.getViaREST("/role/" + id, true, loginId);
+ Role role = new Role();
+ role = mapper.readValue(roleString, Role.class);
+ if (role.getRoleFunctions() != null) {
+ @SuppressWarnings("unchecked")
+ Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
+ Set<RoleFunction> roleFunctionListNew = new HashSet<>();
+ Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
+ while (itetaror.hasNext()) {
+ Object nextValue = itetaror.next();
+ RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
+ roleFunctionListNew.add(roleFun);
+ }
+
+ role.setRoleFunctions(roleFunctionListNew);
+ }
+ logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + role.getId());
+ return role;
+
+ }
+
+ @Override
+ public void saveRole(String loginId, Role domainRole) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ String role = mapper.writeValueAsString(domainRole);
+ try {
+ restApiRequestBuilder.postViaREST("/role", true, role, loginId);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "saveRole Failed", e);
+ throw new Exception(e.getMessage());
+ }
+ }
+
+ @Override
+ public void deleteRole(String loginId, Role domainRole) throws Exception {
+ String roleName = domainRole.getName().replaceAll(" ", "%20");
+ try {
+ restApiRequestBuilder.deleteViaRest("/deleteRole/"+ roleName, true, null, loginId);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteRole Failed", e);
+ throw new Exception(e.getMessage());
+ }
+ }
+ @Override
+ public List<Role> getAvailableRoles(String requestedLoginId) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ String roleList = restApiRequestBuilder.getViaREST("/roles", true, requestedLoginId);
+ List<Role> roles = null;
+ roles = mapper.readValue(roleList,
+ TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
+ return roles;
+ }
+
+ @Override
+ public List<Role> getActiveRoles(String requestedLoginId) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ String roleString = restApiRequestBuilder.getViaREST("/activeRoles", true, requestedLoginId);
+ List<Role> roles = null;
+ roles = mapper.readValue(roleString,
+ TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
+ return roles;
+
+ }
+
+ @Override
+ public RoleFunction getRoleFunction(String requestedLoginId, String code) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ String responseString = restApiRequestBuilder.getViaREST("/function/" + code, true, requestedLoginId);
+ RoleFunction roleFunction = new RoleFunction();
+ if (!responseString.isEmpty()) {
+ roleFunction = mapper.readValue(responseString, RoleFunction.class);
+ }
+ return roleFunction;
+ }
+
+ @Override
+ public void saveRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ String roleFunction = mapper.writeValueAsString(domainRoleFunction);
+ try{
+ restApiRequestBuilder.postViaREST("/roleFunction", true, roleFunction, requestedLoginId);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction Failed", e);
+ throw new Exception(e.getMessage());
+ }
+ }
+
+ @Override
+ public void deleteRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws Exception {
+ String code = domainRoleFunction.getCode();
+ try {
+ restApiRequestBuilder.deleteViaRest("/roleFunction/"+ code, true, null, requestedLoginId);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction Failed ", e);
+ throw new Exception(e.getMessage());
+ }
+ }
+
+ @Override
+ public void deleteDependcyRoleRecord(String requestedLoginId, Long id) {
+ try {
+ restApiRequestBuilder.deleteViaRest("/deleteDependcyRoleRecord/" + id, true, null, requestedLoginId);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord Failed", e);
+ }
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import javax.sql.DataSource;
+
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.RoleFunction;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.annotation.Transactional;
+
+@Transactional
+public class RoleServiceImpl implements RoleService {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleServiceImpl.class);
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ DataSource dataSource;
+
+ public DataSource getDataSource() {
+ return dataSource;
+ }
+
+ @Autowired
+ public void setDataSource(DataSource dataSource) {
+ this.dataSource = dataSource;
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<RoleFunction> getRoleFunctions(String loginId) {
+ // List msgDB = getDataAccessService().getList(Profile.class, null);
+ return getDataAccessService().getList(RoleFunction.class, null);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<Role> getAvailableChildRoles(String loginId,Long roleId) {
+ List<Role> availableChildRoles = (List<Role>) getDataAccessService().getList(Role.class, null);
+ if (roleId == null || roleId == 0) {
+ return availableChildRoles;
+ }
+
+ Role currentRole = (Role) getDataAccessService().getDomainObject(Role.class, roleId, null);
+ Set<Role> allParentRoles = new TreeSet<Role>();
+ allParentRoles = getAllParentRolesAsList(loginId,currentRole, allParentRoles);
+
+ Iterator<Role> availableChildRolesIterator = availableChildRoles.iterator();
+ while (availableChildRolesIterator.hasNext()) {
+ Role role = availableChildRolesIterator.next();
+ if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
+ availableChildRolesIterator.remove();
+ }
+ }
+ return availableChildRoles;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Set<Role> getAllParentRolesAsList(String loginId,Role role, Set<Role> allParentRoles) {
+ Set<Role> parentRoles = role.getParentRoles();
+ allParentRoles.addAll(parentRoles);
+ Iterator<Role> parentRolesIterator = parentRoles.iterator();
+ while (parentRolesIterator.hasNext()) {
+ getAllParentRolesAsList( loginId,parentRolesIterator.next(), allParentRoles);
+ }
+ return allParentRoles;
+ }
+
+ public RoleFunction getRoleFunction(String loginId,String code) {
+ return (RoleFunction) getDataAccessService().getDomainObject(RoleFunction.class, code, null);
+ }
+
+ public void saveRoleFunction(String loginId,RoleFunction domainRoleFunction) {
+ getDataAccessService().saveDomainObject(domainRoleFunction, null);
+ }
+
+ public void deleteRoleFunction(String loginId,RoleFunction domainRoleFunction) {
+ getDataAccessService().deleteDomainObject(domainRoleFunction, null);
+ }
+
+ public Role getRole(String loginId,Long id) {
+ return (Role) getDataAccessService().getDomainObject(Role.class, id, null);
+ }
+
+ public void saveRole(String loginId,Role domainRole) {
+ getDataAccessService().saveDomainObject(domainRole, null);
+ }
+
+ public void deleteRole(String loginId,Role domainRole) {
+ getDataAccessService().deleteDomainObject(domainRole, null);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<Role> getAvailableRoles(String loginId) {
+ return getDataAccessService().getList(Role.class, null);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<Role> getActiveRoles(String loginId) {
+ String filter = " where active_yn = 'Y' ";
+ return getDataAccessService().getList(Role.class, filter, null, null);
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ @Override
+ public void deleteDependcyRoleRecord(String loginId,Long id) {
+ Connection conn = null;
+ Statement stmt = null;
+ try {
+ conn = getDataSource().getConnection();
+ stmt = conn.createStatement();
+ String sql = "delete from fn_user_role where role_id = '" + id + "'";
+ stmt.executeUpdate(sql);
+ stmt.close();
+ conn.close();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", e);
+ } finally {
+ try {
+ if (stmt != null)
+ stmt.close();
+ } catch (SQLException se2) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", se2);
+ }
+ try {
+ if (conn != null)
+ conn.close();
+ } catch (SQLException se) {
+ logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", se);
+ }
+ }
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.domain.UrlsAccessible;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Transactional
+@Service("urlAccessService")
+public class UrlAccessImpl implements UrlAccessService {
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @Override
+ public boolean isUrlAccessible(HttpServletRequest request, String currentUrl) {
+ boolean isAccessible = false;
+ Map<String, String> params = new HashMap<>();
+ params.put("current_url", currentUrl);
+ List list = dataAccessService.executeNamedQuery("restrictedUrls", params, null);
+
+ // loop through the list of restricted URL's
+ if (list != null && list.size() > 0) {
+ for (int i = 0; i < list.size(); i++) {
+ UrlsAccessible urlFunctions = (UrlsAccessible) list.get(i);
+ // String url = (String) urlFunctions.getUrl();
+ String functionCd = (String) urlFunctions.getFunctionCd();
+ if (UserUtils.isAccessible(request, functionCd)) {
+ isAccessible = true;
+ }
+ }
+ return isAccessible;
+ }
+ return true;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import javax.servlet.http.HttpServletRequest;
+
+public interface UrlAccessService {
+
+ /**
+ * Answers whether the specified URL is accessible.
+ *
+ * @param request
+ * @param currentUrl
+ * @return true if yes, false if no.
+ */
+ public boolean isUrlAccessible(HttpServletRequest request, String currentUrl);
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.List;
+
+import org.onap.portalsdk.core.domain.User;
+
+
+public interface UserProfileService {
+ List<User> findAll();
+ User getUserByLoginId(String loginId);
+ void saveUser(User user);
+ public List<User> findAllUserWithOnOffline(String originOrgUserId);
+ List<User> findAllActive();
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.SortedSet;
+
+import org.hibernate.criterion.Criterion;
+import org.hibernate.criterion.Restrictions;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.domain.support.CollaborateList;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("userProfile")
+@Transactional
+public class UserProfileServiceImpl implements UserProfileService{
+
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @SuppressWarnings("unchecked")
+ public List<User> findAll() {
+ return getDataAccessService().getList(User.class, null);
+ }
+
+ @SuppressWarnings("unchecked")
+ public User getUserByLoginId(String loginId){
+ User user=null;
+ List<Criterion> restrictionsList = new ArrayList<Criterion>();
+ Criterion criterion1= Restrictions.eq("loginId",loginId);
+ restrictionsList.add(criterion1);
+ List<User> users = (List<User>) getDataAccessService().getList(User.class,null, restrictionsList, null);
+ if(users!=null && users.size()==1)
+ user = users.get(0);
+ return user;
+ }
+
+ public void saveUser(User user){
+
+ getDataAccessService().saveDomainObject(user, null);
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<User> findAllUserWithOnOffline(String originOrgUserId) {
+ HashSet<String> onlineUser = CollaborateList.getInstance().getAllUserName();
+ List<User> users = getDataAccessService().getList(User.class, null);
+ for(User u:users){
+ if(onlineUser.contains(u.getOrgUserId()))
+ u.setOnline(true);
+ if(u.getOrgUserId()!=null){
+ if(originOrgUserId.compareTo(u.getOrgUserId()) > 0) {
+ u.setChatId(originOrgUserId + "-" + u.getOrgUserId());
+ } else u.setChatId(u.getOrgUserId() + "-" + originOrgUserId );
+ }
+ }
+ return users;
+
+ }
+
+ public List<User> findAllActive() {
+ @SuppressWarnings("unchecked")
+ List<User> users = getDataAccessService().getList(User.class, null);
+ Iterator<User> itr = users.iterator();
+ while(itr.hasNext()){
+ User u = (User) itr.next();
+ if(!u.getActive())
+ itr.remove();//if not active remove user from list
+ else {
+ SortedSet<Role> roles = u.getRoles();
+ Iterator<Role> itrRoles = roles.iterator();
+ while(itrRoles.hasNext()){
+ Role role = (Role) itrRoles.next();
+ if(!role.getActive())
+ u.removeRole(role.getId());//if not active remove role from list
+ }
+ }
+ }
+ return users;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.io.IOException;
+
+import org.onap.portalsdk.core.domain.User;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+
+public interface UserService {
+
+ /**
+ * Gets the user object for the specified ID.
+ *
+ * @param id
+ * orgUserID
+ * @return User object
+ * @throws IOException
+ */
+ User getUser(String id) throws IOException;
+
+ /**
+ * Builds a User object from a JSON string.
+ *
+ * @param response
+ * @return User object
+ * @throws IOException
+ * @throws JsonProcessingException
+ */
+ User userMapper(String response) throws IOException, JsonProcessingException;
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.RoleFunction;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.domain.UserApp;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.annotation.Transactional;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Transactional
+public class UserServiceCentalizedImpl implements UserService {
+
+ @Autowired
+ private RestApiRequestBuilder restApiRequestBuilder;
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ @Override
+ public User getUser(String id) throws IOException {
+ String orgUserId = getUserByProfileId(id);
+ String responseString = restApiRequestBuilder.getViaREST("/user/" + orgUserId, true, id);
+ User user = userMapper(responseString);
+ return user;
+ }
+
+ public String getUserByProfileId(String id) {
+ Map<String, Long> params = new HashMap<>();
+ params.put("user_id", new Long(id));
+ @SuppressWarnings("rawtypes")
+ List list = getDataAccessService().executeNamedQuery("getUserByProfileId", params, null);
+ String orgUserId = "";
+ if (list != null && !list.isEmpty())
+ orgUserId = (String) list.get(0);
+ return orgUserId;
+ }
+
+ @Override
+ public User userMapper(String res) throws IOException, JsonProcessingException {
+ ObjectMapper mapper = new ObjectMapper();
+ User user = mapper.readValue(res, User.class);
+ Set<RoleFunction> roleFunctionListNew = new HashSet<>();
+ SortedSet<UserApp> userAppSet = new TreeSet<>();
+ @SuppressWarnings("unchecked")
+ Set<UserApp> setAppsObj = user.getUserApps();
+ Iterator<UserApp> it = setAppsObj.iterator();
+ while (it.hasNext()) {
+ Object next = it.next();
+ UserApp nextApp = mapper.convertValue(next, UserApp.class);
+ Role role = nextApp.getRole();
+ @SuppressWarnings("unchecked")
+ Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
+ Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
+ while (itetaror.hasNext()) {
+ Object nextValue = itetaror.next();
+ RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
+ roleFunctionListNew.add(roleFunction);
+ }
+ role.setRoleFunctions(roleFunctionListNew);
+ nextApp.setRole(role);
+ nextApp.getRole().getRoleFunctions();
+
+ userAppSet.add(nextApp);
+ user.setUserApps(userAppSet);
+ }
+ return user;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import org.onap.portalsdk.core.domain.User;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.annotation.Transactional;
+
+@Transactional
+public class UserServiceImpl implements UserService {
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @Override
+ public User getUser(String id) {
+ return (User) dataAccessService.getDomainObject(User.class, Long.parseLong(id), null);
+ }
+
+ @Override
+ public User userMapper(String response) {
+ throw new UnsupportedOperationException("method cannot be used");
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+
+public interface WebServiceCallService {
+ public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword)throws Exception;
+ /*public String get(String restURL, String restPath);*/
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service;
+
+import java.util.List;
+
+import org.onap.portalsdk.core.domain.App;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("webServiceCallService")
+@Transactional
+public class WebServiceCallServiceImpl implements WebServiceCallService{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebServiceCallServiceImpl.class);
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @Autowired
+ private AppService appService;
+
+ /**
+ * Verify REST Credential
+ * @return true if the credential is accepted; else false.
+ */
+ @Override
+ public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword)throws Exception {
+ App app = appService.getDefaultApp();
+ if (app!=null) {
+ String encriptedPwdDB = app.getAppPassword();
+ String appUserName = app.getUsername();
+ String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB, secretKey==null?SystemProperties.getProperty(SystemProperties.Decryption_Key):secretKey);
+ if(decreptedPwd.equals(requestPassword) && appUserName.equals(requestAppName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Getting App information from FN_APP table
+ * @return App domain object, or null if not found.
+ */
+ public App findApp(){
+ List<?> list = null;
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where id = 1");
+ list = getDataAccessService().getList(App.class, criteria.toString(), null, null);
+ return (list == null || list.size() == 0) ? null : (App) list.get(0);
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ /*/
+ @Override
+ public String get(String restURL, String restPath) {
+ String appUserName = "";
+ String appUebKey = "";
+ String decreptedPwd = "";
+ String appName = "";
+ String inputLine = "";
+ String serviceName = "";
+ String loginId = "";
+ StringBuffer jsonResponse = new StringBuffer();
+
+ StopWatch stopWatch = new StopWatch("WebServiceCallServiceImpl.get");
+ stopWatch.start();
+ try {
+ logger.info(EELFLoggerDelegate.metricsLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started.");
+ logger.debug(EELFLoggerDelegate.debugLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started.");
+ loginId = MDC.get("LoginId");
+ appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
+ App app = appService.getDefaultApp();
+ if (app!=null) {
+ appName = app.getName();
+ appUserName = app.getUsername();
+ try{
+ decreptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: " + e.getMessage());
+ }
+ } else {
+ logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database.");
+ appName = SystemProperties.SERVICE_NAME;
+ }
+
+ //Create the connection object
+ URL obj = new URL(restURL + restPath);
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+ con.setRequestMethod("GET");
+ con.setConnectTimeout(3000);
+ con.setReadTimeout(8000);
+
+ //add request header
+ con.setRequestProperty("username", appUserName);
+ con.setRequestProperty("password", decreptedPwd);
+ con.setRequestProperty("uebkey", appUebKey);
+ con.setRequestProperty(SystemProperties.LOGIN_ID, loginId);
+ con.setRequestProperty(SystemProperties.USERAGENT_NAME, appName);
+ con.setRequestProperty(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID));
+
+ //set MDC context for outgoing audit logging
+ serviceName = String.format("%s:%s.%s", appName, SystemProperties.ECOMP_PORTAL_BE, restPath);
+ MDC.put(Configuration.MDC_SERVICE_NAME, serviceName);
+ MDC.put(Configuration.MDC_REMOTE_HOST, restURL);
+ MDC.put(SystemProperties.MDC_APPNAME, appName);
+ MDC.put(SystemProperties.MDC_REST_PATH, restPath);
+ MDC.put(SystemProperties.MDC_REST_METHOD, "GET");
+
+ int responseCode = con.getResponseCode();
+ logger.info(EELFLoggerDelegate.errorLogger, "Received the response code '" + responseCode + "' while getting the '" + restPath + "' for user: " + loginId);
+
+ BufferedReader in = new BufferedReader(
+ new InputStreamReader(con.getInputStream()));
+
+ while ((inputLine = in.readLine()) != null) {
+ jsonResponse.append(inputLine);
+ }
+ in.close();
+
+ logSecurityMessage(RESULT_ENUM.SUCCESS);
+ logger.debug(EELFLoggerDelegate.debugLogger, restPath + " response: " + jsonResponse.toString());
+ logger.debug(EELFLoggerDelegate.debugLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started.");
+ } catch(UrlAccessRestrictedException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Authentication exception occurred in WebServiceCallServiceImpl.get (" + restPath + "). Details: " + e.getMessage());
+ logSecurityMessage(RESULT_ENUM.FAILURE);
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get (" + restPath + "). Details: " + e.getMessage());
+ logSecurityMessage(RESULT_ENUM.FAILURE);
+ } finally {
+ if (stopWatch.isRunning()) stopWatch.stop();
+ MDC.put(SystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms");
+ logger.info(EELFLoggerDelegate.metricsLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is completed.");
+
+ //clear the temporary MDC context values
+ MDC.remove(SystemProperties.MDC_TIMER);
+ MDC.remove(SystemProperties.MDC_REST_METHOD);
+ MDC.remove(SystemProperties.MDC_REST_PATH);
+ MDC.remove(SystemProperties.MDC_APPNAME);
+ MDC.remove(Configuration.MDC_REMOTE_HOST);
+ MDC.remove(Configuration.MDC_SERVICE_NAME);
+ }
+
+ return jsonResponse.toString();
+ }
+
+ //Handles all the outgoing rest/ueb messages.
+ public void logSecurityMessage(RESULT_ENUM isSuccess) {
+ String additionalInfo = "";
+ String protocol = "HTTP";
+ String loginId = MDC.get("LoginId");
+ additionalInfo = String.format("Rest API=%s, Rest Method=%s, App-Name=%s, Request-URL=%s",
+ MDC.get(SystemProperties.MDC_REST_PATH), MDC.get(SystemProperties.MDC_REST_METHOD),
+ MDC.get(SystemProperties.MDC_APPNAME), MDC.get(Configuration.MDC_REMOTE_HOST));
+
+ logger.info(EELFLoggerDelegate.auditLogger, AuditLogFormatter.getInstance().createMessage(
+ protocol, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE.name(), loginId, SystemProperties.SERVICE_NAME,
+ isSuccess.name(), additionalInfo));
+ }
+ /**/
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service.support;
+
+
+import org.onap.portalsdk.core.FusionObject;
+
+public class FusionService implements FusionObject {
+ /** Logger for this class and subclasses */
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service.support;
+
+import javax.naming.directory.DirContext;
+
+
+public interface ServiceLocator {
+ DirContext getDirContext(String initialContextFactory, String providerUrl, String securityPrincipal);
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.service.support;
+
+import java.util.Properties;
+
+import javax.naming.Context;
+import javax.naming.NamingException;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.InitialDirContext;
+import javax.naming.ldap.InitialLdapContext;
+
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.stereotype.Service;
+
+/**
+ * This class implements the J2EE service locator pattern. It provides lookup
+ * facilities for various services. Currenttly LDAP (pre-v3) is supported
+ */
+@Service("serviceLocator")
+public class ServiceLocatorImpl implements ServiceLocator {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ServiceLocatorImpl.class);
+
+ private Context context; // JNDI context (not currently in use)
+ private Context rootContext; // Java env root context (not currently in use)
+ private DirContext dirContext; // LDAP DIR context
+ private InitialLdapContext ldapContext; // LDAP context LDAPv3-style (not currently in use)
+
+
+ // cannot directly instantiate
+ public ServiceLocatorImpl() {}
+
+ /*public static ServiceLocator getLocator() {
+ if (locator == null)
+ locator = new ServiceLocator();
+ return locator;
+ }
+
+ public Object clone() throws CloneNotSupportedException {
+ throw new CloneNotSupportedException();
+ }*/
+
+
+ // Get an LDAP directory context
+ public DirContext getDirContext(String initialContextFactory, String providerUrl, String securityPrincipal) {
+
+ if (dirContext == null) {
+
+ Properties properties = new Properties();
+ properties.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
+ properties.put(Context.PROVIDER_URL, providerUrl);
+ properties.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
+
+ try {
+ dirContext = new InitialDirContext(properties);
+ }
+ catch (NamingException ne) {
+ logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while creating an Initial Directory Context: " + ne.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, "Explanation: " + ne.getExplanation());
+ }
+ }
+
+ return dirContext;
+ }
+
+ // Get an LDAP directory context - LDAPv3-style
+ /*public InitialLdapContext getLdapContext() { //throws NamingException {
+ if (ldapContext == null) {
+ Properties properties = new Properties();
+ // @todo - need to parameterize context factoy class and url
+ properties.put(Context.INITIAL_CONTEXT_FACTORY, AttLdap.DIR_INITIAL_CONTEXT_FACTORY);
+ properties.put(Context.PROVIDER_URL, AttLdap.DIR_PROVIDER_URL);
+ properties.put(Context.SECURITY_PRINCIPAL, AttLdap.DIR_SECURITY_PRINCIPAL);
+ Control[] ctrl = null;
+ try {
+ ldapContext = new InitialLdapContext(properties, ctrl);
+ }
+ catch (NamingException ne) {
+ // MJ FIX log exception?
+ }
+ }
+ return ldapContext;
+ }*/
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.util;
+
+import org.onap.portalsdk.core.objectcache.jcs.JCSCacheManager;
+import org.springframework.context.annotation.Configuration;
+@Configuration
+public class CacheManager extends JCSCacheManager {
+ public CacheManager() {
+
+ }
+
+ /* The following can be customized for your application to cache the appropriate data upon application startup. The provided
+ example retrieves a list of sample lookup data and puts the list in the Cache Manager. To retrieve that data, simply call the
+ Cache Manager's getObject(String key) method which will return an Object instance. To put additional data in the Cache Manager
+ outside of application startup, call the Cache Manager's putObject(String key, Object objectToCache) method. */
+ public void loadLookUpCache() {
+ /*
+ List<Role> result = (List<Role>)getDataAccessService().getList(Role.class,null);
+
+ if (result != null) {
+ putObject("lookupRoles", result);
+ }*/
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.util;
+import java.security.AlgorithmParameters;
+import java.security.SecureRandom;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.commons.codec.binary.Base64;
+
+public class EncDecUtilTest {
+
+ private static final String password = "test";
+ private static final String salt = "r n�HN~�\ 6�\1a|\bf��X\1d�" ;
+ private static int pswdIterations = 65536 ;
+ private static int keySize = 256;
+ private byte[] ivBytes;
+
+ public String encrypt(String plainText) throws Exception {
+
+ //get salt
+ //salt = generateSalt();
+ byte[] saltBytes = salt.getBytes("UTF-8");
+
+ // Derive the key
+ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
+ PBEKeySpec spec = new PBEKeySpec(
+ password.toCharArray(),
+ saltBytes,
+ pswdIterations,
+ keySize
+ );
+
+ SecretKey secretKey = factory.generateSecret(spec);
+ SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
+
+ //encrypt the message
+ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+ cipher.init(Cipher.ENCRYPT_MODE, secret);
+ AlgorithmParameters params = cipher.getParameters();
+ ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
+ byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
+ return new Base64().encodeAsString(encryptedTextBytes);
+ }
+
+ @SuppressWarnings("static-access")
+ public String decrypt(String encryptedText) throws Exception {
+
+ byte[] saltBytes = salt.getBytes("UTF-8");
+ byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText);
+
+ // Derive the key
+ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
+ PBEKeySpec spec = new PBEKeySpec(
+ password.toCharArray(),
+ saltBytes,
+ pswdIterations,
+ keySize
+ );
+
+ SecretKey secretKey = factory.generateSecret(spec);
+ SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
+
+ // Decrypt the message
+ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+ cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));
+
+
+ byte[] decryptedTextBytes = null;
+ try {
+ decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
+ } catch (IllegalBlockSizeException e) {
+ e.printStackTrace();
+ } catch (BadPaddingException e) {
+ e.printStackTrace();
+ }
+
+ return new String(decryptedTextBytes);
+ }
+
+ public String generateSalt() {
+ SecureRandom random = new SecureRandom();
+ byte bytes[] = new byte[20];
+ random.nextBytes(bytes);
+ String s = new String(bytes);
+ return s;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.util;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.onap.portalsdk.core.domain.User;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class JSONUtil {
+ public static String convertResponseToJSON(String response) throws JsonProcessingException{
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String, String> responseMap = new HashMap<String, String>();
+ responseMap.put("response", response);
+ response = mapper.writeValueAsString(responseMap);
+ return response;
+ }
+
+ public static User mapToDomainUser(User domainUser, User editUser) {
+ domainUser.setOrgId(editUser.getOrgId());
+ domainUser.setManagerId(editUser.getManagerId());
+ domainUser.setFirstName(editUser.getFirstName());
+ domainUser.setMiddleInitial(editUser.getMiddleInitial());
+ domainUser.setLastName(editUser.getLastName());
+ domainUser.setPhone(editUser.getPhone());
+ domainUser.setEmail(editUser.getEmail());
+ domainUser.setHrid(editUser.getHrid());
+ domainUser.setOrgUserId(editUser.getOrgUserId());
+ domainUser.setOrgCode(editUser.getOrgCode());
+ domainUser.setOrgManagerUserId(editUser.getOrgManagerUserId());
+ domainUser.setJobTitle(editUser.getJobTitle());
+ domainUser.setLoginId(editUser.getLoginId());
+ domainUser.setActive(editUser.getActive());
+ return domainUser;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.util;
+
+import javax.servlet.ServletContext;
+
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.core.env.Environment;
+
+/**
+ * SystemProperties contains a list of constants used throughout portions of the
+ * application. Populated by Spring from multiple configuration files.
+ *
+ * Should be used like this:
+ *
+ * <pre>
+ *
+ * @Autowired
+ * SystemProperties systemProperties;
+ * </pre>
+ */
+@Configuration
+@PropertySource(value = { "${container.classpath:}/WEB-INF/conf/system.properties",
+ "${container.classpath:}/WEB-INF/fusion/conf/fusion.properties",
+ "${container.classpath:}/WEB-INF/conf/sql.properties" })
+public class SystemProperties {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SystemProperties.class);
+
+ private static Environment environment;
+
+ private ServletContext servletContext;
+
+ public SystemProperties() {
+ }
+
+ protected Environment getEnvironment() {
+ return environment;
+ }
+
+ @Autowired
+ public void setEnvironment(Environment environment) {
+ SystemProperties.environment = environment;
+ }
+
+ public ServletContext getServletContext() {
+ return servletContext;
+ }
+
+ public void setServletContext(ServletContext servletContext) {
+ this.servletContext = servletContext;
+ }
+
+ /**
+ * Tests whether a property value is available for the specified key.
+ *
+ * @param key Property key
+ * @return True if the key is known, otherwise false.
+ */
+ public static boolean containsProperty(String key) {
+ return environment.containsProperty(key);
+ }
+
+ /**
+ * Returns the property value associated with the given key (never
+ * {@code null}), after trimming any trailing space.
+ *
+ * @param key
+ * Property key
+ * @return Property value; the empty string if the environment was not
+ * autowired, which should never happen.
+ * @throws IllegalStateException
+ * if the key cannot be resolved
+ */
+ public static String getProperty(String key) {
+ String value = "";
+ if (environment == null) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getProperty: environment is null, should never happen!");
+ }
+ else {
+ value = environment.getRequiredProperty(key);
+ // java.util.Properties preserves trailing space
+ if (value != null)
+ value = value.trim();
+ }
+ return value;
+ }
+
+ /**
+ * Gets the property value for the key {@link #APPLICATION_NAME}.
+ *
+ * method created to get around JSTL 1.0 limitation of not being able to
+ * access a static method of a bean
+ *
+ * @return Application name
+ */
+ public String getApplicationName() {
+ return getProperty(APPLICATION_NAME);
+ }
+
+ /**
+ * Gets the property value for the key {@link #APP_DISPLAY_NAME}.
+ *
+ * @return Application display name
+ */
+ public String getAppDisplayName() {
+ return getProperty(APP_DISPLAY_NAME);
+ }
+
+ // keys used to reference values in the system properties file
+ public static final String DOMAIN_CLASS_LOCATION = "domain_class_location";
+ public static final String DEFAULT_ERROR_MESSAGE = "default_error_message";
+
+ public static final String CSP_COOKIE_NAME = "csp_cookie_name";
+ public static final String CSP_GATE_KEEPER_DATA_KEY = "csp_gate_keeper_data_key";
+ public static final String CSP_GATE_KEEPER_PROD_KEY = "csp_gate_keeper_prod_key";
+ public static final String CSP_LOGIN_URL = "csp_login_url";
+ public static final String CSP_LOGOUT_URL = "csp_logout_url";
+
+ public static final String WEB_JUNCTION_USER_ID_HEADER_NAME = "web_junction_user_id_header_name";
+
+ public static final String AUTHENTICATION_MECHANISM = "authentication_mechanism";
+
+ public static final String APPLICATION_NAME = "application_name";
+ public static final String HIBERNATE_CONFIG_FILE_PATH = "hibernate_config_file_path";
+ public static final String APPLICATION_USER_ID = "application_user_id";
+
+ public static final String POST_INITIAL_CONTEXT_FACTORY = "post_initial_context_factory";
+ public static final String POST_PROVIDER_URL = "post_provider_url";
+ public static final String POST_SECURITY_PRINCIPAL = "post_security_principal";
+ public static final String POST_MAX_RESULT_SIZE = "post_max_result_size";
+ public static final String POST_DEFAULT_ROLE_ID = "post_default_role_id";
+
+ public static final String FILES_PATH = "files_path";
+ public static final String TEMP_PATH = "temp_path";
+
+ public static final String NUM_UPLOAD_FILES = "num_upload_files";
+
+ public static final String SYS_ADMIN_ROLE_ID = "sys_admin_role_id";
+
+ public static final String SYS_ADMIN_ROLE_FUNCTION_DELETE_FROM_UI = "sys_admin_role_function_delete_from_ui";
+ public static final String USER_NAME = "user_name";
+ public static final String FIRST_NAME = "first_name";
+ public static final String LAST_NAME = "last_name";
+ public static final String APP_DISPLAY_NAME = "app_display_name";
+ // Application base URL is a proper prefix of the on-boarding URL
+ public static final String APP_BASE_URL = "app_base_url";
+
+ public static final String MENU_PROPERTIES_FILE_LOCATION = "menu_properties_file_location";
+ public static final String MENU_QUERY_NAME = "menu_query_name";
+ public static final String APPLICATION_MENU_SET_NAME = "application_menu_set_name";
+ public static final String APPLICATION_MENU_ATTRIBUTE_NAME = "application_menu_attribute_name";
+ public static final String APPLICATION_MENU_PROPERTIES_NAME = "application_menu_properties_name";
+ public static final String BUSINESS_DIRECT_MENU_SET_NAME = "business_direct_menu_set_name";
+ public static final String BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME = "business_direct_menu_attribute_name";
+ public static final String BUSINESS_DIRECT_MENU_PROPERTIES_NAME = "business_direct_menu_properties_name";
+ public static final String RAPTOR_CONFIG_FILE_PATH = "raptor_config_file_path";
+ public static final String HOMEPAGE_DATA_CALLBACK_CLASS = "homepage_data_callback_class";
+ public static final String ERROR_EMAIL_DISTRIBUTION = "error_email_distribution";
+ public static final String ERROR_EMAIL_SOURCE_ADDRESS = "error_email_source_address";
+ public static final String ERROR_EMAIL_SUBJECT_LINE = "error_email_subject_line";
+ public static final String PROFILE_SEARCH_REPORT_ID = "profile_search_report_id";
+ public static final String CALLABLE_PROFILE_SEARCH_REPORT_ID = "callable_profile_search_report_id";
+ public static final String CLUSTERED = "clustered";
+
+ public static final String USER_ATTRIBUTE_NAME = "user_attribute_name";
+ public static final String ROLES_ATTRIBUTE_NAME = "roles_attribute_name";
+ public static final String ROLE_FUNCTIONS_ATTRIBUTE_NAME = "role_functions_attribute_name";
+ public static final String CLIENT_DEVICE_ATTRIBUTE_NAME = "client_device_attribute_name";
+ public static final String CLIENT_DEVICE_EMULATION = "client_device_emulation";
+ public static final String CLIENT_DEVICE_TYPE_TO_EMULATE = "client_device_type_to_emulate";
+ // File generation - Document
+ public static final String TEMPLATES_PATH = "templates_path";
+ public static final String DOCUMENT_XML_ENCODING = "document_xml_encoding";
+
+ // Transaction
+ public static final String ROUTING_DATASOURCE_KEY = "routing_datasource_key";
+
+ // Document Library keys
+ public static final String DOCLIB_ADMIN_ROLE_ID = "doclib_admin_role_id";
+ public static final String DOCLIB_USER_ROLE_ID = "doclib_user_role_id";
+
+ public static final String SYSTEM_PROPERTIES_FILENAME = "system.properties";
+ public static final String FUSION_PROPERTIES_FILENAME = "fusion.properties";
+ public static final String SUCCESS_TASKS_PROPERTIES_FILENAME = "success_tasks.properties";
+
+ // login methods
+ public static final String LOGIN_METHOD_CSP = "login_method_csp";
+ public static final String LOGIN_METHOD_WEB_JUNCTION = "login_method_web_junction";
+ public static final String LOGIN_METHOD_BACKDOOR = "login_method_backdoor";
+ public static final String LOGIN_METHOD_ATTRIBUTE_NAME = "login_method_attribute_name";
+ public static final String ROLE_FUNCTION_LIST = "role_function_list";
+
+
+ // login error message keys
+ public static final String MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY = "login.error.hrid.empty";
+ public static final String MESSAGE_KEY_LOGIN_ERROR_HEADER_EMPTY = "login.error.header.empty";
+ public static final String MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE = "login.error.user.inactive";
+ public static final String MESSAGE_KEY_LOGIN_ERROR_USER_NOT_FOUND = "login.error.hrid.not-found";
+ public static final String MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED = "login.error.application.locked";
+ public static final String MESSAGE_KEY_AUTOLOGIN_NONE = "webphone.autoimport.nouser";
+ public static final String MESSAGE_KEY_AUTOLOGIN_MULTIPLE = "webphone.autoimport.multiple";
+
+ // Application Mobile capability
+ public static final String MOBILE_ENABLE = "mobile_enable";
+
+ public static final String DATABASE_TIME_ZONE = "db.time_zone";
+
+ public static final String AUTO_USER_IMPORT_ENABLE = "auto_user_import_enable";
+ public static final String AUTO_USER_IMPORT_ROLE = "auto_user_import_role";
+
+ public static final String ITRACKER_EMAIL_SOURCE_ADDRESS = "itracker_email_source_address";
+ public static final String ITRACKER_EMAIL_DISTRIBUTION = "itracker_email_distribution";
+ public static final String ITRACKER_SYSTEM_USER = "itracker_system_user_id";
+
+ public static final String MAIL_SERVER_HOST = "mail_server_host";
+ public static final String MAIL_SERVER_PORT = "mail_server_port";
+
+ // Routing Data Source keys
+ public static final String ROUTING_DATASOURCE_KEY_NON_XA = "NON-XA";
+ public static final String ROUTING_DATASOURCE_KEY_XA = "XA";
+ public static final String QUARTZ_JOB_ENABLED = "quartz_job_enable";
+ public static final String WORKFLOW_EMAIL_SENDER = "workflow_email_sender";
+ public static final String DROOLS_GUVNOR_HOME = "drools.guvnor.home";
+
+ // Hibernate Config
+ public static final String HB_DIALECT = "hb.dialect";
+ public static final String HB_SHOW_SQL = "hb.show_sql";
+ public static final String IDLE_CONNECTION_TEST_PERIOD = "hb.idle_connection_test_period";
+
+ // DataSource
+ public static final String DB_DRIVER = "db.driver";
+ public static final String DB_CONNECTIONURL = "db.connectionURL";
+ public static final String DB_USERNAME = "db.userName";
+ /** @deprecated this variable is used in many places so don't remove */
+ public static final String DB_PASSWOR = "db.password";
+ public static final String DB_PASSWORD = "db.password";
+ public static final String DB_MIN_POOL_SIZE = "db.min_pool_size";
+ public static final String DB_MAX_POOL_SIZE = "db.max_pool_size";
+ public static final String TEST_CONNECTION_ON_CHECKOUT = "db.test_connection_on_checkout";
+ public static final String PREFERRED_TEST_QUERY = "db.preferred_test_query";
+
+ public static final String MYLOGINS_FEED_CRON = "mylogins_feed_cron";
+ public static final String SESSIONTIMEOUT_FEED_CRON = "sessiontimeout_feed_cron";
+ public static final String LOG_CRON = "log_cron";
+
+ public static final String DB_ENCRYPT_FLAG = "db.encrypt_flag";
+
+ // Decryption Key
+ public static final String Decryption_Key = "decryption_key";
+
+ // Logging/Audit Fields
+ public static final String MDC_APPNAME = "AppName";
+ public static final String MDC_REST_PATH = "RestPath";
+ public static final String MDC_REST_METHOD = "RestMethod";
+ public static final String INSTANCE_UUID = "instance_uuid";
+ public static final String MDC_CLASS_NAME = "ClassName";
+ public static final String MDC_LOGIN_ID = "LoginId";
+ public static final String MDC_TIMER = "Timer";
+ public static final String SDK_NAME = "ECOMP_SDK";
+ public static final String ECOMP_REQUEST_ID = "X-ECOMP-RequestID";
+ public static final String PARTNER_NAME = "PartnerName";
+ public static final String FULL_URL = "Full-URL";
+ public static final String AUDITLOG_BEGIN_TIMESTAMP = "AuditLogBeginTimestamp";
+ public static final String AUDITLOG_END_TIMESTAMP = "AuditLogEndTimestamp";
+ public static final String METRICSLOG_BEGIN_TIMESTAMP = "MetricsLogBeginTimestamp";
+ public static final String METRICSLOG_END_TIMESTAMP = "MetricsLogEndTimestamp";
+ public static final String CLIENT_IP_ADDRESS = "ClientIPAddress";
+ public static final String STATUS_CODE = "StatusCode";
+ public static final String RESPONSE_CODE = "ResponseCode";
+ // Component or sub component name
+ public static final String TARGET_ENTITY = "TargetEntity";
+ // API or operation name
+ public static final String TARGET_SERVICE_NAME = "TargetServiceName";
+
+ // Logging Compliance
+ public static final String DOUBLE_WHITESPACE_SEPARATOR = " ";
+ public static final String SINGLE_WHITESPACE_SEPARATOR = " ";
+ public static final String SINGLE_QUOTE = "'";
+ public static final String NA = "N/A";
+ public static final String UNKNOWN = "Unknown";
+ public static final String SECURITY_LOG_TEMPLATE = "Protocol:{0} Security-Event-Type:{1} Login-ID:{2} {3}";
+ public static final String ECOMP_PORTAL_BE = "ECOMP_PORTAL_BE";
+ public static final String PROTOCOL = "PROTOCOL";
+ public static final String SECURIRY_EVENT_TYPE = "SECURIRY_EVENT_TYPE";
+ public static final String LOGIN_ID = "LOGIN_ID";
+ public static final String ACCESSING_CLIENT = "ACCESSING_CLIENT";
+ public static final String RESULT_STR = "RESULT";
+ public static final String ECOMP_PORTAL_FE = "ECOMP_PORTAL_FE";
+ public static final String ADDITIONAL_INFO = "ADDITIONAL_INFO";
+ public static final String INTERFACE_NAME = "INTERFACE_NAME";
+ public static final String USERAGENT_NAME = "user-agent";
+
+ // Protocols
+ public static final String HTTP = "HTTP";
+ public static final String HTTPS = "HTTPS";
+ public static final String SSO_VALUE = "sso";
+
+ public enum RESULT_ENUM {
+ SUCCESS, FAILURE
+ }
+
+ public enum SecurityEventTypeEnum {
+ FE_LOGIN_ATTEMPT, FE_LOGOUT, SSO_LOGIN_ATTEMPT_PHASE_1, SSO_LOGIN_ATTEMPT_PHASE_2, SSO_LOGOUT, LDAP_PHONEBOOK_USER_SEARCH, INCOMING_REST_MESSAGE, OUTGOING_REST_MESSAGE, REST_AUTHORIZATION_CREDENTIALS_MODIFIED, ECOMP_PORTAL_USER_MODIFIED, ECOMP_PORTAL_USER_ADDED, ECOMP_PORTAL_USER_REMOVED, ECOMP_PORTAL_WIDGET, INCOMING_UEB_MESSAGE, ECOMP_PORTAL_HEALTHCHECK
+ }
+
+ // Menu
+ public static final String CONTACT_US_LINK = "contact_us_link";
+
+ // Left Menu
+ public static final String LEFT_MENU_PARENT = "parentList";
+ public static final String LEFT_MENU_CHILDREND = "childItemList";
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.util;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalsdk.core.command.UserRowBean;
+import org.onap.portalsdk.core.domain.User;
+
+public class UsageUtils {
+ @SuppressWarnings("rawtypes")
+ public static ArrayList<UserRowBean> getActiveUsers(HashMap activeUsers) {
+ ArrayList<UserRowBean> rows = new ArrayList<UserRowBean>();
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
+
+ for(Iterator i = activeUsers.keySet().iterator(); i.hasNext(); ){
+ String sessionId = (String)i.next();
+ HttpSession session = (HttpSession)activeUsers.get(sessionId);
+ User userBean = (User)session.getAttribute("user");
+ //
+ // Not all sessions will be valid logins
+ // Skip those ones
+ //
+ if(null == userBean)
+ continue;
+
+ UserRowBean userRow = new UserRowBean();
+ userRow.setFirstName(userBean.getFirstName());
+ userRow.setLastName(userBean.getLastName());
+ userRow.setEmail(userBean.getEmail());
+ userRow.setId(userBean.getId());
+ userRow.setSessionId(sessionId);
+ userRow.setLoginTime(sdf.format(new Date(session.getCreationTime())));
+ userRow.setLastLoginTime(sdf.format(userBean.getLastLoginDate()));
+
+ //
+ // Calculate the last time and time remaining for these sessions.
+ //
+ int sessionLength = session.getMaxInactiveInterval();
+ long now = new java.util.Date().getTime();
+ long lastAccessed = (now - session.getLastAccessedTime()) / 1000;
+ long lengthInactive = (now - session.getLastAccessedTime());
+ long minutesRemaining = sessionLength - (lengthInactive / 1000);
+
+ userRow.setLastAccess((lastAccessed / 60) + ":" + String.format("%02d", (lastAccessed % 60)));
+ userRow.setRemaining((minutesRemaining / 60) + ":" + String.format("%02d", (minutesRemaining % 60)));
+
+ rows.add(userRow);
+ }
+
+ return rows;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public static ArrayList<UserRowBean> getActiveUsersAfterDelete(HashMap activeUsers, final java.lang.Object data) {
+ return getActiveUsers(deleteSession(activeUsers,data));
+
+ }
+
+ @SuppressWarnings("rawtypes")
+ private static HashMap deleteSession(HashMap activeUsers, Object data) {
+ String sessionId = ((UserRowBean)data).getSessionId();
+ HttpSession session = (HttpSession)activeUsers.get(sessionId);
+ session.invalidate();
+ activeUsers.remove(sessionId);
+
+ return activeUsers;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.util;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.Map;
+
+import org.yaml.snakeyaml.Yaml;
+import org.yaml.snakeyaml.representer.Representer;
+
+public class YamlUtils {
+
+ static Yaml yaml;
+
+ static {
+
+ Representer representer = new Representer();
+ //representer.addClassTag(Domain.class, Tag.MAP);
+
+
+ yaml = new Yaml(representer);
+
+ }
+
+ public static void writeYamlFile(String filePath, String fileName,
+ Map<String, Object> model) throws IOException {
+ FileWriter writer = new FileWriter(filePath + File.separator + fileName);
+ yaml.dump(model, writer);
+ writer.close();
+ }
+
+ public static String returnYaml(
+ Map<String, Object> model) throws IOException {
+
+ return yaml.dump(model);
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public static Map<String, Object> readYamlFile(
+ String filePath, String fileName) throws FileNotFoundException,
+ IOException {
+ FileReader reader = new FileReader(filePath + File.separator + fileName);
+
+ Map<String,Object> callFlowBs = (Map<String,Object>)yaml.load(reader);
+ reader.close();
+ return callFlowBs;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.web.socket;
+
+import java.io.IOException;
+import java.util.Hashtable;
+import java.util.Map;
+
+import javax.websocket.OnClose;
+import javax.websocket.OnMessage;
+import javax.websocket.OnOpen;
+import javax.websocket.Session;
+import javax.websocket.server.ServerEndpoint;
+
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@ServerEndpoint("/contact")
+public class PeerBroadcastSocket {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PeerBroadcastSocket.class);
+
+ public static Map<String, Object> channelMap = new Hashtable<String, Object>();
+ public Map<String, String> sessionMap = new Hashtable<String, String>();
+ ObjectMapper mapper = new ObjectMapper();
+
+ @OnMessage
+ public void message(String message, Session session) {
+ try {
+ // JSONObject jsonObject = new JSONObject(message);
+ @SuppressWarnings("unchecked")
+ Map<String, Object> jsonObject = mapper.readValue(message, Map.class);
+ try {
+ Object from = jsonObject.get("from");
+ if (from != null) {
+ channelMap.put(from.toString(), session);
+ sessionMap.put(session.getId(), from.toString());
+ }
+ } catch (Exception je) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to read value" + je.getMessage());
+ }
+
+ try {
+ Object to = jsonObject.get("to");
+ if (to == null)
+ return;
+ Object toSessionObj = channelMap.get(to);
+ if (toSessionObj != null) {
+ Session toSession = null;
+ toSession = (Session) toSessionObj;
+ toSession.getBasicRemote().sendText(message);
+ }
+
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to send text" + ex.getMessage());
+ }
+
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed" + ex.getMessage());
+ }
+
+ }
+
+ @OnOpen
+ public void open(Session session) {
+ logger.info(EELFLoggerDelegate.debugLogger, "Channel opened");
+ }
+
+ @OnClose
+ public void close(Session session) {
+ String channel = sessionMap.get(session.getId());
+ if (channel != null) {
+ Object sessObj = channelMap.get(channel);
+ if (sessObj != null) {
+ try {
+ ((Session) sessObj).close();
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to close" + e.getMessage());
+ }
+ }
+ channelMap.remove(channel);
+ }
+ logger.info(EELFLoggerDelegate.debugLogger, "Channel closed");
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.web.socket;
+
+import java.util.Hashtable;
+import java.util.Map;
+
+import javax.websocket.OnClose;
+import javax.websocket.OnMessage;
+import javax.websocket.OnOpen;
+import javax.websocket.Session;
+import javax.websocket.server.ServerEndpoint;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@ServerEndpoint("/webrtc")
+public class WebRTCSocket {
+
+
+ public static Map<String,Hashtable<String,Object[]>> channelMap = new Hashtable<String,Hashtable<String,Object[]>>();
+ public Map<String,String> sessionMap = new Hashtable<String,String>();
+ ObjectMapper mapper = new ObjectMapper();
+
+
+ @OnMessage
+ public void message(String message, Session session) {
+ try {
+ //JSONObject jsonObject = new JSONObject(message);
+ @SuppressWarnings("unchecked")
+ Map<String,Object> jsonObject = mapper.readValue(message, Map.class);
+ try {
+ Object isOpen = jsonObject.get("open");
+ if(isOpen != null && (Boolean)isOpen == true) {
+ String channel = (String) jsonObject.get("channel");
+ Object value = channelMap.get(channel);
+ Hashtable<String,Object[]> sourceDestMap = null;
+ if(value == null)
+ sourceDestMap = new Hashtable<String,Object[]>();
+ else
+ sourceDestMap = (Hashtable<String,Object[]>) value;
+
+ sourceDestMap.put(session.getId(), new Object[]{session});
+ channelMap.put(channel, sourceDestMap);
+ sessionMap.put(session.getId(), channel);
+
+
+ }
+ }
+ catch (Exception je) {
+ je.printStackTrace();
+ }
+
+ try{
+
+ Object dataObj = jsonObject.get("data");
+ if(dataObj == null)
+ return;
+ Map<String,Object> dataMapObj = ( Map<String,Object>)dataObj;
+ //Object thisUserId = dataMapObj.get("userid");
+ String channel = null;
+ try{
+ Object channelObj = dataMapObj.get("sessionid");
+ if(channelObj != null)
+ channel = (String) channelObj;
+ else
+ channel = (String) jsonObject.get("channel");
+ }
+ catch(Exception json) {
+ json.printStackTrace();
+ }
+
+ /*
+ JSONObject dataMapObj = (JSONObject)dataObj;
+ Object thisUserId = dataMapObj.get("userid");
+ String channel = (String) dataMapObj.get("sessionid");
+ Hashtable<String,Object> sourceDestMap = sessionMap.get(channel);
+
+ if(thisUserId != null && sourceDestMap.get((String)thisUserId) == null) {
+ sourceDestMap.put((String)thisUserId, new Object[] {message, session});
+ }
+
+ for(String userId : sourceDestMap.keySet()){
+ if(!userId.equals(thisUserId)) {
+ Session otherSession = (Session) ((Object[])sourceDestMap.get(userId))[1];
+ otherSession.getBasicRemote().sendText(message);
+ }
+ }
+ */
+
+ Hashtable<String,Object[]> sourceDestMap = channelMap.get(channel);
+ if(sourceDestMap != null)
+ for(String id : sourceDestMap.keySet()){
+ if(!id.equals(session.getId())) {
+ Session otherSession = (Session) ((Object[])sourceDestMap.get(id))[0];
+ if(otherSession.isOpen())
+ otherSession.getBasicRemote().sendText(mapper.writeValueAsString(dataObj));
+ }
+
+ }
+ }
+ catch (Exception je) {
+ je.printStackTrace();
+ }
+
+ }
+ catch (Exception je) {
+ je.printStackTrace();
+ }
+ //System.out.println("Message received:" + message);
+ }
+
+ @OnOpen
+ public void open(Session session) {
+ // System.out.println("Channel opened");
+ }
+
+ @OnClose
+ public void close(Session session) {
+ String channel = sessionMap.get(session.getId());
+ if (channel != null) {
+ channelMap.remove(channel);
+ }
+ // System.out.println("Channel closed");
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.web.support;
+
+import java.io.File;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+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 javax.sql.DataSource;
+
+import org.hibernate.Session;
+import org.onap.portalsdk.core.exception.SessionExpiredException;
+import org.onap.portalsdk.core.objectcache.AbstractCacheManager;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.io.FileSystemResource;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.StringUtils;
+
+
+public class AppUtils {
+
+
+
+ private static DataAccessService dataAccessService;
+
+ private static AbstractCacheManager cacheManager;
+
+ private static boolean applicationLocked;
+
+ private static Hashtable feedback = new Hashtable();
+
+ private static DataSource datasource;
+
+ public static DataSource getDatasource() {
+ return datasource;
+ }
+
+ @Autowired
+ public void setDatasource(DataSource datasource) {
+ AppUtils.datasource = datasource;
+ }
+
+ public AppUtils() {
+ }
+
+ public static HttpSession getSession(HttpServletRequest request) {
+ HttpSession session = null;
+ if (request != null) {
+ session = request.getSession(false);
+ if (session == null) {
+ throw new SessionExpiredException();
+ }
+ } else {
+ throw new SessionExpiredException();
+ }
+ return session;
+ }
+
+ public static List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy) {
+ return getLookupList(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null);
+ } // getLookupList
+
+ public static List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, Session session) {
+ String cacheKey = dbTable + "|" + dbValueCol + "|" + dbLabelCol + "|" + dbFilter + "|" + dbOrderBy;
+ List list = getLookupListFromCache(cacheKey);
+ if (list == null) {
+ list = getDataAccessService().getLookupList(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null);
+ if (list != null) {
+ addLookupListToCache(cacheKey, list);
+ }
+ } // if
+ return list;
+ } // getLookupList
+
+ private static List getLookupListFromCache(String key) {
+ return (List)getObjectFromCache(key);
+ } // getLookupListFromCache
+
+ public static Object getObjectFromCache(String key) {
+ if (isCacheManagerAvailable()) {
+ return getCacheManager().getObject(key);
+ } else {
+ return null;
+ }
+ } // getObjectFromCache
+
+ private static void addLookupListToCache(String key, List list) {
+ addObjectToCache(key, list);
+ } // addLookupListToCache
+
+ public static void addObjectToCache(String key, Object o) {
+ if (isCacheManagerAvailable()) {
+ getCacheManager().putObject(key, o);
+ }
+ } // addObjectToCache
+
+ @Autowired
+ public void setCacheManager(AbstractCacheManager cacheManager) {
+ this.cacheManager = cacheManager;
+ }
+
+ public static AbstractCacheManager getCacheManager() {
+ return cacheManager;
+ }
+
+ public static boolean isCacheManagerAvailable() {
+ return (getCacheManager() != null);
+ }
+
+ public void setFeedback(Hashtable feedback) {
+ this.feedback = feedback;
+ }
+
+ public static boolean isApplicationLocked() {
+ return applicationLocked;
+ }
+
+ public static DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ @Autowired
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ public static void setApplicationLocked(boolean locked) {
+ applicationLocked = locked;
+ }
+
+ public static String getLookupValueByLabel(String label, String dbTable, String dbValueCol, String dbLabelCol) {
+ if (label == null || label.equals("")) {
+ return "";
+ }
+
+ List<org.onap.portalsdk.core.domain.Lookup> lstResult = getLookupListNoCache(dbTable, dbValueCol, dbLabelCol, dbLabelCol + "='" + label.replaceAll("'", "''") + "'", "");
+ if (lstResult == null) {
+ return "";
+ }
+ if (lstResult.size() > 0) {
+ return ((org.onap.portalsdk.core.domain.Lookup)lstResult.toArray()[0]).getValue();
+ } else {
+ return "";
+ }
+ }
+
+ public static String getLookupValueByLabel(String label, List lookupList) {
+ Iterator i = null;
+
+ if (label == null || label.equalsIgnoreCase("")) {
+ return "";
+ }
+
+ if (lookupList == null || lookupList.size() == 0) {
+ return "";
+ }
+
+ i = lookupList.iterator();
+ while (i.hasNext()) {
+ org.onap.portalsdk.core.domain.Lookup lookup = (org.onap.portalsdk.core.domain.Lookup)i.next();
+
+ if (lookup.getLabel().equals(label)) {
+ return lookup.getValue();
+ }
+ }
+
+ return "";
+}
+ public static List getLookupListNoCache(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy) {
+ return getLookupListNoCache(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null);
+ } // getLookupListNoCache
+
+
+ public static List getLookupListNoCache(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, Session session) {
+ return getDataAccessService().getLookupList(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null);
+ } // getLookupListNoCache
+
+
+
+} // AppUtils
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.web.support;
+
+public interface ControllerProperties {
+
+ static final String TASK_GET = "get";
+ static final String TASK_DELETE = "delete";
+ static final String TASK_SAVE = "save";
+ static final String TASK_PROCESS = "process";
+ static final String TASK_TOGGLE_ACTIVE = "toggleActive";
+ static final String TASK_DOWNLOAD = "download";
+ static final String TASK_POPUP = "popup";
+ static final String TASK_LOOKUP = "lookup";
+ static final String TASK_ADD_ROW = "addRow";
+ static final String TASK_APPROVE = "approve";
+ static final String TASK_REJECT = "reject";
+ static final String TASK_RESET = "reset";
+ static final String TASK_ASSIGN = "assign";
+ static final String TASK_CUT = "cut";
+ static final String TASK_COPY = "copy";
+ static final String TASK_PASTE = "paste";
+ static final String TASK_SELECT = "select";
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.web.support;
+
+public class FeedbackMessage {
+
+ private String message;
+ private int messageType;
+ private boolean keyed;
+
+ public static final int MESSAGE_TYPE_ERROR = 10;
+ public static final int MESSAGE_TYPE_WARNING = 20;
+ public static final int MESSAGE_TYPE_INFO = 30;
+ public static final int MESSAGE_TYPE_SUCCESS = 40;
+
+ public static final String DEFAULT_MESSAGE_SUCCESS = "Update successful.";
+ public static final String DEFAULT_MESSAGE_ERROR = "An error occurred while processing the request: ";
+
+ public static final String DEFAULT_MESSAGE_SYSTEM_ADMINISTRATOR = "If the problem persists, please contact your Administrator.";
+
+ public FeedbackMessage() {
+ }
+
+ public FeedbackMessage(String message) {
+ this(message, MESSAGE_TYPE_ERROR);
+ }
+
+ public FeedbackMessage(String message, int messageType) {
+ this(message, messageType, false);
+ }
+
+ public FeedbackMessage(String message, int messageType, boolean keyed) {
+ this.message = message;
+ this.messageType = messageType;
+ this.keyed = keyed;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public int getMessageType() {
+ return messageType;
+ }
+
+ public boolean isKeyed() {
+ return keyed;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public void setMessageType(int messageType) {
+ this.messageType = messageType;
+ }
+
+ public void setKeyed(boolean keyed) {
+ this.keyed = keyed;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.web.support;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class JsonMessage {
+
+ private String data;
+ private String data2;
+ private String data3;
+ public JsonMessage(String data) {
+ super();
+ this.data = data;
+ }
+ public JsonMessage(String data,String data2) {
+ super();
+ this.data = data;
+ this.data2 = data2;
+ }
+
+ public JsonMessage(String data,String data2,String data3) {
+ super();
+ this.data = data;
+ this.data2 = data2;
+ this.data3 = data3;
+ }
+
+ public String getData() {
+ return data;
+ }
+
+ public void setData(String data) {
+ this.data = data;
+ }
+ public String getData2() {
+ return data2;
+ }
+ public void setData2(String data2) {
+ this.data2 = data2;
+ }
+ public String getData3() {
+ return data3;
+ }
+ public void setData3(String data3) {
+ this.data3 = data3;
+ }
+
+
+ /**
+ * Builds JSON object with status + message response body.
+ *
+ * @param success
+ * True to indicate success, false to signal failure.
+ * @param msg
+ * Message to include in the response object; ignored if null.
+ * @return
+ *
+ * <pre>
+ * { "status" : "ok" (or "error"), "message": "some explanation" }
+ * </pre>
+ */
+ public static String buildJsonResponse(boolean success, String msg) {
+ PortalAPIResponse response = new PortalAPIResponse(success, msg);
+ String json = null;
+ try {
+ json = new ObjectMapper().writeValueAsString(response);
+ } catch (JsonProcessingException ex) {
+ // Truly should never, ever happen
+ json = "{ \"status\": \"error\",\"message\":\"" + ex.toString() + "\" }";
+ }
+ return json;
+ }
+
+ /**
+ * Builds JSON object with status of error and message containing stack
+ * trace for the specified throwable.
+ *
+ * @param t
+ * Throwable with stack trace to use as message
+ * @return
+ *
+ * <pre>
+ * { "status" : "error", "message": "some-big-stacktrace" }
+ * </pre>
+ */
+ public static String buildJsonResponse(Throwable t) {
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw);
+ t.printStackTrace(pw);
+ return buildJsonResponse(false, sw.toString());
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.web.support;
+
+import java.util.*;
+
+public class MessagesList {
+
+ private boolean successMessageDisplayed = true;
+ private boolean includeCauseInCustomExceptions = false;
+
+ private List successMessages;
+ private List exceptionMessages;
+
+ public MessagesList() {
+ setExceptionMessages(new ArrayList());
+ setSuccessMessages(new ArrayList());
+ }
+
+ public MessagesList(boolean displaySuccess) {
+ this();
+ setSuccessMessageDisplayed(displaySuccess);
+ }
+
+ public List getExceptionMessages() {
+ return exceptionMessages;
+ }
+
+ public List getSuccessMessages() {
+ return successMessages;
+ }
+
+ public boolean isSuccessMessageDisplayed() {
+ return successMessageDisplayed;
+ }
+
+ public boolean isIncludeCauseInCustomExceptions() {
+ return includeCauseInCustomExceptions;
+ }
+
+
+ public void setExceptionMessages(List exceptionMessages) {
+ this.exceptionMessages = exceptionMessages;
+ }
+
+ public void setSuccessMessages(List successMessages) {
+ this.successMessages = successMessages;
+ }
+
+ public void setSuccessMessageDisplayed(boolean successMessageDisplayed) {
+ this.successMessageDisplayed = successMessageDisplayed;
+ }
+
+ public void setIncludeCauseInCustomExceptions(boolean includeCauseInCustomExceptions) {
+ this.includeCauseInCustomExceptions = includeCauseInCustomExceptions;
+ }
+
+
+ public void addSuccessMessage(FeedbackMessage message) {
+ getSuccessMessages().add(message);
+ }
+
+ public void addExceptionMessage(FeedbackMessage message) {
+ getExceptionMessages().add(message);
+ }
+
+ public boolean hasExceptionMessages() {
+ return!getExceptionMessages().isEmpty();
+ }
+
+ public boolean hasSuccessMessages() {
+ return!getSuccessMessages().isEmpty();
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.web.support;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.UUID;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.RoleFunction;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.exception.SessionExpiredException;
+import org.onap.portalsdk.core.lm.FusionLicenseManager;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.menu.MenuBuilder;
+import org.onap.portalsdk.core.restful.domain.EcompRole;
+import org.onap.portalsdk.core.restful.domain.EcompUser;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+
+@SuppressWarnings("rawtypes")
+public class UserUtils {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserUtils.class);
+
+ public static final String KEY_USER_ROLES_CACHE = "userRoles";
+
+ private static DataAccessService dataAccessService;
+
+ public static void setUserSession(HttpServletRequest request, User user, Set applicationMenuData,
+ Set businessDirectMenuData, String loginMethod , List<RoleFunction> roleFunctionList) {
+ HttpSession session = request.getSession(true);
+
+ UserUtils.clearUserSession(request); // let's clear the current user
+ // session to avoid any
+ // conflicts during the set
+
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME), loginMethod);
+
+ getRoleFunctions(request);
+
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
+ session.setAttribute(SystemProperties.FIRST_NAME, user.getFirstName());
+ session.setAttribute(SystemProperties.LAST_NAME, user.getLastName());
+ session.setAttribute(SystemProperties.ROLE_FUNCTION_LIST, roleFunctionList);
+
+ ServletContext context = session.getServletContext();
+ int licenseVarificationFlag = 3;
+ try {
+ licenseVarificationFlag = (Integer) context.getAttribute("licenseVerification");
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.debugLogger, "Error while get license varification " + e.getMessage());
+ }
+ String displayName = "";
+ if (SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) != null)
+ displayName = SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME);
+ switch (licenseVarificationFlag) {
+ case FusionLicenseManager.DEVELOPER_LICENSE:
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME),
+ displayName + " [Development Version]");
+ break;
+ case FusionLicenseManager.EXPIRED_LICENSE:
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME),
+ displayName + " [LICENSE EXPIRED]");
+ break;
+ case FusionLicenseManager.VALID_LICENSE:
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), displayName);
+ break;
+ default:
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME),
+ displayName + " [INVALID LICENSE]");
+ break;
+ }
+
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME),
+ MenuBuilder.filterMenu(applicationMenuData, request));
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME),
+ MenuBuilder.filterMenu(businessDirectMenuData, request));
+ }
+
+ public static void clearUserSession(HttpServletRequest request) {
+ HttpSession session = AppUtils.getSession(request);
+
+ if (session == null) {
+ throw new SessionExpiredException();
+ }
+
+ // removes all stored attributes from the current user's session
+ session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
+ session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
+ session.removeAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME));
+ session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
+ session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
+ session.removeAttribute(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME));
+ session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTION_LIST));
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public static Set getRoleFunctions(HttpServletRequest request) {
+ HashSet roleFunctions = null;
+// HashSet<RoleFunction> rolefun = null;
+ HttpSession session = request.getSession();
+ roleFunctions = (HashSet) session
+ .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
+
+ if (roleFunctions == null) {
+ HashMap roles = getRoles(request);
+ roleFunctions = new HashSet();
+
+ Iterator i = roles.keySet().iterator();
+
+ while (i.hasNext()) {
+ Long roleKey = (Long) i.next();
+ Role role = (Role) roles.get(roleKey);
+
+ Iterator j = role.getRoleFunctions().iterator();
+
+ while (j.hasNext()) {
+ RoleFunction function = (RoleFunction) j.next();
+ roleFunctions.add(function.getCode());
+ }
+ }
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME),
+ roleFunctions);
+ }
+ return roleFunctions;
+ }
+
+ public static HashMap getRoles(HttpServletRequest request) {
+ HashMap roles = null;
+
+ // HttpSession session = request.getSession();
+ HttpSession session = AppUtils.getSession(request);
+ roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
+
+ // if roles are not already cached, let's grab them from the user
+ // session
+ if (roles == null) {
+ User user = getUserSession(request);
+
+ // get all user roles (including the tree of child roles)
+ roles = getAllUserRoles(user);
+
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME),
+ getAllUserRoles(user));
+ }
+
+ return roles;
+ }
+
+ public static User getUserSession(HttpServletRequest request) {
+ HttpSession session = AppUtils.getSession(request);
+
+ if (session == null) {
+ throw new SessionExpiredException();
+ }
+
+ return (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
+ }
+
+ @SuppressWarnings("unchecked")
+ public static HashMap getAllUserRoles(User user) {
+ HashMap roles = new HashMap();
+ Iterator i = user.getRoles().iterator();
+
+ while (i.hasNext()) {
+ Role role = (Role) i.next();
+
+ if (role.getActive()) {
+ roles.put(role.getId(), role);
+
+ // let's take a recursive trip down the tree to add all child
+ // roles
+ addChildRoles(role, roles);
+ }
+ }
+
+ return roles;
+ }
+
+ @SuppressWarnings("unchecked")
+ private static void addChildRoles(Role role, HashMap roles) {
+ Set childRoles = role.getChildRoles();
+ if (childRoles != null && childRoles.size() > 0) {
+ Iterator j = childRoles.iterator();
+ while (j.hasNext()) {
+ Role childRole = (Role) j.next();
+ if (childRole.getActive()) {
+ roles.put(childRole.getId(), childRole);
+ addChildRoles(childRole, roles);
+ }
+ }
+ }
+
+ }
+
+
+
+ public static boolean hasRole(HttpServletRequest request, String roleKey) {
+ return getRoles(request).keySet().contains(new Long(roleKey));
+ }
+
+ public static boolean hasRole(User user, String roleKey) {
+ return getAllUserRoles(user).keySet().contains(new Long(roleKey));
+ }
+
+ public static boolean isAccessible(HttpServletRequest request, String functionKey) {
+ return getRoleFunctions(request).contains(functionKey);
+ }
+
+ public static String getLoginMethod(HttpServletRequest request) {
+ HttpSession session = AppUtils.getSession(request);
+
+ if (session == null) {
+ throw new SessionExpiredException();
+ }
+
+ return (String) session
+ .getAttribute(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME));
+ }
+
+ public static DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ @Autowired
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ UserUtils.dataAccessService = dataAccessService;
+ }
+
+ public static int getUserId(HttpServletRequest request) {
+ return getUserIdAsLong(request).intValue();
+ }
+
+ public static Long getUserIdAsLong(HttpServletRequest request) {
+ Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
+
+ if (request != null) {
+ if (getUserSession(request) != null) {
+ userId = getUserSession(request).getId();
+ }
+ }
+ return userId;
+ }
+
+ private static final Object stackTraceLock = new Object();
+
+ /**
+ * Serializes a stack trace of the specified throwable and returns it as a
+ * string.
+ *
+ * TODO: why is synchronization required?
+ *
+ * @param t
+ * @return String version of stack trace
+ */
+ public static String getStackTrace(Throwable t) {
+ synchronized (stackTraceLock) {
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw);
+ t.printStackTrace(pw);
+ return sw.toString();
+ }
+ }
+
+ /**
+ * Gets the full URL of the request by joining the request and any query
+ * string.
+ *
+ * @param request
+ * @return Full URL of the request including query parameters
+ */
+ public static String getFullURL(HttpServletRequest request) {
+ if (request != null) {
+ StringBuffer requestURL = request.getRequestURL();
+ String queryString = request.getQueryString();
+
+ if (queryString == null) {
+ return requestURL.toString();
+ } else {
+ return requestURL.append('?').append(queryString).toString();
+ }
+ }
+ return "";
+ }
+
+ /**
+ * Gets or generates a request ID by searching for header X-ECOMP-RequestID.
+ * If not found, generates a new random UUID.
+ *
+ * @param request
+ * @return Request ID for the specified request
+ */
+ public static String getRequestId(HttpServletRequest request) {
+ Enumeration<String> headerNames = request.getHeaderNames();
+
+ String requestId = "";
+ try {
+ while (headerNames.hasMoreElements()) {
+ String headerName = (String) headerNames.nextElement();
+ if (logger.isTraceEnabled())
+ logger.trace(EELFLoggerDelegate.debugLogger, "getRequestId: header {} = {}", headerName,
+ request.getHeader(headerName));
+ if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
+ requestId = request.getHeader(headerName);
+ break;
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.debugLogger, "getRequestId: failed to get headder", e);
+ }
+
+ if (requestId.isEmpty())
+ requestId = UUID.randomUUID().toString();
+ logger.debug(EELFLoggerDelegate.debugLogger, "getRequestId: result is {}", requestId);
+ return requestId;
+ }
+
+ /**
+ * Converts a Hibernate-mapped User object to a JSON-serializable EcompUser
+ * object.
+ *
+ * @param user
+ * @return EcompUser with a subset of fields.
+ */
+ public static EcompUser convertToEcompUser(User user) {
+ EcompUser userJson = new EcompUser();
+ userJson.setEmail(user.getEmail());
+ userJson.setFirstName(user.getFirstName());
+ userJson.setHrid(user.getHrid());
+ userJson.setJobTitle(user.getJobTitle());
+ userJson.setLastName(user.getLastName());
+ userJson.setLoginId(user.getLoginId());
+ userJson.setOrgManagerUserId(user.getOrgManagerUserId());
+ userJson.setMiddleInitial(user.getMiddleInitial());
+ userJson.setOrgCode(user.getOrgCode());
+ userJson.setOrgId(user.getOrgId());
+ userJson.setPhone(user.getPhone());
+ userJson.setOrgUserId(user.getOrgUserId());
+ Set<EcompRole> ecompRoles = new TreeSet<EcompRole>();
+ for (Role role : user.getRoles()) {
+ ecompRoles.add(convertToEcompRole(role));
+ }
+ userJson.setRoles(ecompRoles);
+ return userJson;
+ }
+
+ /**
+ * Converts a Hibernate-mapped Role object to a JSON-serializable EcompRole
+ * object.
+ *
+ * @param role
+ * @return EcompRole with a subset of fields: ID and name
+ */
+ public static EcompRole convertToEcompRole(Role role) {
+ EcompRole ecompRole = new EcompRole();
+ ecompRole.setId(role.getId());
+ ecompRole.setName(role.getName());
+ return ecompRole;
+ }
+
+ }
+
+
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core;
-
-/**
- * <p>
- * Title: FusionObject
- * </p>
- *
- * <p>
- * Description: This interface is implemented by all top-level support classes
- * of each package in FUSION. This allows all top-level support classes to have
- * some commonality for easier maintenance.
- * </p>
- *
- * <p>
- * Copyright: Copyright (c) 2007
- * </p>
- *
- * @version 1.1
- */
-public interface FusionObject {
-
- public class Parameters {
- // HashMap parameters passed to the Service and Dao tiers
- public static final String PARAM_USERID = "userId";
- public static final String PARAM_HTTP_REQUEST = "request";
- public static final String PARAM_FILTERS = "filters";
- public static final String PARAM_CLIENT_DEVICE = "client_device";
- // Request parameters passed in the Web tier
- public static final String REQUEST_PARAM_DISPLAY_SUCCESS_MESSAGE = "display_success_message";
- }
-
- /**
- * <p>
- * Title: FusionObject.Utilities
- * </p>
- *
- * <p>
- * Description: Inner class that has some utility functions available for
- * any class that implements it.
- * </p>
- *
- * <p>
- * Copyright: Copyright (c) 2007
- * </p>
- *
- * @version 1.1
- */
- public class Utilities {
- /**
- * nvl - replaces a string value with an empty string if null.
- *
- * @param s
- * String - the string value that needs to be checked
- * @return String - returns the original string value if not null.
- * Otherwise an empty string ("") is returned.
- */
- public static String nvl(String s) {
- return (s == null) ? "" : s;
- }
-
- /**
- * nvl - replaces a string value with a default value if null.
- *
- * @param s
- * String - the string value that needs to be checked
- * @param sDefault
- * String - the default value
- * @return String - returns the original string value if not null.
- * Otherwise the default value is returned.
- */
- public static String nvl(String s, String sDefault) {
- return nvl(s).equals("") ? sDefault : s;
- }
-
- /**
- * Tests the specified string for nullity.
- *
- * @param a
- * String to test for nullity.
- * @return True if the specified string is null, empty or the 4-character
- * sequence "null" (ignoring case); otherwise false.
- */
- public static boolean isNull(String a) {
- if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null"))
- return true;
- else
- return false;
- }
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.auth;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalsdk.core.command.LoginBean;
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.menu.MenuProperties;
-import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException;
-import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
-import org.openecomp.portalsdk.core.service.LoginService;
-import org.openecomp.portalsdk.core.service.RoleService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.servlet.ModelAndView;
-import org.springframework.web.util.WebUtils;
-
-public abstract class LoginStrategy {
-
- public static final String DEFAULT_SUCCESS_VIEW = "welcome";
- public static final String DEFAULT_FAILURE_VIEW = "login";
- private static final String JSESSIONID = "JSESSIONID";
-
- public static final String EP_SERVICE = "EPService";
- public static final String USER_ID = "UserId";
- public static final String ERROR_MESSAGE_KEY = "error";
-
- @Autowired
- private LoginService loginService;
-
- @Autowired
- RoleService roleService;
-
- public abstract ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception;
-
- public abstract String getUserId(HttpServletRequest request) throws PortalAPIException;
-
- public ModelAndView doExternalLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
- invalidateExistingSession(request);
-
- Map<String, String> model = new HashMap<String, String>();
- LoginBean commandBean = new LoginBean();
- String loginId = request.getParameter("loginId");
- String password = request.getParameter("password");
- commandBean.setLoginId(loginId);
- commandBean.setLoginPwd(password);
- HashMap additionalParamsMap = new HashMap();
-
- // Get the client device type and pass it into LoginService for audit
- // logging.
- /**
- * ClientDeviceType clientDevice = (ClientDeviceType)request.getAttribut
- * (SystemProperties.getProperty(SystemProperties.CLIENT_DEVICE_ATTRIBUTE_NAME));
- * additionalParamsMap.put(Parameters.PARAM_CLIENT_DEVICE,
- * clientDevice);
- **/
- commandBean = loginService.findUser(commandBean,
- (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), additionalParamsMap);
- List<RoleFunction> roleFunctionList= roleService.getRoleFunctions(loginId);
-
-
-
- if (commandBean.getUser() == null) {
- String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage()
- : "login.error.external.invalid";
- model.put("error", loginErrorMessage);
-
- String[] errorCodes = new String[1];
- errorCodes[0] = loginErrorMessage;
-
- return new ModelAndView("login_external", "model", model);
-
- } else {
- // store the currently logged in user's information in the session
- UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
- commandBean.getBusinessDirectMenu(),
- SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_BACKDOOR), roleFunctionList);
- initateSessionMgtHandler(request);
-
- // user has been authenticated, now take them to the welcome page
- // return new ModelAndView("redirect:/profile_search");
- return new ModelAndView("redirect:welcome.htm");
-
- }
- }
-
- protected void invalidateExistingSession(HttpServletRequest request){
- request.getSession().invalidate();
- }
-
- protected String getJessionId(HttpServletRequest request) {
- Cookie ep = WebUtils.getCookie(request, JSESSIONID);
- if (ep == null) {
- return request.getSession().getId();
- }
- return ep.getValue();
-
- }
-
- protected void initateSessionMgtHandler(HttpServletRequest request) {
- String jSessionId = getJessionId(request);
- PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
- }
-
- public LoginService getLoginService() {
- return loginService;
- }
-
- public void setLoginService(LoginService loginService) {
- this.loginService = loginService;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.command;
-
-import java.util.Set;
-
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.domain.support.FusionCommand;
-
-public class LoginBean extends FusionCommand {
-
- private String loginId;
- private String loginPwd;
- private String hrid;
- private String userid;
- private String siteAccess;
- private String loginErrorMessage;
-
- private User user;
- @SuppressWarnings("rawtypes")
- private Set menu;
- @SuppressWarnings("rawtypes")
- private Set businessDirectMenu;
-
- /**
- * getLoginId
- *
- * @return String
- */
- public String getLoginId() {
- return loginId;
- }
-
- /**
- * getLoginPwd
- *
- * @return String
- */
- public String getLoginPwd() {
- return loginPwd;
- }
-
- /**
- * getMenu
- *
- * @return Set
- */
- @SuppressWarnings("rawtypes")
- public Set getMenu() {
- return menu;
- }
-
- /**
- * getUser
- *
- * @return User
- */
- public User getUser() {
- return user;
- }
-
- /**
- * getHrid
- *
- * @return String
- */
- public String getHrid() {
- return hrid;
- }
-
- /**
- * getSiteAccess
- *
- * @return String
- */
- public String getSiteAccess() {
- return siteAccess;
- }
-
- /**
- * getBusinessDirectMenu
- *
- * @return Set
- */
- @SuppressWarnings("rawtypes")
- public Set getBusinessDirectMenu() {
- return businessDirectMenu;
- }
-
- /**
- * getLoginErrorMessage
- *
- * @return String
- */
- public String getLoginErrorMessage() {
- return loginErrorMessage;
- }
-
- /**
- * setLoginId
- *
- * @param loginId String
- */
- public void setLoginId(String loginId) {
- this.loginId = loginId;
- }
-
- /**
- * setLoginPwd
- *
- * @param loginPwd String
- */
- public void setLoginPwd(String loginPwd) {
- this.loginPwd = loginPwd;
- }
-
- @SuppressWarnings("rawtypes")
- public void setMenu(Set menu) {
- this.menu = menu;
- }
-
- /**
- * setUser
- *
- * @param user User
- */
- public void setUser(User user) {
- this.user = user;
- }
-
- /**
- * setHrid
- *
- * @param hrid String
- */
- public void setHrid(String hrid) {
- this.hrid = hrid;
- }
-
- /**
- * setSiteAccess
- *
- * @param siteAccess String
- */
- public void setSiteAccess(String siteAccess) {
- this.siteAccess = siteAccess;
- }
-
- /**
- * setBusinessDirectMenu
- *
- * @param businessDirectMenu Set
- */
- @SuppressWarnings("rawtypes")
- public void setBusinessDirectMenu(Set businessDirectMenu) {
- this.businessDirectMenu = businessDirectMenu;
- }
-
- /**
- * setLoginErrorMessage
- *
- * @param loginErrorMessage String
- */
- public void setLoginErrorMessage(String loginErrorMessage) {
- this.loginErrorMessage = loginErrorMessage;
- }
-
- public String getUserid() {
- return userid;
- }
-
- public void setUserid(String userid) {
- this.userid = userid;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.command;
-
-import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-
-@JsonSerialize
-public class PostDroolsBean {
-
- private String droolsFile;
- private String className;
- private String selectedRules;
-
- public String getDroolsFile() {
- return droolsFile;
- }
- public void setDroolsFile(String droolsFile) {
- this.droolsFile = droolsFile;
- }
- public String getSelectedRules() {
- return selectedRules;
- }
- public void setSelectedRules(String selectedRules) {
- this.selectedRules = selectedRules;
- }
- public String getClassName() {
- return className;
- }
- public void setClassName(String className) {
- this.className = className;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.command;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.command.support.SearchBase;
-import org.openecomp.portalsdk.core.domain.User;
-
-import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-
-@JsonSerialize
-public class PostSearchBean extends SearchBase {
-
- private User user = null;
- private User userOrig = null;
- private String[] selected;
- private String[] postHrid;
- private String[] postOrgUserId;
- private String[] postFirstName;
- private String[] postLastName;
- private String[] postOrgCode;
- private String[] postPhone;
- private String[] postEmail;
- private String[] postAddress1;
- private String[] postAddress2;
- private String[] postCity;
- private String[] postState;
- private String[] postZipCode;
- private String[] postLocationClli;
- private String[] postBusinessCountryCode;
- private String[] postBusinessCountryName;
- private String[] postDepartment;
- private String[] postDepartmentName;
- private String[] postBusinessUnit;
- private String[] postBusinessUnitName;
- private String[] postJobTitle;
- private String[] postOrgManagerUserId;
- private String[] postCommandChain;
- private String[] postCompanyCode;
- private String[] postCompany;
- private String[] postCostCenter;
- private String[] postSiloStatus;
- private String[] postFinancialLocCode;
-
-
- @SuppressWarnings("rawtypes")
- public PostSearchBean() {
- this(null);
- } // PostSearchBean
-
- @SuppressWarnings("rawtypes")
- public PostSearchBean(List items) {
- super(items);
-
- user = new User();
- userOrig = new User();
-
- setSortBy1("");
- setSortBy1Orig("");
-
- //setSortByList(...);
- } // PostSearchBean
-
-
- public String getFirstName() { return user.getFirstName(); }
- public String getLastName() { return user.getLastName(); }
- public String getHrid() { return user.getHrid(); }
- public String getOrgUserId() { return user.getOrgUserId(); }
- public String getOrgCode() { return user.getOrgCode(); }
- public String getEmail() { return user.getEmail(); }
- public String getOrgManagerUserId() { return user.getOrgManagerUserId(); }
-
- public String getFirstNameOrig() { return user.getFirstName(); }
- public String getLastNameOrig() { return user.getLastName(); }
- public String getHridOrig() { return user.getHrid(); }
- public String getOrgUserIdOrig() { return user.getOrgUserId(); }
- public String getOrgCodeOrig() { return user.getOrgCode(); }
- public String getEmailOrig() { return user.getEmail(); }
- public String getOrgManagerUserIdOrig() { return user.getOrgManagerUserId(); }
-
-
- public User getUser() { return user; }
-
- public String[] getPostEmail() {
- return postEmail;
- }
-
- public String[] getPostFirstName() {
- return postFirstName;
- }
-
- public String[] getPostHrid() {
- return postHrid;
- }
-
- public String[] getPostLastName() {
- return postLastName;
- }
-
- public String[] getPostOrgCode() {
- return postOrgCode;
- }
-
- public String[] getPostPhone() {
- return postPhone;
- }
-
- public String[] getPostOrgUserId() {
- return postOrgUserId;
- }
-
- public String[] getSelected() {
- return selected;
- }
-
- public String[] getPostAddress1() {
- return postAddress1;
- }
-
- public String[] getPostBusinessCountryCode() {
- return postBusinessCountryCode;
- }
-
- public String[] getPostCity() {
- return postCity;
- }
-
- public String[] getPostCommandChain() {
- return postCommandChain;
- }
-
- public String[] getPostCompany() {
- return postCompany;
- }
-
- public String[] getPostCompanyCode() {
- return postCompanyCode;
- }
-
- public String[] getPostDepartment() {
- return postDepartment;
- }
-
- public String[] getPostDepartmentName() {
- return postDepartmentName;
- }
-
- public String[] getPostBusinessCountryName() {
- return postBusinessCountryName;
- }
-
- public String[] getPostJobTitle() {
- return postJobTitle;
- }
-
- public String[] getPostLocationClli() {
- return postLocationClli;
- }
-
- public String[] getPostOrgManagerUserId() {
- return postOrgManagerUserId;
- }
-
- public String[] getPostState() {
- return postState;
- }
-
- public String[] getPostZipCode() {
- return postZipCode;
- }
-
- public void setFirstName(String value) { user.setFirstName(value); }
- public void setLastName(String value) { user.setLastName(value); }
- public void setHrid(String value) { user.setHrid(value); }
- public void setOrgUserId(String value) { user.setOrgUserId(value); }
- public void setOrgCode(String value) { user.setOrgCode(value); }
- public void setEmail(String value) { user.setEmail(value); }
- public void setOrgManagerUserId(String value) { user.setOrgManagerUserId(value); }
-
- public void setFirstNameOrig(String value) { userOrig.setFirstName(value); }
- public void setLastNameOrig(String value) { userOrig.setLastName(value); }
- public void setHridOrig(String value) { userOrig.setHrid(value); }
- public void setOrgUserIdOrig(String value) { userOrig.setOrgUserId(value); }
- public void setOrgCodeOrig(String value) { userOrig.setOrgCode(value); }
- public void setEmailOrig(String value) { userOrig.setEmail(value); }
- public void setOrgManagerUserIdOrig(String value) { userOrig.setOrgManagerUserId(value); }
-
- public void setUser(User value) { this.user = value; }
-
- public void setPostEmail(String[] postEmail) {
- this.postEmail = postEmail;
- }
-
- public void setPostFirstName(String[] postFirstName) {
- this.postFirstName = postFirstName;
- }
-
- public void setPostHrid(String[] postHrid) {
- this.postHrid = postHrid;
- }
-
- public void setPostLastName(String[] postLastName) {
- this.postLastName = postLastName;
- }
-
- public void setPostOrgCode(String[] postOrgCode) {
- this.postOrgCode = postOrgCode;
- }
-
- public void setPostPhone(String[] postPhone) {
- this.postPhone = postPhone;
- }
-
- public void setPostOrgUserId(String[] postOrgUserId) {
- this.postOrgUserId = postOrgUserId;
- }
-
- public void setSelected(String[] selected) {
- this.selected = selected;
- }
-
- public void setPostAddress1(String[] postAddress1) {
- this.postAddress1 = postAddress1;
- }
-
- public void setPostBusinessCountryCode(String[] postBusinessCountryCode) {
- this.postBusinessCountryCode = postBusinessCountryCode;
- }
-
- public void setPostCity(String[] postCity) {
- this.postCity = postCity;
- }
-
- public void setPostCommandChain(String[] postCommandChain) {
- this.postCommandChain = postCommandChain;
- }
-
- public void setPostCompany(String[] postCompany) {
- this.postCompany = postCompany;
- }
-
- public void setPostCompanyCode(String[] postCompanyCode) {
- this.postCompanyCode = postCompanyCode;
- }
-
- public void setPostDepartment(String[] postDepartment) {
- this.postDepartment = postDepartment;
- }
-
- public void setPostDepartmentName(String[] postDepartmentName) {
- this.postDepartmentName = postDepartmentName;
- }
-
- public void setPostBusinessCountryName(String[] postBusinessCountryName) {
- this.postBusinessCountryName = postBusinessCountryName;
- }
-
- public void setPostJobTitle(String[] postJobTitle) {
- this.postJobTitle = postJobTitle;
- }
-
- public void setPostLocationClli(String[] postLocationClli) {
- this.postLocationClli = postLocationClli;
- }
-
- public void setPostOrgManagerUserId(String[] postOrgManagerUserId) {
- this.postOrgManagerUserId = postOrgManagerUserId;
- }
-
- public void setPostState(String[] postState) {
- this.postState = postState;
- }
-
- public void setPostZipCode(String[] postZipCode) {
- this.postZipCode = postZipCode;
- }
-
- public String[] getPostAddress2() {
- return postAddress2;
- }
-
- public void setPostAddress2(String[] postAddress2) {
- this.postAddress2 = postAddress2;
- }
-
- public User getUserOrig() {
- return userOrig;
- }
-
- public void setUserOrig(User userOrig) {
- this.userOrig = userOrig;
- }
-
- public String[] getPostBusinessUnit() {
- return postBusinessUnit;
- }
-
- public void setPostBusinessUnit(String[] postBusinessUnit) {
- this.postBusinessUnit = postBusinessUnit;
- }
-
- public String[] getPostBusinessUnitName() {
- return postBusinessUnitName;
- }
-
- public void setPostBusinessUnitName(String[] postBusinessUnitName) {
- this.postBusinessUnitName = postBusinessUnitName;
- }
-
- public String[] getPostCostCenter() {
- return postCostCenter;
- }
-
- public void setPostCostCenter(String[] postCostCenter) {
- this.postCostCenter = postCostCenter;
- }
-
- public String[] getPostSiloStatus() {
- return postSiloStatus;
- }
-
- public void setPostSiloStatus(String[] postSiloStatus) {
- this.postSiloStatus = postSiloStatus;
- }
-
- public String[] getPostFinancialLocCode() {
- return postFinancialLocCode;
- }
-
- public void setPostFinancialLocCode(String[] postFinancialLocCode) {
- this.postFinancialLocCode = postFinancialLocCode;
- }
-
- public void resetSearch() {
- super.resetSearch();
- setUser(new User());
- } // resetSearch
-
-
- public boolean isCriteriaUpdated() {
- if(user==null&&userOrig==null)
- return false;
- else if(user==null||userOrig==null)
- return true;
- else
- return (! (
- Utilities.nvl(user.getFirstName()).equals(Utilities.nvl(userOrig.getFirstName()))&&
- Utilities.nvl(user.getLastName()).equals(Utilities.nvl(userOrig.getLastName()))&&
- //Utilities.nvl(user.getHrid()).equals(Utilities.nvl(userOrig.getHrid()))&&
- Utilities.nvl(user.getOrgUserId()).equals(Utilities.nvl(userOrig.getOrgUserId()))&&
- Utilities.nvl(user.getOrgCode()).equals(Utilities.nvl(userOrig.getOrgCode()))&&
- Utilities.nvl(user.getEmail()).equals(Utilities.nvl(userOrig.getEmail()))&&
- Utilities.nvl(user.getOrgManagerUserId()).equals(Utilities.nvl(userOrig.getOrgManagerUserId()))&&
- true));
- } // isCriteriaUpdated
-
-} // PostSearchBean
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.command;
-
-import org.openecomp.portalsdk.core.domain.User;
-
-public class UserRowBean extends User {
-
- /**
- *
- */
- private static final long serialVersionUID = -2724597119083972190L;
- private String sessionId;
- private String lastAccess;
- private String remaining;
- private String loginTime;
- private String LastLoginTime;
-
-
- public String getLastAccess(){
- return this.lastAccess;
- }
-
-
- public void setLastAccess(String lastAccess){
- this.lastAccess = lastAccess;
- }
-
-
- public String getRemaining(){
- return this.remaining;
- }
-
-
- public void setRemaining(String remaining){
- this.remaining = remaining;
- }
-
-
- public String getSessionId() {
- return sessionId;
- }
-
-
- public void setSessionId(String sessionId) {
- this.sessionId = sessionId;
- }
-
-
- public String getLoginTime() {
- return loginTime;
- }
-
-
- public void setLoginTime(String loginTime) {
- this.loginTime = loginTime;
- }
-
-
- public String getLastLoginTime() {
- return LastLoginTime;
- }
-
-
- public void setLastLoginTime(String lastLoginTime) {
- LastLoginTime = lastLoginTime;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.command.support;
-
-import java.util.*;
-
-import org.openecomp.portalsdk.core.domain.support.FusionCommand;
-
-public abstract class SearchBase extends FusionCommand {
-
- public static String SORT_BY_MODIFIER_DESC = "D";
- public static String SORT_BY_MODIFIER_ASC = "A";
- public static String SORT_BY_MODIFIER_DESC_IMAGE_NAME = "sort_desc.gif";
- public static String SORT_BY_MODIFIER_ASC_IMAGE_NAME = "sort_asc.gif";
-
-
- private String sortBy1 = null;
- private String sortBy2 = null;
- private String sortBy3 = null;
-
- private String sortBy1Orig = null;
- private String sortBy2Orig = null;
- private String sortBy3Orig = null;
-
- private String sortByModifier1 = null;
- private String sortByModifier2 = null;
- private String sortByModifier3 = null;
-
- private String sortByModifier1Orig = null;
- private String sortByModifier2Orig = null;
- private String sortByModifier3Orig = null;
-
- private String accessType = "WRITE"; //null;
-
- private String submitAction = "";
- private String masterId = "";
- private String detailId = "";
-
- private String showResult = "Y";
-
- private SearchResult searchResult = null;
- private boolean sortingUpdated;
-
- @SuppressWarnings("rawtypes")
- public SearchBase(List items) {
- searchResult = (items == null) ? (new SearchResult()) : (new SearchResult(items));
- } // SearchBase
-
-
- public String getSortBy1() {
- return sortBy1;
- }
-
- public String getSortBy2() {
- return sortBy2;
- }
-
- public String getSortBy3() {
- return sortBy3;
- }
-
- public String getSortBy1Orig() {
- return sortBy1;
- }
-
- public String getSortBy2Orig() {
- return sortBy2;
- }
-
- public String getSortBy3Orig() {
- return sortBy3;
- }
-
- public String getAccessType() {
- return accessType;
- }
-
- public String getSubmitAction() {
- return submitAction;
- }
-
- public String getMasterId() {
- return masterId;
- }
-
- public String getDetailId() {
- return detailId;
- }
-
- public String getShowResult() {
- return showResult;
- }
-
- //public ArrayList getSortByList() { return sortByList; }
-
- public SearchResult getSearchResult() {
- return searchResult;
- }
-
- public String getSortByModifier1() {
- return sortByModifier1;
- }
-
- public String getSortByModifier1Orig() {
- return sortByModifier1;
- }
-
- public String getSortByModifier2() {
- return sortByModifier2;
- }
-
- public String getSortByModifier2Orig() {
- return sortByModifier2;
- }
-
- public String getSortByModifier3() {
- return sortByModifier3;
- }
-
- public String getSortByModifier3Orig() {
- return sortByModifier3;
- }
-
- public int getPageNo() {
- return (isCriteriaUpdated() || isSortingUpdated()) ? 0 : getSearchResult().getPageNo();
- }
-
- public int getPageSize() {
- return getSearchResult().getPageSize();
- }
-
- public int getDataSize() {
- return getSearchResult().getDataSize();
- }
-
- public int getNewDataSize() {
- return isCriteriaUpdated() ? -1 : getDataSize();
- }
-
-
- public void setSortBy1(String sortBy1) {
- this.sortBy1 = sortBy1;
- }
-
- public void setSortBy2(String sortBy2) {
- this.sortBy2 = sortBy2;
- }
-
- public void setSortBy3(String sortBy3) {
- this.sortBy3 = sortBy3;
- }
-
- public void setSortBy1Orig(String sortBy1Orig) {
- this.sortBy1Orig = sortBy1Orig;
- }
-
- public void setSortBy2Orig(String sortBy2Orig) {
- this.sortBy2Orig = sortBy2Orig;
- }
-
- public void setSortBy3Orig(String sortBy3Orig) {
- this.sortBy3Orig = sortBy3Orig;
- }
-
- public void setAccessType(String accessType) {
- this.accessType = accessType;
- }
-
- public void setSubmitAction(String submitAction) {
- this.submitAction = submitAction;
- }
-
- public void setMasterId(String masterId) {
- this.masterId = masterId;
- }
-
- public void setDetailId(String detailId) {
- this.detailId = detailId;
- }
-
- public void setShowResult(String showResult) {
- this.showResult = showResult;
- }
-
- public void setSearchResult(SearchResult searchResult) {
- this.searchResult = searchResult;
- }
-
- public void setSortByModifier1(String sortByModifier1) {
- this.sortByModifier1 = sortByModifier1;
- }
-
- public void setSortByModifier1Orig(String sortByModifier1Orig) {
- this.sortByModifier1Orig = sortByModifier1Orig;
- }
-
- public void setSortByModifier2(String sortByModifier2) {
- this.sortByModifier2 = sortByModifier2;
- }
-
- public void setSortByModifier2Orig(String sortByModifier2Orig) {
- this.sortByModifier2Orig = sortByModifier2Orig;
- }
-
- public void setSortByModifier3(String sortByModifier3) {
- this.sortByModifier3 = sortByModifier3;
- }
-
- public void setSortByModifier3Orig(String sortByModifier3Orig) {
- this.sortByModifier3Orig = sortByModifier3Orig;
- }
-
- public void setSortingUpdated(boolean sortingUpdated) {
- this.sortingUpdated = sortingUpdated;
- }
-
- public void setPageNo(int pageNo) {
- getSearchResult().setPageNo(pageNo);
- }
-
- public void setPageSize(int pageSize) {
- getSearchResult().setPageSize(pageSize);
- }
-
- public void setDataSize(int dataSize) {
- getSearchResult().setDataSize(dataSize);
- }
-
-
- public void resetSearch() {
- setSortBy1(null);
- setSortBy2(null);
- setSortBy3(null);
- setSortByModifier1(SearchBase.SORT_BY_MODIFIER_ASC);
- setSortByModifier2(SearchBase.SORT_BY_MODIFIER_ASC);
- setSortByModifier3(SearchBase.SORT_BY_MODIFIER_ASC);
- setPageNo(0);
- setDataSize( -1);
- } // resetSearch
-
-
- public abstract boolean isCriteriaUpdated();
-
- public boolean isSortingUpdated() {
- return (!(Utilities.nvl(sortBy1).equals(Utilities.nvl(sortBy1Orig)) &&
- Utilities.nvl(sortBy2).equals(Utilities.nvl(sortBy2Orig)) &&
- Utilities.nvl(sortBy3).equals(Utilities.nvl(sortBy3Orig)) &&
- Utilities.nvl(sortByModifier1).equals(Utilities.nvl(sortByModifier1Orig)) &&
- Utilities.nvl(sortByModifier2).equals(Utilities.nvl(sortByModifier2Orig)) &&
- Utilities.nvl(sortByModifier3).equals(Utilities.nvl(sortByModifier3Orig))));
- } // isSortingUpdated
-
-} // SearchBase
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.command.support;
-
-import java.util.*;
-
-@SuppressWarnings("rawtypes")
-public class SearchResult extends ArrayList implements java.io.Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -451947878984459011L;
- private int pageNo = 0;
- private int pageSize = 50;
- private int dataSize = -1;
-
- private String accessType = null;
-
- //private boolean empty = true; // Overrides collections [isEmpty] with searchResult present/not present logic
-
-
- public SearchResult() {}
-
- @SuppressWarnings("unchecked")
- public SearchResult(List items) {
- super(items);
- } // SearchResult
-
- /*public SearchResult(boolean empty) {
- this();
- this.empty = empty;
- } // SearchResult*/
-
-
- public int getPageNo() { return pageNo; }
- public int getPageSize() { return pageSize; }
- public int getDataSize() { return dataSize; }
-
- public int getSize() { return size(); } // for Struts bean property access
- //public boolean isEmpty() { return empty; }
-
- public String getAccessType() { return accessType; }
-
- public void setPageNo(int pageNo) { this.pageNo=pageNo; }
- public void setPageSize(int pageSize) { this.dataSize=pageSize; }
- public void setDataSize(int dataSize) { this.dataSize=dataSize; }
-
- public void setAccessType(String accessType) { this.accessType = accessType; }
-
-} // SearchResult
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.conf;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.sql.DataSource;
-
-import org.openecomp.portalsdk.core.interceptor.ResourceInterceptor;
-import org.openecomp.portalsdk.core.interceptor.SessionTimeoutInterceptor;
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.format.AppMessagesEnum;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.menu.MenuBuilder;
-import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.service.DataAccessServiceImpl;
-import org.openecomp.portalsdk.core.service.LocalAccessCondition;
-import org.openecomp.portalsdk.core.service.RestApiRequestBuilder;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Conditional;
-import org.springframework.web.servlet.ViewResolver;
-import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
-import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
-import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
-import org.springframework.web.servlet.view.InternalResourceViewResolver;
-import org.springframework.web.servlet.view.JstlView;
-import org.springframework.web.servlet.view.UrlBasedViewResolver;
-import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
-import org.springframework.web.servlet.view.tiles3.TilesView;
-
-import com.mchange.v2.c3p0.ComboPooledDataSource;
-
-/**
- * Configures Spring features in the ECOMP Portal SDK including request
- * interceptors and view resolvers. Application should subclass and override
- * methods as needed.
- */
-public class AppConfig extends WebMvcConfigurerAdapter implements Configurable, ApplicationContextAware {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppConfig.class);
-
- private final List<String> tileDefinitions = new ArrayList<String>();
- protected ApplicationContext appApplicationContext = null;
-
- public AppConfig() {
- // loads all default fields and marks logging
- // has been started for each log file type.
- initGlobalLocalContext();
- }
-
- /**
- * Creates and returns a new instance of a secondary (order=2)
- * {@link ViewResolver} that finds files by adding prefix "/WEB-INF/jsp/"
- * and suffix ".jsp" to the base view name.
- *
- * @return New instance of {@link ViewResolver}.
- */
- @Bean
- public ViewResolver viewResolver() {
- InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
- viewResolver.setViewClass(JstlView.class);
- viewResolver.setPrefix("/WEB-INF/jsp/");
- viewResolver.setSuffix(".jsp");
- viewResolver.setOrder(2);
- return viewResolver;
- }
-
- /**
- * Loads all the default logging fields into the global MDC context and
- * marks each log file type that logging has been started.
- */
- private void initGlobalLocalContext() {
- logger.init();
- }
-
- /*
- * Any requests from the url pattern /static/**, Spring will look for the
- * resources from the /static/ Same as <mvc:resources mapping="/static/**"
- * location="/static/"/> in xml
- */
- @Override
- public void addResourceHandlers(ResourceHandlerRegistry registry) {
- // registry.addResourceHandler("/static/**").addResourceLocations("/static/");
- registry.addResourceHandler("/**").addResourceLocations("/");
- }
-
- /**
- * Creates and returns a new instance of a {@link DataAccessService} class.
- *
- * @return New instance of {@link DataAccessService}.
- */
- @Bean
- public DataAccessService dataAccessService() {
- return new DataAccessServiceImpl();
- }
-
- /**
- * Creates and returns a new instance of a {@link SystemProperties} class.
- *
- * @return New instance of {@link SystemProperties}.
- */
- @Bean
- public SystemProperties systemProperties() {
- return new SystemProperties();
- }
-
- /**
- * Creates and returns a new instance of a {@link MenuBuilder} class.
- *
- * @return New instance of {@link MenuBuilder}.
- */
- @Bean
- public MenuBuilder menuBuilder() {
- return new MenuBuilder();
- }
-
- /**
- * Creates and returns a new instance of a {@link UserUtils} class.
- *
- * @return New instance of {@link UserUtils}.
- */
- @Bean
- public UserUtils userUtil()
- {
- return new UserUtils();
- }
-
- /**
- * Creates and returns a new instance of an {@link AppUtils} class.
- *
- * @return New instance of {@link AppUtils}.
- */
- @Bean
- public AppUtils appUtils() {
- return new AppUtils();
- }
-
- /**
- * Creates and returns a new instance of a {@link TilesConfigurer} class.
- *
- * @return New instance of {@link TilesConfigurer}.
- */
- @Bean
- public TilesConfigurer tilesConfigurer() {
- TilesConfigurer tilesConfigurer = new TilesConfigurer();
- tilesConfigurer.setDefinitions(tileDefinitions());
- tilesConfigurer.setCheckRefresh(true);
- return tilesConfigurer;
- }
-
- /**
- *
- * Creates the Application Data Source.
- *
- * @return DataSource Object
- * @throws Exception
- * on failure to create data source object
- */
- @Bean
- public DataSource dataSource() throws Exception {
-
- systemProperties();
-
- ComboPooledDataSource dataSource = new ComboPooledDataSource();
- try {
- dataSource.setDriverClass(SystemProperties.getProperty(SystemProperties.DB_DRIVER));
- dataSource.setJdbcUrl(SystemProperties.getProperty(SystemProperties.DB_CONNECTIONURL));
- dataSource.setUser(SystemProperties.getProperty(SystemProperties.DB_USERNAME));
- String password = SystemProperties.getProperty(SystemProperties.DB_PASSWORD);
- if (SystemProperties.containsProperty(SystemProperties.DB_ENCRYPT_FLAG)) {
- String encryptFlag = SystemProperties.getProperty(SystemProperties.DB_ENCRYPT_FLAG);
- if (encryptFlag != null && encryptFlag.equalsIgnoreCase("true")) {
- password = CipherUtil.decrypt(password);
- }
- }
- dataSource.setPassword(password);
- dataSource
- .setMinPoolSize(Integer.parseInt(SystemProperties.getProperty(SystemProperties.DB_MIN_POOL_SIZE)));
- dataSource
- .setMaxPoolSize(Integer.parseInt(SystemProperties.getProperty(SystemProperties.DB_MAX_POOL_SIZE)));
- dataSource.setIdleConnectionTestPeriod(
- Integer.parseInt(SystemProperties.getProperty(SystemProperties.IDLE_CONNECTION_TEST_PERIOD)));
- dataSource.setTestConnectionOnCheckout(getConnectionOnCheckout());
- dataSource.setPreferredTestQuery(getPreferredTestQuery());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Error initializing database, verify database settings in properties file: "
- + UserUtils.getStackTrace(e),
- AlarmSeverityEnum.CRITICAL);
- logger.error(EELFLoggerDelegate.debugLogger,
- "Error initializing database, verify database settings in properties file: "
- + UserUtils.getStackTrace(e),
- AlarmSeverityEnum.CRITICAL);
- // Raise an alarm that opening a connection to the database failed.
- logger.logEcompError(AppMessagesEnum.BeDaoSystemError);
- throw e;
- }
- return dataSource;
- }
-
- /**
- * Gets the value of the property
- * {@link SystemProperties#PREFERRED_TEST_QUERY}; defaults to "Select 1" if
- * the property is not defined.
- *
- * @return String value that is a SQL query
- */
- private String getPreferredTestQuery() {
- // Use simple default
- String preferredTestQueryStr = "SELECT 1";
- if (SystemProperties.containsProperty(SystemProperties.PREFERRED_TEST_QUERY)) {
- preferredTestQueryStr = SystemProperties.getProperty(SystemProperties.PREFERRED_TEST_QUERY);
- logger.debug(EELFLoggerDelegate.debugLogger, "getPreferredTestQuery: property key {} value is {}",
- SystemProperties.PREFERRED_TEST_QUERY, preferredTestQueryStr);
- } else {
- logger.info(EELFLoggerDelegate.errorLogger,
- "getPreferredTestQuery: property key {} not found, using default value {}",
- SystemProperties.PREFERRED_TEST_QUERY, preferredTestQueryStr);
- }
- return preferredTestQueryStr;
- }
-
- /**
- * Gets the value of the property
- * {@link SystemProperties#TEST_CONNECTION_ON_CHECKOUT}; defaults to true if
- * the property is not defined.
- *
- * @return Boolean value
- */
- private Boolean getConnectionOnCheckout() {
- // Default to true, always test connection
- boolean testConnectionOnCheckout = true;
- if (SystemProperties.containsProperty(SystemProperties.TEST_CONNECTION_ON_CHECKOUT)) {
- testConnectionOnCheckout = Boolean
- .valueOf(SystemProperties.getProperty(SystemProperties.TEST_CONNECTION_ON_CHECKOUT));
- logger.debug(EELFLoggerDelegate.debugLogger, "getConnectionOnCheckout: property key {} value is {}",
- SystemProperties.TEST_CONNECTION_ON_CHECKOUT, testConnectionOnCheckout);
- } else {
- logger.info(EELFLoggerDelegate.errorLogger,
- "getConnectionOnCheckout: property key {} not found, using default value {}",
- SystemProperties.TEST_CONNECTION_ON_CHECKOUT, testConnectionOnCheckout);
- }
- return testConnectionOnCheckout;
- }
-
- /*
- * TODO: Check whether it is appropriate to extend the list of tile
- * definitions at every invocation.
- */
- protected String[] tileDefinitions() {
- tileDefinitions.add("/WEB-INF/fusion/defs/definitions.xml");
- tileDefinitions.addAll(addTileDefinitions());
-
- return tileDefinitions.toArray(new String[0]);
- }
-
- /**
- * Creates and returns a new empty list. This method should be overridden by
- * child classes.
- *
- * @return An empty list.
- */
- public List<String> addTileDefinitions() {
- return new ArrayList<String>();
- }
-
- /**
- * Creates and returns a new instance of a primary (order=1)
- * {@link UrlBasedViewResolver} that finds files using the contents of
- * definitions.xml files.
- *
- * @return New instance of {@link UrlBasedViewResolver}
- */
- @Bean
- public UrlBasedViewResolver tileViewResolver() {
- UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
- viewResolver.setViewClass(TilesView.class);
- viewResolver.setOrder(1);
- return viewResolver;
- }
-
- /**
- * Adds new instances of the following interceptors to the specified
- * interceptor registry: {@link SessionTimeoutInterceptor},
- * {@link ResourceInterceptor}
- */
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- registry.addInterceptor(new SessionTimeoutInterceptor())
- .excludePathPatterns(getExcludeUrlPathsForSessionTimeout());
- registry.addInterceptor(resourceInterceptor());
- }
-
- /**
- * Creates and returns a new instance of a {@link ResourceInterceptor}.
- *
- * @return New instance of {@link ResourceInterceptor}
- */
- @Bean
- public ResourceInterceptor resourceInterceptor() {
- return new ResourceInterceptor();
- }
-
- private String[] excludeUrlPathsForSessionTimeout = {};
-
- /**
- * Gets the array of Strings that are paths excluded for session timeout.
- *
- * @return Array of String
- */
- public String[] getExcludeUrlPathsForSessionTimeout() {
- return excludeUrlPathsForSessionTimeout;
- }
-
- /**
- * Sets the array of Strings that are paths excluded for session timeout.
- *
- * @param excludeUrlPathsForSessionTimeout
- * Paths to exclude
- */
- public void setExcludeUrlPathsForSessionTimeout(final String... excludeUrlPathsForSessionTimeout) {
- this.excludeUrlPathsForSessionTimeout = excludeUrlPathsForSessionTimeout;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.springframework.context.ApplicationContextAware#setApplicationContext
- * (org.springframework.context.ApplicationContext)
- */
- @Override
- public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
- appApplicationContext = applicationContext;
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.conf;
-
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.core.env.ConfigurableEnvironment;
-import org.springframework.web.context.WebApplicationContext;
-import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
-
-public abstract class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppInitializer.class);
- private final String activeProfile = "src";
-
- @Override
- protected WebApplicationContext createServletApplicationContext() {
- WebApplicationContext context = super.createServletApplicationContext();
-
- try {
-
- ((ConfigurableEnvironment) context.getEnvironment()).setActiveProfiles(activeProfile);
- } catch (Exception e) {
-
- logger.error(EELFLoggerDelegate.errorLogger, "Unable to set the active profile" + e.getMessage(),AlarmSeverityEnum.MAJOR);
- throw e;
-
- }
-
- return context;
- }
-
- @Override
- protected Class<?>[] getRootConfigClasses() {
- return null;
- }
-
- @Override
- protected Class<?>[] getServletConfigClasses() {
-
- return new Class[] { AppConfig.class };
- }
-
- /*
- * URL request will direct to the Spring dispatcher for processing
- */
- @Override
- protected String[] getServletMappings() {
- return new String[] { "/" };
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.conf;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.springframework.web.servlet.ViewResolver;
-import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
-
-public interface Configurable {
-
- public ViewResolver viewResolver();
-
- public void addResourceHandlers(ResourceHandlerRegistry registry) ;
-
- public DataAccessService dataAccessService();
-
- public List<String> addTileDefinitions();
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.conf;
-
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.sql.DataSource;
-
-import org.hibernate.SessionFactory;
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.orm.hibernate4.HibernateTransactionManager;
-import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
-import org.springframework.transaction.annotation.EnableTransactionManagement;
-
-import com.mchange.v2.c3p0.ComboPooledDataSource;
-
-@Configuration
-@EnableTransactionManagement
-public class HibernateConfiguration {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HibernateConfiguration.class);
-
- @Autowired
- private HibernateMappingLocatable hbMappingLocatable;
-
- @Autowired
- private DataSource dataSource;
-
- @Bean
- public LocalSessionFactoryBean sessionFactory() {
- LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
- sessionFactory.setDataSource(dataSource);
- sessionFactory.setPackagesToScan(hbMappingLocatable.getPackagesToScan());
- sessionFactory.setHibernateProperties(getHibernateProperties());
- sessionFactory.setMappingLocations(hbMappingLocatable.getMappingLocations());
- return sessionFactory;
- }
-
- /**
- * Builds a properties object with Hibernate properties in te system.properties file.
- *
- * @return Properties object
- */
- private Properties getHibernateProperties() {
- Properties properties = new Properties();
- properties.put("hibernate.dialect", SystemProperties.getProperty(SystemProperties.HB_DIALECT));
- properties.put("hibernate.show_sql", SystemProperties.getProperty(SystemProperties.HB_SHOW_SQL));
- return properties;
- }
-
- @SuppressWarnings("rawtypes")
- @Bean
- public Map dataSourceMap() throws Exception {
- Connection conn = null;
- Statement stmt = null;
- Map<String, ComboPooledDataSource> dataSourceMap = new HashMap<String, ComboPooledDataSource>();
-
- try {
- conn = dataSource.getConnection();
- stmt = conn.createStatement();
- String sql;
- sql = "SELECT schema_id,datasource_type,connection_url,user_name,password,driver_class,min_pool_size,max_pool_size,idle_connection_test_period FROM schema_info";
- ResultSet rs = stmt.executeQuery(sql);
-
- while (rs.next()) {
- ComboPooledDataSource dataSource = new ComboPooledDataSource();
- dataSource.setDriverClass(rs.getString("driver_class"));
- dataSource.setJdbcUrl(rs.getString("connection_url"));
- dataSource.setUser(rs.getString("user_name"));
- dataSource.setPassword(rs.getString("password"));
- dataSource.setMinPoolSize(rs.getInt("min_pool_size"));
- dataSource.setMaxPoolSize(rs.getInt("max_pool_size"));
- dataSource.setIdleConnectionTestPeriod(rs.getInt("idle_connection_test_period"));
- dataSourceMap.put(rs.getString("schema_id"), dataSource);
- }
- rs.close();
- stmt.close();
- conn.close();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Error initializing database, verify database settings in properties file: " + e.getMessage(),
- AlarmSeverityEnum.CRITICAL);
- e.printStackTrace();
- dataSourceMap = null;
- throw e;
- } finally {
- try {
- if (stmt != null)
- stmt.close();
- } catch (SQLException se2) {
- }
- try {
- if (conn != null)
- conn.close();
- } catch (SQLException se) {
- se.printStackTrace();
- }
- }
-
- return dataSourceMap;
- }
-
- @Bean
- @Autowired
- public HibernateTransactionManager transactionManager(SessionFactory s) {
- HibernateTransactionManager txManager = new HibernateTransactionManager();
- txManager.setSessionFactory(s);
- return txManager;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.conf;
-
-import org.springframework.core.io.Resource;
-
-/**
- * Defines methods used by developers to supply Hibernate configuration.
- */
-public interface HibernateMappingLocatable {
-
- /**
- * Gets Hibernate mapping locations.
- *
- * @return Array of Resource objects (usually ClassPathResource that's a
- * file) which contain Hibernate mapping information.
- */
- public Resource [] getMappingLocations();
-
- /**
- * Gets package names.
- *
- * @return Array of Java package names to scan for classes with Hibernate annotations.
- */
- public String [] getPackagesToScan();
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.controller;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
-import org.openecomp.portalsdk.core.domain.MenuData;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.interfaces.SecurityInterface;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.menu.MenuBuilder;
-import org.openecomp.portalsdk.core.service.AppService;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.service.FnMenuService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.ModelAttribute;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Controller
-public abstract class FusionBaseController implements SecurityInterface{
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FusionBaseController.class);
-
- @Override
- public boolean isAccessible() {
- return true;
- }
-
- public boolean isRESTfulCall(){
- return true;
- }
- @Autowired
- private FnMenuService fnMenuService;
-
- @Autowired
- private MenuBuilder menuBuilder;
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @Autowired
- AppService appService;
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @ModelAttribute("menu")
- public Map<String, Object> getMenu(HttpServletRequest request) {
- HttpSession session = null;
- Map<String, Object> model = new HashMap<String, Object>();
- try {
- try {
- String appName = appService.getDefaultAppName();
- if (appName==null || appName=="") {
- appName = SystemProperties.SDK_NAME;
- }
- logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, appName);
- } catch (Exception e) {
- }
-
- session = request.getSession();
- User user = UserUtils.getUserSession(request);
- if(session!=null && user!=null){
- Set<MenuData> menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
- if(menuResult==null){
- Set appMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME),dataAccessService);
- session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME), MenuBuilder.filterMenu(appMenu, request));
- menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
- }
- model = setMenu(menuResult);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- }
- return model;
- }
-
- public Map<String, Object> setMenu(Set<MenuData> menuResult) throws Exception{
- ObjectMapper mapper = new ObjectMapper();
- List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>();;
- List<MenuData> parentList = new ArrayList<MenuData>();;
- Map<String, Object> model = new HashMap<String, Object>();
- try{
- fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult);
- }catch(Exception e){
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- }
- model.put("childItemList",childItemList!=null?mapper.writeValueAsString(childItemList):"");
- model.put("parentList",parentList!=null?mapper.writeValueAsString(parentList):"");
- return model;
- }
-
- public MenuBuilder getMenuBuilder() {
- return menuBuilder;
- }
-
- public void setMenuBuilder(MenuBuilder menuBuilder) {
- this.menuBuilder = menuBuilder;
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.controller;
-
-public class RestrictedBaseController extends FusionBaseController{
-
- protected String viewName;
- private String exceptionView;
- @Override
- public boolean isAccessible() {
- return false;
- }
- @Override
- public boolean isRESTfulCall(){
- return false;
- }
- protected String getViewName() {
- return viewName;
- }
- protected void setViewName(String viewName) {
- this.viewName = viewName;
- }
-
- public String getExceptionView() {
- return (exceptionView == null) ? "runtime_error_handler" : exceptionView;
- }
-
- public void setExceptionView(String exceptionView) {
- this.exceptionView = exceptionView;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.controller;
-
-public class RestrictedRESTfulBaseController extends FusionBaseController{
-
- protected String viewName;
- private String exceptionView;
- @Override
- public boolean isAccessible() {
- return false;
- }
- @Override
- public boolean isRESTfulCall(){
- return true;
- }
- protected String getViewName() {
- return viewName;
- }
- protected void setViewName(String viewName) {
- this.viewName = viewName;
- }
-
- public String getExceptionView() {
- return (exceptionView == null) ? "runtime_error_handler" : exceptionView;
- }
-
- public void setExceptionView(String exceptionView) {
- this.exceptionView = exceptionView;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.controller;
-
-public class UnRestrictedBaseController extends FusionBaseController{
- protected String viewName;
-
- @Override
- public boolean isAccessible() {
- return true;
- }
- @Override
- public boolean isRESTfulCall(){
- return false;
- }
- protected String getViewName() {
- return viewName;
- }
-
- protected void setViewName(String viewName) {
- this.viewName = viewName;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.dao;
-import java.io.Serializable;
-import java.lang.reflect.ParameterizedType;
-
-import org.hibernate.Criteria;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
-public abstract class AbstractDao<PK extends Serializable, T> {
-
- private final Class<T> persistentClass;
-
- @SuppressWarnings("unchecked")
- public AbstractDao(){
- this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
- }
-
- @Autowired
- private SessionFactory sessionFactory;
-
- protected Session getSession(){
- return sessionFactory.getCurrentSession();
- }
-
- @SuppressWarnings("unchecked")
- public T getByKey(PK key) {
- return (T) getSession().get(persistentClass, key);
- }
-
- public void persist(T entity) {
- getSession().persist(entity);
- }
-
- public void delete(T entity) {
- getSession().delete(entity);
- }
-
- protected Criteria createEntityCriteria(){
- return getSession().createCriteria(persistentClass);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.dao;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.domain.Profile;
-
-public interface ProfileDao {
- List<Profile> findAll();
- Profile getProfile(int id);
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.dao;
-
-import java.util.List;
-
-import org.hibernate.Criteria;
-import org.hibernate.criterion.Restrictions;
-import org.openecomp.portalsdk.core.dao.AbstractDao;
-import org.openecomp.portalsdk.core.domain.Profile;
-import org.springframework.stereotype.Repository;
-
-@Repository("profileDao")
-public class ProfileDaoImpl extends AbstractDao<Integer, Profile> implements ProfileDao{
-
-
- public List<Profile> findAll() {
- Criteria crit = getSession().createCriteria(Profile.class);
- @SuppressWarnings("unchecked")
- List<Profile> p = crit.list();
-
- return p;
- }
-
-
- public Profile getProfile(int id) {
- Criteria crit = getSession().createCriteria(Profile.class);
- crit.add(Restrictions.eq("id", id));
- Profile profile = (Profile) crit.uniqueResult();
-
- return profile;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.dao.hibernate;
-
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.hibernate.Criteria;
-import org.hibernate.FetchMode;
-import org.hibernate.Query;
-import org.hibernate.SQLQuery;
-import org.hibernate.Session;
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Order;
-import org.hibernate.criterion.ProjectionList;
-import org.hibernate.type.LongType;
-import org.openecomp.portalsdk.core.dao.support.FusionDao;
-import org.openecomp.portalsdk.core.domain.Lookup;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-
-public abstract class ModelOperationsCommon extends FusionDao {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ModelOperationsCommon.class);
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public List _getList(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex, String orderBy) {
- List list = null;
- String className = domainClass.getName();
-
- Session session = getSessionFactory().getCurrentSession();
-
- logger.info(EELFLoggerDelegate.debugLogger, "Getting " + className.toLowerCase() + " records"
- + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "")
- + "...");
-
-
- if (filterClause != null && filterClause.length() > 0) {
- logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause);
-
- }
-
- list = session.createQuery("from " + className + Utilities.nvl(filterClause, "")
- + ((orderBy != null) ? " order by " + orderBy : "")).list();
- list = (fromIndex != null) ? list.subList(fromIndex.intValue() - 1, toIndex.intValue()) : list;
-
- if (orderBy == null && list != null) {
- Collections.sort(list);
- }
-
- return list;
- }
-
- public List<?> _getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
- List<Order> orderByList) {
- return _getList(domainClass, projectionsList, restrictionsList, orderByList, null);
- }
-
- public List<?> _getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
- List<Order> orderByList, HashMap<String, FetchMode> fetchModeMap) {
-
- Session session = getSessionFactory().getCurrentSession();
-
- Criteria criteria = session.createCriteria(domainClass);
-
- if (projectionsList != null) {
- criteria.setProjection(projectionsList);
- }
-
- if (restrictionsList != null && !restrictionsList.isEmpty()) {
- for (Criterion criterion : restrictionsList)
- criteria.add(criterion);
- }
-
- if (orderByList != null && !orderByList.isEmpty()) {
- for (Order order : orderByList)
- criteria.addOrder(order);
- }
-
- if (fetchModeMap != null) {
- Iterator<String> itr = fetchModeMap.keySet().iterator();
- String key = null;
- while (itr.hasNext()) {
- key = itr.next();
- criteria.setFetchMode(key, fetchModeMap.get(key));
- }
-
- }
- return criteria.list();
- }
-
- @SuppressWarnings("rawtypes")
- public DomainVo _get(Class domainClass, Serializable id) {
- DomainVo vo = null;
-
- Session session = getSessionFactory().getCurrentSession();
-
- logger.info(EELFLoggerDelegate.debugLogger, "Getting " + domainClass.getName() + " record for id - " + id.toString());
-
-
- vo = (DomainVo) session.get(domainClass, id);
-
- if (vo == null) {
- try {
- vo = (DomainVo) domainClass.newInstance();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed while instantiating a class of " + domainClass.getName() + e.getMessage());
-
- }
- }
-
- return vo;
- }
-
- @SuppressWarnings("rawtypes")
- public List _getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy,
- HashMap additionalParams) {
- logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list...");
-
- List list = null;
- String dbOrderByCol = dbOrderBy;
-
- Session session = getSessionFactory().getCurrentSession();
-
- // default the orderBy if null;
- if (Utilities.nvl(dbOrderBy).length() == 0) {
- dbOrderByCol = dbLabelCol;
- dbOrderBy = dbLabelCol;
- } else {
- if (dbOrderBy.lastIndexOf(" ") > -1) {
- dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" "));
- }
- }
-
- StringBuffer sql = new StringBuffer();
-
- sql.append("select distinct ").append(dbLabelCol).append(" as lab, ").append(dbValueCol).append(" as val, ")
- .append(dbOrderByCol).append(" as sortOrder ").append("from ").append(dbTable).append(" ")
- .append((Utilities.nvl(dbFilter).length() == 0) ? "" : (" where " + dbFilter)).append(" order by ")
- .append(dbOrderBy);
-
- try {
- list = session.createSQLQuery(sql.toString()).addEntity(Lookup.class).list();
- } catch (Exception e) {
- list = null;
- logger.info(EELFLoggerDelegate.debugLogger, "The results for the lookup list query [" + sql + "] were empty.");
- }
-
- return list;
- } // getLookupList
-
- /* This method is used to execute SQL queries */
- @SuppressWarnings("rawtypes")
- protected final List _executeSQLQuery(String sql, Class domainClass) {
- return _executeSQLQuery(sql, domainClass, null, null);
- }
-
- /* This method is used to execute SQL queries with paging */
- @SuppressWarnings("rawtypes")
- protected final List _executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex) {
- Session session = getSessionFactory().getCurrentSession();
-
- SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass);
-
- if (fromIndex != null && toIndex != null) {
- query.setFirstResult(fromIndex.intValue());
- int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
- query.setMaxResults(pageSize);
- }
-
- return query.list();
- }
-
- /* This method is used to execute HQL queries */
- @SuppressWarnings("rawtypes")
- protected final List _executeQuery(String sql) {
- return _executeQuery(sql, null, null);
- }
-
- /* This method is used to execute HQL queries with paging */
- @SuppressWarnings("rawtypes")
- protected final List _executeQuery(String sql, Integer fromIndex, Integer toIndex) {
- Session session = getSessionFactory().getCurrentSession();
-
- Query query = session.createQuery(sql);
-
- if (fromIndex != null && toIndex != null) {
- query.setFirstResult(fromIndex.intValue());
- int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
- query.setMaxResults(pageSize);
- }
-
- return query.list();
- }
-
- /*
- * This method can be used to execute both HQL or SQL named queries. The
- * distinction will come in the hbm.xml mapping file defining the named
- * query. Named HQL queries use the <query> tag while named SQL queries use
- * the <sql-query> tag.
- */
- @SuppressWarnings("rawtypes")
- protected final List _executeNamedQuery(String queryName, Map params) {
- return _executeNamedQuery(queryName, params, null, null);
- }
-
- /*
- * This method can be used to execute both HQL or SQL named queries with
- * paging. The distinction will come in the hbm.xml mapping file defining
- * the named query. Named HQL queries use the <query> tag while named SQL
- * queries use the <sql-query> tag.
- */
- @SuppressWarnings("rawtypes")
- protected final List _executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex) {
- Session session = getSessionFactory().getCurrentSession();
- Query query = session.getNamedQuery(queryName);
- bindQueryParameters(query, params);
- if (fromIndex != null && toIndex != null) {
- query.setFirstResult(fromIndex.intValue());
- int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
- query.setMaxResults(pageSize);
- }
- return query.list();
- }
-
- // RAPTOR ZK
- /*
- * This method can be used to execute both HQL or SQL named queries with
- * paging. The distinction will come in the hbm.xml mapping file defining
- * the named query. Named HQL queries use the <query> tag while named SQL
- * queries use the <sql-query> tag.
- */
- @SuppressWarnings("rawtypes")
- protected final List _executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params) {
- Session session = getSessionFactory().getCurrentSession();
- Query query = session.getNamedQuery(queryName);
- String queryStr = query.getQueryString();
- StringBuffer modifiedSql = new StringBuffer(" select count(*) as countRows from (" + queryStr + " ) al ");
- if (whereClause != null && whereClause.length() > 0)
- modifiedSql.append("where " + whereClause);
- // SQLQuery sqlQuery = session.createSQLQuery(" select count(*) as
- // {reportSearch.countRows} from ("+ modifiedSql.toString()+")");
- SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString());
- bindQueryParameters(sqlQuery, params);
- sqlQuery.addScalar("countRows", LongType.INSTANCE);
- // sqlQuery.addEntity("reportSearch", entity);
- // sqlQuery.setResultTransformer(new
- // AliasToBeanResultTransformer(SearchCount.class));
- return sqlQuery.list();
-
- }
-
- /*
- * This method can be used to execute both HQL or SQL named queries with
- * paging. The distinction will come in the hbm.xml mapping file defining
- * the named query. Named HQL queries use the <query> tag while named SQL
- * queries use the <sql-query> tag. It is modified to test ZK filter.
- */
- @SuppressWarnings("rawtypes")
- protected final List _executeNamedQuery(Class entity, String queryName, String whereClause, Map params,
- Integer fromIndex, Integer toIndex) {
- Session session = getSessionFactory().getCurrentSession();
- Query query = session.getNamedQuery(queryName);
- bindQueryParameters(query, params);
- String queryStr = query.getQueryString();
- StringBuffer modifiedSql = new StringBuffer(" select * from (" + queryStr + " ) al ");
- if (whereClause != null && whereClause.length() > 0)
- modifiedSql.append("where " + whereClause);
-
- SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString());
- bindQueryParameters(sqlQuery, params);
- sqlQuery.addEntity("reportSearch", entity);
-
- if (fromIndex != null && toIndex != null) {
- sqlQuery.setFirstResult(fromIndex.intValue());
- int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
- sqlQuery.setMaxResults(pageSize);
- }
- return sqlQuery.list();
- }
-
- /*
- * This method can be used to execute both HQL or SQL named queries with
- * paging. The distinction will come in the hbm.xml mapping file defining
- * the named query. Named HQL queries use the <query> tag while named SQL
- * queries use the <sql-query> tag.
- */
- @SuppressWarnings("rawtypes")
- protected final List _executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy,
- boolean asc, Integer fromIndex, Integer toIndex) {
- Session session = getSessionFactory().getCurrentSession();
- Query query = session.getNamedQuery(queryName);
- bindQueryParameters(query, params);
- String queryStr = query.getQueryString();
- queryStr = String.format(queryStr, _orderBy, asc ? "ASC" : "DESC");
- SQLQuery sqlQuery = session.createSQLQuery(queryStr);
- bindQueryParameters(sqlQuery, params);
- sqlQuery.addEntity("reportSearch", entity);
- if (fromIndex != null && toIndex != null) {
- sqlQuery.setFirstResult(fromIndex.intValue());
- int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
- sqlQuery.setMaxResults(pageSize);
- }
- return sqlQuery.list();
- }
-
- // Where Clause
- @SuppressWarnings("rawtypes")
- protected final List _executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params,
- String _orderBy, boolean asc, Integer fromIndex, Integer toIndex) {
- Session session = getSessionFactory().getCurrentSession();
- Query query = session.getNamedQuery(queryName);
- bindQueryParameters(query, params);
- String queryStr = query.getQueryString();
- queryStr = String.format(queryStr, _orderBy, asc ? "ASC" : "DESC");
- // StringBuffer modifiedSql = new StringBuffer(queryStr );
- StringBuffer modifiedSql = new StringBuffer(" select * from (" + queryStr + " ) al ");
- // modifiedSql.insert(queryStr.lastIndexOf("order by"), " " +
- // whereClause + " ");
- if (whereClause != null && whereClause.length() > 0)
- modifiedSql.append("where " + whereClause);
- SQLQuery sqlQuery = session.createSQLQuery(modifiedSql.toString());
- bindQueryParameters(sqlQuery, params);
- sqlQuery.addEntity("reportSearch", entity);
- if (fromIndex != null && toIndex != null) {
- sqlQuery.setFirstResult(fromIndex.intValue());
- int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
- sqlQuery.setMaxResults(pageSize);
- }
- return sqlQuery.list();
- }
-
- // RAPTOR ZK END
-
- /* Processes custom Insert/Update/Delete SQL statements */
- protected final int _executeUpdateQuery(String sql) throws Exception {
- Session session = getSessionFactory().getCurrentSession();
- Query query = session.createSQLQuery(sql);
- return query.executeUpdate();
- }
-
- /* Processes Insert/Update/Delete Named SQL statements */
- @SuppressWarnings("rawtypes")
- protected final int _executeNamedUpdateQuery(String queryName, Map params) throws Exception {
- Session session = getSessionFactory().getCurrentSession();
- Query query = session.getNamedQuery(queryName);
- bindQueryParameters(query, params);
- return query.executeUpdate();
- }
-
- protected final void _update(DomainVo vo, Integer userId) {
- _update(vo, ((userId != null) ? userId.intValue() : 0));
- }
-
- protected final void _update(DomainVo vo, int userId) {
- Date timestamp = new Date();
-
- Session session = getSessionFactory().getCurrentSession();
-
- if (vo.getId() == null || vo.getId().intValue() == 0) { // add new
- vo.setCreated(timestamp);
- vo.setModified(timestamp);
-
- if (userId != 0
- && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
- vo.setCreatedId(new Long(userId));
- vo.setModifiedId(new Long(userId));
- }
- } else { // update existing
- vo.setModified(timestamp);
-
- if (userId != 0
- && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
- vo.setModifiedId(new Long(userId));
- }
- }
-
- session.saveOrUpdate(vo);
- }
-
- protected final void _remove(DomainVo vo) {
- Session session = getSessionFactory().getCurrentSession();
- session.delete(vo);
- }
-
- @SuppressWarnings("rawtypes")
- protected final int _remove(Class domainClass, String whereClause) {
- int rowsAffected = 0;
-
- Session session = getSessionFactory().getCurrentSession();
-
- StringBuffer sql = new StringBuffer("delete from ");
-
- sql.append(domainClass.getName()).append(" where ").append(whereClause);
-
- rowsAffected = session.createQuery(sql.toString()).executeUpdate();
-
- return rowsAffected;
- }
-
- protected final void _flush() {
- Session session = getSessionFactory().getCurrentSession();
- session.flush();
- }
-
- @SuppressWarnings("rawtypes")
- private void bindQueryParameters(Query query, Map params) {
- if (params != null) {
- for (Iterator i = params.entrySet().iterator(); i.hasNext();) {
- Map.Entry entry = (Map.Entry) i.next();
-
- Object parameterValue = entry.getValue();
-
- if (!(parameterValue instanceof Collection) && !(parameterValue instanceof Object[])) {
- query.setParameter((String) entry.getKey(), parameterValue);
- } else {
- if (parameterValue instanceof Collection) {
- query.setParameterList((String) entry.getKey(), (Collection) parameterValue);
- } else {
- if (parameterValue instanceof Object[]) {
- query.setParameterList((String) entry.getKey(), (Object[]) parameterValue);
- }
- }
- }
- }
- }
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.dao.support;
-
-import org.hibernate.SessionFactory;
-
-import org.openecomp.portalsdk.core.FusionObject;
-
-public class FusionDao implements FusionObject {
- private SessionFactory sessionFactory;
-
- public void setSessionFactory(SessionFactory sessionFactory) {
- this.sessionFactory = sessionFactory;
- }
-
- public SessionFactory getSessionFactory() {
- return this.sessionFactory;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-/**
- * Represents a row in the FN_APP table in the EP_SDK database. (A nearly
- * identical table is defined in Portal database.)
- *
- * @version 1.0
- */
-public class App extends DomainVo {
-
- private static final long serialVersionUID = 3465979916929796990L;
-
- // superclass defines Id
- private String name; // app_name
- private String imageUrl; // app_image_url
- private String description; // app_description
- private String notes; // app_notes
- private String url; // app_url
- private String alternateUrl; // app_alternate_url
- private String restEndpoint; // app_rest_endpoint
- private String mlAppName; // ml_app_name
- private String mlAppAdminId; // ml_app_admin_id;
- private String motsId; // mots_id
- private String appPassword; // app_password
- private String open;
- private String enabled;
- private byte[] thumbnail;
- private String username; // app_username
- private String uebKey; // ueb_key
- private String uebSecret; // ueb_secret
- private String uebTopicName; // ueb_topic_name
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getAppPassword() {
- return appPassword;
- }
-
- public void setAppPassword(String appPassword) {
- this.appPassword = appPassword;
- }
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getImageUrl() {
- return imageUrl;
- }
-
- public void setImageUrl(String imageUrl) {
- this.imageUrl = imageUrl;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getNotes() {
- return notes;
- }
-
- public void setNotes(String notes) {
- this.notes = notes;
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public String getAlternateUrl() {
- return alternateUrl;
- }
-
- public void setAlternateUrl(String alternateUrl) {
- this.alternateUrl = alternateUrl;
- }
-
- public String getRestEndpoint() {
- return restEndpoint;
- }
-
- public void setRestEndpoint(String restEndpoint) {
- this.restEndpoint = restEndpoint;
- }
-
- public String getMlAppName() {
- return mlAppName;
- }
-
- public void setMlAppName(String mlAppName) {
- this.mlAppName = mlAppName;
- }
-
- public String getMlAppAdminId() {
- return mlAppAdminId;
- }
-
- public void setMlAppAdminId(String mlAppAdminId) {
- this.mlAppAdminId = mlAppAdminId;
- }
-
- public String getMotsId() {
- return motsId;
- }
-
- public void setMotsId(String motsId) {
- this.motsId = motsId;
- }
-
- public String getOpen() {
- return open;
- }
-
- public void setOpen(String open) {
- this.open = open;
- }
-
- public String getEnabled() {
- return enabled;
- }
-
- public void setEnabled(String enabled) {
- this.enabled = enabled;
- }
-
- public byte[] getThumbnail() {
- return this.thumbnail;
- }
-
- public void setThumbnail(byte[] thumbnail) {
- this.thumbnail = thumbnail;
- }
-
- public String getUebKey() {
- return uebKey;
- }
-
- public void setUebKey(String uebKey) {
- this.uebKey = uebKey;
- }
-
- public String getUebSecret() {
- return uebSecret;
- }
-
- public void setUebSecret(String uebSecret) {
- this.uebSecret = uebSecret;
- }
-
- public String getUebTopicName() {
- return uebTopicName;
- }
-
- public void setUebTopicName(String uebTopicName) {
- this.uebTopicName = uebTopicName;
- }
-
- /**
- * Answers true if the objects have the same ID.
- */
- public int compareTo(Object obj) {
- Long c1 = getId();
- Long c2 = ((App) obj).getId();
- return c1.compareTo(c2);
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-import java.util.Date;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-public class AuditLog extends DomainVo {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public static final String CD_ACTIVITY_LOGIN = "login";
- public static final String CD_ACTIVITY_LOGOUT = "logout";
- public static final String CD_ACTIVITY_MOBILE_LOGIN = "mobile_login";
- public static final String CD_ACTIVITY_MOBILE_LOGOUT = "mobile_logout";
-
- /*-------Profile activities -----------*/
- public static final String CD_ACTIVITY_ROLE_ADD = "add_role";
- public static final String CD_ACTIVITY_ROLE_REMOVE = "remove_role";
- public static final String CD_ACTIVITY_CHILD_ROLE_ADD = "add_child_role";
- public static final String CD_ACTIVITY_CHILD_ROLE_REMOVE = "remove_child_role";
- public static final String CD_ACTIVITY_ROLE_ADD_FUNCTION = "add_role_function";
- public static final String CD_ACTIVITY_ROLE_REMOVE_FUNCTION = "remove_role_function";
- public static final String CD_ACTIVITY_USER_ROLE_ADD = "add_user_role";
- public static final String CD_ACTIVITY_USER_ROLE_REMOVE = "remove_user_role";
-
- /*Audit activities*/
- public static final String CD_ACTIVITY_FUNCTIONAL_ACCESS = "functional_access";
- public static final String CD_ACTIVITY_TAB_ACCESS = "tab_access";
- public static final String CD_ACTIVITY_APP_ACCESS = "app_access";
- public static final String CD_ACTIVITY_LEFT_MENU_ACCESS = "left_menu_access";
-
-
- private String activityCode;
- private String affectedRecordId;
- private String comments;
- private Date auditDate;
- private Long userId;
-
- public AuditLog() {
- setCreated(new Date());
- }
-
- public String getActivityCode() {
- return activityCode;
- }
-
- public String getComments() {
- return comments;
- }
-
- public String getAffectedRecordId() {
- return affectedRecordId;
- }
-
- public void setActivityCode(String activityCode) {
- this.activityCode = activityCode;
- }
-
- public void setComments(String comments) {
- this.comments = comments;
- }
-
- public void setAffectedRecordId(String affectedRecordId) {
- this.affectedRecordId = affectedRecordId;
- }
-
- public Date getAuditDate() {
- return auditDate;
- }
-
- public void setAuditDate(Date auditDate) {
- this.auditDate = auditDate;
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public void setUserId(Long userId) {
- this.userId = userId;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-import java.util.*;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-public class BroadcastMessage extends DomainVo {
-
- /**
- *
- */
-
- private static final long serialVersionUID = 1L;
- public BroadcastMessage() {
- }
-
- public static final String ID_MESSAGE_LOCATION_LOGIN = "10";
- public static final String ID_MESSAGE_LOCATION_WELCOME = "20";
-
- private String messageText;
- private Integer locationId;
- private Date startDate;
- private Date endDate;
- private Integer sortOrder;
- private Boolean active;
- private String siteCd;
-
- public Boolean getActive() {
- return active;
- }
-
- public Date getEndDate() {
- return endDate;
- }
-
- public Integer getLocationId() {
- return locationId;
- }
-
- public String getMessageText() {
- return messageText;
- }
-
- public Integer getSortOrder() {
- return sortOrder;
- }
-
- public Date getStartDate() {
- return startDate;
- }
-
- public String getSiteCd() {
- return siteCd;
- }
-
-
- public void setActive(Boolean active) {
- this.active = active;
- }
-
- public void setEndDate(Date endDate) {
- this.endDate = endDate;
- }
-
- public void setLocationId(Integer locationId) {
- this.locationId = locationId;
- }
-
- public void setMessageText(String messageText) {
- this.messageText = messageText;
- }
-
- public void setSortOrder(Integer sortOrder) {
- this.sortOrder = sortOrder;
- }
-
- public void setStartDate(Date startDate) {
- this.startDate = startDate;
- }
-
- public void setSiteCd(String siteCd) {
- this.siteCd = siteCd;
- }
-
-
- public int compareTo(Object obj){
- Integer c1 = getLocationId();
- Integer c2 = ((BroadcastMessage)obj).getLocationId();
-
- if (c1.compareTo(c2) == 0) {
- c1 = getSortOrder();
- c2 = ((BroadcastMessage)obj).getSortOrder();
-
- if (c1.compareTo(c2) == 0) {
- Long c3 = getId();
- Long c4 = ((BroadcastMessage)obj).getId();
-
- return c3.compareTo(c4);
- }
- }
-
- return c1.compareTo(c2);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.Set;
-
-/* Super class from which all data objects descend
- *
- * Per Sunder T on 3 June 2016:
- *
- * Yes, we need to get rid of domain.DomainVO and fold all the references to the support.DomainVO.
- */
-@SuppressWarnings("rawtypes")
-@Deprecated
-public class DomainVo extends FusionVo implements Serializable, Cloneable, Comparable {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- protected Long id;
- protected Date created;
- protected Date modified;
- protected Long createdId;
- protected Long modifiedId;
- protected Long rowNum;
-
- protected Serializable auditUserId;
-
- Set auditTrail = null;
-
- public DomainVo() {
- }
-
- public void setId(Long i) {
- id = i;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- public void setModified(Date modified) {
- this.modified = modified;
- }
-
- public void setCreatedId(Long createdId) {
- this.createdId = createdId;
- }
-
- public void setModifiedId(Long modifiedId) {
- this.modifiedId = modifiedId;
- }
-
- public void setAuditUserId(Serializable auditUserId) {
- this.auditUserId = auditUserId;
- }
-
- public void setRowNum(Long rowNum) {
- this.rowNum = rowNum;
- }
-
- public void setAuditTrail(Set auditTrail) {
- this.auditTrail = auditTrail;
- }
-
- public Long getId() {
- return id;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public Date getModified() {
- return modified;
- }
-
- public Long getCreatedId() {
- return createdId;
- }
-
- public Long getModifiedId() {
- return modifiedId;
- }
-
- public Serializable getAuditUserId() {
- return auditUserId;
- }
-
- public Long getRowNum() {
- return rowNum;
- }
-
- public Set getAuditTrail() {
- return auditTrail;
- }
-
- @SuppressWarnings("unchecked")
- public void addAuditTrailLog(AuditLog auditLog) {
- if (getAuditTrail() == null) {
- setAuditTrail(new HashSet());
- }
-
- getAuditTrail().add(auditLog);
- }
-
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
-
- public Object copy() {
- return copy(false);
- }
-
- public Object copy(boolean isIdNull) {
- // let's create a "copy" of the object using serialization
- ByteArrayOutputStream baos = null;
- ByteArrayInputStream bais = null;
- ObjectOutputStream oos = null;
- ObjectInputStream ois = null;
-
- DomainVo newVo = null;
-
- try {
-
- baos = new ByteArrayOutputStream();
- oos = new ObjectOutputStream(baos);
- oos.writeObject(this);
-
- bais = new ByteArrayInputStream(baos.toByteArray());
- ois = new ObjectInputStream(bais);
- newVo = (DomainVo) ois.readObject();
-
- if (isIdNull) {
- newVo.setId(null);
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return newVo;
- }
-
- public int compareTo(Object obj) {
- Long c1 = getId();
- Long c2 = ((DomainVo) obj).getId();
-
- return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-/**
- * <p>RoleFunction.java</p>
- *
- * <p>Represents a role function data object.</p>
- *
- * @version 1.0
- */
-public class FnMenu extends DomainVo {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public FnMenu() {}
-
- private Integer menuId;
- private String label;
- private Integer parentId;
- private String action;
- private String functionCd;
- private Integer sortOrder;
- private String servlet;
- private String queryString;
- private String externalUrl;
- private String target;
- private String active;
- private String separator;
- private String imageSrc;
- private String menuSetCode;
-
- public Integer getMenuId() {
- return menuId;
- }
- public void setMenuId(Integer menuId) {
- this.menuId = menuId;
- }
- public String getLabel() {
- return label;
- }
- public void setLabel(String label) {
- this.label = label;
- }
- public Integer getParentId() {
- return parentId;
- }
- public void setParentId(Integer parentId) {
- this.parentId = parentId;
- }
- public String getAction() {
- return action;
- }
- public void setAction(String action) {
- this.action = action;
- }
- public String getFunctionCd() {
- return functionCd;
- }
- public void setFunctionCd(String functionCd) {
- this.functionCd = functionCd;
- }
- public Integer getSortOrder() {
- return sortOrder;
- }
- public void setSortOrder(Integer sortOrder) {
- this.sortOrder = sortOrder;
- }
- public String getServlet() {
- return servlet;
- }
- public void setServlet(String servlet) {
- this.servlet = servlet;
- }
- public String getQueryString() {
- return queryString;
- }
- public void setQueryString(String queryString) {
- this.queryString = queryString;
- }
- public String getExternalUrl() {
- return externalUrl;
- }
- public void setExternalUrl(String externalUrl) {
- this.externalUrl = externalUrl;
- }
- public String getTarget() {
- return target;
- }
- public void setTarget(String target) {
- this.target = target;
- }
- public String getActive() {
- return active;
- }
- public void setActive(String active) {
- this.active = active;
- }
- public String getSeparator() {
- return separator;
- }
- public void setSeparator(String separator) {
- this.separator = separator;
- }
- public String getImageSrc() {
- return imageSrc;
- }
- public void setImageSrc(String imageSrc) {
- this.imageSrc = imageSrc;
- }
- public String getMenuSetCode() {
- return menuSetCode;
- }
- public void setMenuSetCode(String menuSetCode) {
- this.menuSetCode = menuSetCode;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-import org.openecomp.portalsdk.core.FusionObject;
-
-public class FusionVo implements FusionObject {
- public FusionVo() {
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-import java.util.Set;
-
-import org.openecomp.portalsdk.core.domain.support.FusionCommand;
-
-@SuppressWarnings("rawtypes")
-public class LoginBean extends FusionCommand {
-
- private String loginId;
- private String loginPwd;
- private String hrid;
- private String orgUserId;
- private String siteAccess;
- private String loginErrorMessage;
-
- private User user;
- private Set menu;
- private Set businessDirectMenu;
-
- /**
- * getLoginId
- *
- * @return String
- */
- public String getLoginId() {
- return loginId;
- }
-
- /**
- * getLoginPwd
- *
- * @return String
- */
- public String getLoginPwd() {
- return loginPwd;
- }
-
- /**
- * getMenu
- *
- * @return Set
- */
- public Set getMenu() {
- return menu;
- }
-
- /**
- * getUser
- *
- * @return User
- */
- public User getUser() {
- return user;
- }
-
- /**
- * getHrid
- *
- * @return String
- */
- public String getHrid() {
- return hrid;
- }
-
- /**
- * getSiteAccess
- *
- * @return String
- */
- public String getSiteAccess() {
- return siteAccess;
- }
-
- /**
- * getBusinessDirectMenu
- *
- * @return Set
- */
- public Set getBusinessDirectMenu() {
- return businessDirectMenu;
- }
-
- /**
- * getLoginErrorMessage
- *
- * @return String
- */
- public String getLoginErrorMessage() {
- return loginErrorMessage;
- }
-
- public String getOrgUserId() {
- return orgUserId;
- }
-
- /**
- * setLoginId
- *
- * @param loginId String
- */
- public void setLoginId(String loginId) {
- this.loginId = loginId;
- }
-
- /**
- * setLoginPwd
- *
- * @param loginPwd String
- */
- public void setLoginPwd(String loginPwd) {
- this.loginPwd = loginPwd;
- }
-
- public void setMenu(Set menu) {
- this.menu = menu;
- }
-
- /**
- * setUser
- *
- * @param user User
- */
- public void setUser(User user) {
- this.user = user;
- }
-
- /**
- * setHrid
- *
- * @param hrid String
- */
- public void setHrid(String hrid) {
- this.hrid = hrid;
- }
-
- /**
- * setSiteAccess
- *
- * @param siteAccess String
- */
- public void setSiteAccess(String siteAccess) {
- this.siteAccess = siteAccess;
- }
-
- /**
- * setBusinessDirectMenu
- *
- * @param businessDirectMenu Set
- */
- public void setBusinessDirectMenu(Set businessDirectMenu) {
- this.businessDirectMenu = businessDirectMenu;
- }
-
- /**
- * setLoginErrorMessage
- *
- * @param loginErrorMessage String
- */
- public void setLoginErrorMessage(String loginErrorMessage) {
- this.loginErrorMessage = loginErrorMessage;
- }
-
- public void setOrgUserId(String orgUserId) {
- this.orgUserId = orgUserId;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-import java.io.Serializable;
-
-import org.openecomp.portalsdk.core.domain.support.NameValueId;
-
-public class Lookup extends FusionVo implements Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private NameValueId nameValueId = new NameValueId();
-
- public Lookup() {}
-
- public Lookup(String label, String value) {
- this();
- setLabel(label);
- setValue(value);
- }
-
- public String getValue() {
- return getNameValueId().getVal();
- }
-
- public String getLabel() {
- return getNameValueId().getLab();
- }
-
- public void setValue(String value) {
- getNameValueId().setVal(value);
- }
-
- public void setLabel(String label) {
- getNameValueId().setLab(label);
- }
-
- public NameValueId getNameValueId() {
- return nameValueId;
- }
-
- public void setNameValueId(NameValueId nameValueId) {
- this.nameValueId = nameValueId;
- }
-
- // required by ZK for to set the selectedItems of Listboxes (used heavily for <select>-style drop-downs)
- public int hashCode() {
- int hash = getValue().hashCode();
- hash = hash + getLabel().hashCode();
-
- return hash;
- }
-
- public boolean equals( Object obj ) {
- boolean equivalent = false;
-
- Lookup lookup = (Lookup)obj;
- if( lookup.getValue().equals(getValue()) && lookup.getLabel().equals(getLabel())) {
- equivalent = true;
- }
-
- return equivalent;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-
-import org.openecomp.portalsdk.core.domain.support.*;
-
-
-/**
- * <p>luCountry.java</p>
- *
- * <p>Represents a country data object.</p>
- *
- * @version 1.0
- */
-public class LuCountry extends DomainVo {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- LuCountry() {}
-
- public String getCountry() {
- return country;
- }
-
- public String getAbbr() {
- return abbr;
- }
-
- public void setCountry(String country) {
- this.country = country;
- }
-
- public void setAbbr(String abbr) {
- this.abbr = abbr;
- }
-
-
- public String getFullName() {
- return fullName;
- }
-
- public void setFullName(String fullName) {
- this.fullName = fullName;
- }
-
- public String getWebphoneCountryLabel() {
- return webphoneCountryLabel;
- }
-
- public void setWebphoneCountryLabel(String webphoneCountryLabel) {
- this.webphoneCountryLabel = webphoneCountryLabel;
- }
-
- public int compareTo(Object obj){
- String c1 = getCountry();
- String c2 = ((LuCountry)obj).getCountry();
-
- return c1.compareTo(c2);
- }
-
-
- private String abbr;
- private String country;
- private String fullName;
- private String webphoneCountryLabel;
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-
-import org.openecomp.portalsdk.core.domain.support.*;
-
-
-/**
- * <p>State.java</p>
- *
- * <p>Represents a state data object.</p>
- *
- * @version 1.0
- */
-public class LuState extends DomainVo {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- LuState() {}
-
- public String getState() {
- return state;
- }
-
- public String getAbbr() {
- return abbr;
- }
-
- public void setState(String state) {
- this.state = state;
- }
-
- public void setAbbr(String abbr) {
- this.abbr = abbr;
- }
-
-
- public int compareTo(Object obj){
- String c1 = getState();
- String c2 = ((LuState)obj).getState();
-
- return c1.compareTo(c2);
- }
-
-
- private String abbr;
- private String state;
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-
-import org.openecomp.portalsdk.core.domain.support.*;
-
-
-/**
- * <p>LuTimeZone.java</p>
- *
- * <p>Represents a LuTimeZone data object.</p>
- *
- * @version 1.0
- */
-public class LuTimeZone extends DomainVo {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- LuTimeZone() {}
-
- public String getName() {
- return name;
- }
-
- public String getValue() {
- return value;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public void setValue(String value) {
- this.value = value;
- }
-
-
- public Long getTimezoneId() {
- return timezoneId;
- }
-
- public void setTimezoneId(Long timezoneId) {
- this.timezoneId = timezoneId;
- }
-
- public int compareTo(Object obj){
- Long c1 = getId();
- Long c2 = ((LuTimeZone)obj).getId();
-
- return c1.compareTo(c2);
- }
-
-
- private String name;
- private Long timezoneId;
- private String value;
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-public class Menu extends DomainVo {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public Menu() {}
-
- public String getAction() {
- return action;
- }
-
- public boolean isActive() {
- return active;
- }
-
- public String getExternalUrl() {
- return externalUrl;
- }
-
- public String getFunctionCd() {
- return functionCd;
- }
-
- public String getLabel() {
- return label;
- }
-
- public String getMenuLevel() {
- return menuLevel;
- }
-
- public Long getParentId() {
- return parentId;
- }
-
- public String getQueryString() {
- return queryString;
- }
-
- public String getServlet() {
- return servlet;
- }
-
- public Short getSortOrder() {
- return sortOrder;
- }
-
- public String getTarget() {
- return target;
- }
-
- public String getMenuSetCode() {
- return menuSetCode;
- }
-
- public void setAction(String action) {
- this.action = action;
- }
-
- public void setActive(boolean active) {
- this.active = active;
- }
-
- public void setExternalUrl(String externalUrl) {
- this.externalUrl = externalUrl;
- }
-
- public void setFunctionCd(String functionCd) {
- this.functionCd = functionCd;
- }
-
- public void setLabel(String label) {
- this.label = label;
- }
-
- public void setMenuLevel(String menuLevel) {
- this.menuLevel = menuLevel;
- }
-
- public void setParentId(Long parentId) {
- this.parentId = parentId;
- }
-
- public void setQueryString(String queryString) {
- this.queryString = queryString;
- }
-
- public void setServlet(String servlet) {
- this.servlet = servlet;
- }
-
- public void setSortOrder(Short sortOrder) {
- this.sortOrder = sortOrder;
- }
-
- public void setTarget(String target) {
- this.target = target;
- }
-
- public void setMenuSetCode(String menuSetCode) {
- this.menuSetCode = menuSetCode;
- }
-
- public boolean isSeparator() {
- return separator;
- }
-
- public void setSeparator(boolean separator) {
- this.separator = separator;
- }
-
- public String getImageSrc() {
- return imageSrc;
- }
-
- public void setImageSrc(String imageSrc) {
- this.imageSrc = imageSrc;
- }
-
- private String menuLevel;
- private String label;
- private Long parentId;
- private String action;
- private String functionCd;
- private Short sortOrder;
- private String servlet;
- private String queryString;
- private String externalUrl;
- private String target;
- private boolean active;
- private String menuSetCode;
- private boolean separator;
- private String imageSrc;
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-import java.util.*;
-
-public class MenuData extends Menu {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private MenuData parentMenu;
- private Set childMenus = new TreeSet();
-
- public MenuData() {}
-
- public Set getChildMenus() {
- return childMenus;
- }
-
- public MenuData getParentMenu() {
- return parentMenu;
- }
-
- public void setChildMenus(Set childMenus) {
- this.childMenus = childMenus;
- }
-
- public void setParentMenu(MenuData parentMenu) {
- this.parentMenu = parentMenu;
- }
-
- public int compareTo(Object obj){
-
- Short c1 = getSortOrder();
- Short c2 = ((MenuData)obj).getSortOrder();
-
- return (c1 == null || c2 == null) ? 1 : ((c1.compareTo(c2) == 0) ? 1 : c1.compareTo(c2));
- }
-
- public String getActiveAsString(){
- return String.valueOf(isActive());
- }
-
- public String getParentIdAsString(){
- return String.valueOf(getParentId());
- }
-
- public String getSeparatorAsString(){
- return String.valueOf(isSeparator());
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-public class Profile extends DomainVo{
-
- private static final long serialVersionUID = 3409056457412656883L;
-
- private Long id;
- private String first_name;
- private String last_name;
- private String email;
- private String orgManagerUserId;
- private String active_yn;
- private String orgUserId;
- public Profile() {}
-
-
- public Long getId() {
- return id;
- }
-
-
- public void setId(Long id) {
- this.id = id;
- }
-
-
- public String getFirst_name() {
- return first_name;
- }
-
- public void setFirst_name(String first_name) {
- this.first_name = first_name;
- }
-
- public String getLast_name() {
- return last_name;
- }
-
- public void setLast_name(String last_name) {
- this.last_name = last_name;
- }
-
- public String getEmail() {
- return email;
- }
-
- public void setEmail(String email) {
- this.email = email;
- }
-
- public String getOrgManagerUserId() {
- return orgManagerUserId;
- }
-
- public void setOrgManagerUserId(String orgManagerUserId) {
- this.orgManagerUserId = orgManagerUserId;
- }
-
- public String getActive_yn() {
- return active_yn;
- }
-
- public void setActive_yn(String active_yn) {
- this.active_yn = active_yn;
- }
-
- public String getOrgUserId() {
- return orgUserId;
- }
-
- public void setOrgUserId(String orgUserId) {
- this.orgUserId = orgUserId;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-
-import java.util.Iterator;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-import com.fasterxml.jackson.annotation.JsonIgnore;
-
-/**
- * <p>Role.java</p>
- * <p>Represents a role data object.</p>
- *
- * @version 1.0
- */
-public class Role extends DomainVo {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private String name;
- private boolean active;
- private Integer priority;
-
- private Set roleFunctions = new TreeSet();
-
- private Set childRoles = new TreeSet();
- @JsonIgnore
- private Set parentRoles = new TreeSet();
-
- public Role() {}
-
- public String getName() {
- return name;
- }
-
- public boolean getActive() {
- return active;
- }
-
- public Set getRoleFunctions() {
- return roleFunctions;
- }
-
- public Integer getPriority() {
- return priority;
- }
-
- public Set getChildRoles() {
- return childRoles;
- }
-
- public Set getParentRoles() {
- return parentRoles;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public void setActive(boolean active) {
- this.active = active;
- }
-
- public void setRoleFunctions(Set roleFunctions) {
- this.roleFunctions = roleFunctions;
- }
-
- public void setPriority(Integer priority) {
- this.priority = priority;
- }
-
-
- public void setChildRoles(Set childRoles) {
- this.childRoles = childRoles;
- }
-
- public void setParentRoles(Set parentRoles) {
- this.parentRoles = parentRoles;
- }
-
- @SuppressWarnings("unchecked")
- public void addRoleFunction(RoleFunction roleFunction) {
- this.roleFunctions.add(roleFunction);
- }
-
- @SuppressWarnings("unchecked")
- public void addChildRole(Role role) {
- this.childRoles.add(role);
- }
-
- @SuppressWarnings("unchecked")
- public void addParentRole(Role role) {
- this.parentRoles.add(role);
- }
-
- public String getEditUrl() {
- return "/role.htm?role_id=" + getId();
- }
-
- public String getToggleActiveImage() {
- return "/static/fusion/images/" + (getActive() ? "active.png" : "inactive.png" );
- }
-
- public String getToggleActiveAltText() {
- return getActive() ? "Click to Deactivate Role" : "Click to Activate Role";
- }
-
- public void removeChildRole(Long roleId) {
- Iterator i = this.childRoles.iterator();
-
- while (i.hasNext()) {
- Role childRole = (Role)i.next();
- if (childRole.getId().equals(roleId)) {
- this.childRoles.remove(childRole);
- break;
- }
- }
- }
-
- public void removeParentRole(Long roleId) {
- Iterator i = this.parentRoles.iterator();
-
- while (i.hasNext()) {
- Role parentRole = (Role)i.next();
- if (parentRole.getId().equals(roleId)) {
- this.parentRoles.remove(parentRole);
- break;
- }
- }
- }
-
- public void removeRoleFunction(String roleFunctionCd) {
- Iterator i = this.roleFunctions.iterator();
-
- while (i.hasNext()) {
- RoleFunction roleFunction = (RoleFunction)i.next();
- if (roleFunction.getCode().equals(roleFunctionCd)) {
- this.roleFunctions.remove(roleFunction);
- break;
- }
- }
- }
-
- public int compareTo(Object obj){
- String c1 = getName();
- String c2 = ((Role)obj).getName();
-
- return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-/**
- * <p>RoleFunction.java</p>
- *
- * <p>Represents a role function data object.</p>
- *
- * @version 1.0
- */
-public class RoleFunction extends DomainVo {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public RoleFunction() {}
-
- public String getName() {
- return name;
- }
-
- public String getCode() {
- return code;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public void setCode(String code) {
- this.code = code;
- }
-
- public String getEditUrl() {
- return "/role_function.htm?role_function_id=" + getCode();
- }
-
- public int compareTo(Object obj){
- String c1 = getName();
- String c2 = ((RoleFunction)obj).getName();
-
- return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
- }
-
- private String code;
- private String name;
- private String editUrl;
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-import java.io.Serializable;
-
-public class UrlsAccessible extends FusionVo implements Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private UrlsAccessibleKey urlsAccessibleKey = new UrlsAccessibleKey();
-
- public UrlsAccessible() {}
-
- public UrlsAccessible(String url, String functionCd) {
- this();
- setUrl(url);
- setFunctionCd(functionCd);
- }
-
- public String getUrl() {
- return getUrlsAccessibleKey().getUrl();
- }
-
- public String getFunctionCd() {
- return getUrlsAccessibleKey().getFunctionCd();
- }
-
- public void setUrl(String url) {
- getUrlsAccessibleKey().setUrl(url);
- }
-
- public void setFunctionCd(String functionCd) {
- getUrlsAccessibleKey().setFunctionCd(functionCd);
- }
-
- public UrlsAccessibleKey getUrlsAccessibleKey() {
- return urlsAccessibleKey;
- }
-
- public void setUrlsAccessibleKey(UrlsAccessibleKey urlsAccessibleKey) {
- this.urlsAccessibleKey = urlsAccessibleKey;
- }
-
- // required by ZK for to set the selectedItems of Listboxes (used heavily for <select>-style drop-downs)
- public int hashCode() {
- int hash = getUrl().hashCode();
- hash = hash + getFunctionCd().hashCode();
-
- return hash;
- }
-
- public boolean equals( Object obj ) {
- boolean equivalent = false;
-
- UrlsAccessible lookup = (UrlsAccessible)obj;
- if( lookup.getUrl().equals(getUrl()) && lookup.getFunctionCd().equals(getFunctionCd())) {
- equivalent = true;
- }
-
- return equivalent;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-import java.io.*;
-
-
-public class UrlsAccessibleKey implements Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private String url;
- private String functionCd;
-
- public UrlsAccessibleKey() {
- }
-
- public UrlsAccessibleKey(String url, String functionCd) {
- setUrl(url);
- setFunctionCd(functionCd);
- }
-
-
- public String getUrl() {
- return url;
- }
-
-
- public String getFunctionCd() {
- return functionCd;
- }
-
-
- public void setUrl(String url) {
- this.url = url;
- }
-
-
- public void setFunctionCd(String functionCd) {
- this.functionCd = functionCd;
- }
-
-
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
-
- if (o == null) {
- return false;
- }
-
- if (!(o instanceof UrlsAccessibleKey)) {
- return false;
- }
-
- final UrlsAccessibleKey key = (UrlsAccessibleKey)o;
-
- if (getFunctionCd().equals(key.getFunctionCd()) & getUrl().equals(key.getUrl())) {
- return true;
- }
-
- return false;
- }
-
-
- public int hashCode() {
- return getUrl().hashCode() + getFunctionCd().hashCode();
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-
-import java.util.Date;
-import java.util.Iterator;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-/**
- * <p>User.java</p>
- *
- * <p>Represents a user data object.</p>
- *
- * @version 1.0
- */
-public class User extends DomainVo {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private Long orgId;
- private Long managerId;
- private String firstName;
- private String middleInitial;
- private String lastName;
- private String phone;
- private String fax;
- private String cellular;
- private String email;
- private Long addressId;
- private String alertMethodCd;
- private String hrid;
- private String orgUserId;
- private String orgCode;
- private String address1;
- private String address2;
- private String city;
- private String state;
- private String zipCode;
- private String country;
- private String orgManagerUserId;
- private String locationClli;
- private String businessCountryCode;
- private String businessCountryName;
- private String businessUnit;
- private String businessUnitName;
- private String department;
- private String departmentName;
- private String companyCode;
- private String company;
- private String zipCodeSuffix;
- private String jobTitle;
- private String commandChain;
- private String siloStatus;
- private String costCenter;
- private String financialLocCode;
-
-
-
- private String loginId;
- private String loginPwd;
- private Date lastLoginDate;
- private boolean active;
- private boolean internal;
- private Long selectedProfileId;
- private Long timeZoneId;
- private boolean online;
- private String chatId;
-
- private Set userApps = new TreeSet();
-
- private Set pseudoRoles = new TreeSet();
-
-
- public User() {}
-
- public Long getAddressId() {
- return addressId;
- }
-
- public String getAlertMethodCd() {
- return alertMethodCd;
- }
-
- public String getCellular() {
- return cellular;
- }
-
- public String getEmail() {
- return email;
- }
-
- public String getFax() {
- return fax;
- }
-
- public String getFirstName() {
- return firstName;
- }
-
- public String getHrid() {
- return hrid;
- }
-
- public Date getLastLoginDate() {
- return lastLoginDate;
- }
-
- public String getLastName() {
- return lastName;
- }
-
- public String getFullName() {
- return getFirstName() + " " + getLastName();
- }
-
- public String getLoginId() {
- return loginId;
- }
-
- public String getLoginPwd() {
- return loginPwd;
- }
-
- public Long getManagerId() {
- return managerId;
- }
-
- public String getMiddleInitial() {
- return middleInitial;
- }
-
- public String getOrgCode() {
- return orgCode;
- }
-
- public Long getOrgId() {
- return orgId;
- }
-
- public String getPhone() {
- return phone;
- }
-
- public String getOrgUserId() {
- return orgUserId;
- }
-
- public boolean getActive() {
- return active;
- }
-
- public boolean getInternal() {
- return internal;
- }
-
- public String getAddress1() {
- return address1;
- }
-
- public String getAddress2() {
- return address2;
- }
-
- public String getCity() {
- return city;
- }
-
- public String getCountry() {
- return country;
- }
-
- public String getState() {
- return state;
- }
-
- public String getZipCode() {
- return zipCode;
- }
-
- public String getBusinessCountryCode() {
- return businessCountryCode;
- }
-
- public String getCommandChain() {
- return commandChain;
- }
-
- public String getCompany() {
- return company;
- }
-
- public String getCompanyCode() {
- return companyCode;
- }
-
- public String getDepartment() {
- return department;
- }
-
- public String getJobTitle() {
- return jobTitle;
- }
-
- public String getLocationClli() {
- return locationClli;
- }
-
- public String getOrgManagerUserId() {
- return orgManagerUserId;
- }
-
- public String getZipCodeSuffix() {
- return zipCodeSuffix;
- }
-
- public String getBusinessCountryName() {
- return businessCountryName;
- }
-
- public Set getPseudoRoles() {
- return pseudoRoles;
- }
-
- public Long getSelectedProfileId() {
- return selectedProfileId;
- }
-
- public void setAddressId(Long addressId) {
- this.addressId = addressId;
- }
-
- public void setAlertMethodCd(String alertMethodCd) {
- this.alertMethodCd = alertMethodCd;
- }
-
- public void setCellular(String cellular) {
- this.cellular = cellular;
- }
-
- public void setEmail(String email) {
- this.email = email;
- }
-
- public void setFax(String fax) {
- this.fax = fax;
- }
-
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
-
- public void setHrid(String hrid) {
- this.hrid = hrid;
- }
-
- public void setLastLoginDate(Date lastLoginDate) {
- this.lastLoginDate = lastLoginDate;
- }
-
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
-
- public void setLoginId(String loginId) {
- this.loginId = loginId;
- }
-
- public void setLoginPwd(String loginPwd) {
- this.loginPwd = loginPwd;
- }
-
- public void setManagerId(Long managerId) {
- this.managerId = managerId;
- }
-
- public void setMiddleInitial(String middleInitial) {
- this.middleInitial = middleInitial;
- }
-
- public void setOrgCode(String orgCode) {
- this.orgCode = orgCode;
- }
-
- public void setOrgId(Long orgId) {
- this.orgId = orgId;
- }
-
- public void setPhone(String phone) {
- this.phone = phone;
- }
-
- public void setOrgUserId(String orgUserId) {
- this.orgUserId = orgUserId;
- }
-
- public void setActive(boolean active) {
- this.active = active;
- }
-
- public void setInternal(boolean internal) {
- this.internal = internal;
- }
-
- public void setAddress1(String address1) {
- this.address1 = address1;
- }
-
- public void setAddress2(String address2) {
- this.address2 = address2;
- }
-
- public void setCity(String city) {
- this.city = city;
- }
-
- public void setCountry(String country) {
- this.country = country;
- }
-
- public void setState(String state) {
- this.state = state;
- }
-
- public void setZipCode(String zipCode) {
- this.zipCode = zipCode;
- }
-
- public void setBusinessCountryCode(String businessCountryCode) {
- this.businessCountryCode = businessCountryCode;
- }
-
- public void setCommandChain(String commandChain) {
- this.commandChain = commandChain;
- }
-
- public void setCompany(String company) {
- this.company = company;
- }
-
- public void setCompanyCode(String companyCode) {
- this.companyCode = companyCode;
- }
-
- public void setDepartment(String department) {
- this.department = department;
- }
-
- public void setJobTitle(String jobTitle) {
- this.jobTitle = jobTitle;
- }
-
- public void setLocationClli(String locationClli) {
- this.locationClli = locationClli;
- }
-
- public void setOrgManagerUserId(String orgManagerUserId) {
- this.orgManagerUserId = orgManagerUserId;
- }
-
- public void setZipCodeSuffix(String zipCodeSuffix) {
- this.zipCodeSuffix = zipCodeSuffix;
- }
-
- public void setBusinessCountryName(String businessCountryName) {
- this.businessCountryName = businessCountryName;
- }
-
- public void setPseudoRoles(Set pseudoRoles) {
- this.pseudoRoles = pseudoRoles;
- }
-
- public void setSelectedProfileId(Long selectedProfileId) {
- this.selectedProfileId = selectedProfileId;
- }
-
- public Long getTimeZoneId() {
- return timeZoneId;
- }
-
- public void setTimeZoneId(Long timeZoneId) {
- this.timeZoneId = timeZoneId;
- }
-
- public String getBusinessUnit() {
- return businessUnit;
- }
-
- public void setBusinessUnit(String businessUnit) {
- this.businessUnit = businessUnit;
- }
-
- public String getSiloStatus() {
- return siloStatus;
- }
-
- public void setSiloStatus(String siloStatus) {
- this.siloStatus = siloStatus;
- }
-
- public String getCostCenter() {
- return costCenter;
- }
-
- public void setCostCenter(String costCenter) {
- this.costCenter = costCenter;
- }
-
- public String getFinancialLocCode() {
- return financialLocCode;
- }
-
- public void setFinancialLocCode(String financialLocCode) {
- this.financialLocCode = financialLocCode;
- }
-
- public String getBusinessUnitName() {
- return businessUnitName;
- }
-
- public void setBusinessUnitName(String businessUnitName) {
- this.businessUnitName = businessUnitName;
- }
-
- public String getDepartmentName() {
- return departmentName;
- }
-
- public void setDepartmentName(String departmentName) {
- this.departmentName = departmentName;
- }
-
- public int compareTo(Object obj){
- User user = (User)obj;
-
- String c1 = getLastName() + getFirstName() + getMiddleInitial();
- String c2 = user.getLastName() + user.getFirstName() + user.getMiddleInitial();
-
- return c1.compareTo(c2);
- }
-
- public boolean isOnline() {
- return online;
- }
-
- public void setOnline(boolean online) {
- this.online = online;
- }
-
- public String getChatId() {
- return chatId;
- }
-
- public void setChatId(String chatId) {
- this.chatId = chatId;
- }
-
- public Set getUserApps() {
- return userApps;
- }
-
- public void setUserApps(Set userApps) {
- this.userApps = userApps;
- }
-
- @SuppressWarnings("unchecked")
- public void addAppRoles(App app, SortedSet<Role> roles) {
- if(roles!=null){
- //add all
- Set userApps = new TreeSet();
- Iterator itr = roles.iterator();
- while(itr.hasNext()){
- Role role = (Role) itr.next();
- UserApp userApp = new UserApp();
- userApp.setUserId(this.id);
- userApp.setApp(app);
- userApp.setRole(role);
- userApps.add(userApp);
- }
- setUserApps(userApps);
- } else {
- //remove all
- this.userApps.clear();
- }
-
-
- }
-
- @SuppressWarnings("unchecked")
- public SortedSet<Role> getAppRoles(App app) {
- SortedSet<Role> roles = new TreeSet();
- Set apps = getUserApps();
- Iterator appsItr = apps.iterator();
- UserApp userApp = null;
- //getting default app
- while(appsItr.hasNext()){
- UserApp tempUserApp = (UserApp)appsItr.next();
- if(tempUserApp.getApp().getId().equals(app.getId())){
- userApp = tempUserApp;
- roles.add(userApp.getRole());
- }
- }
- return roles;
- }
-
- public SortedSet<Role> getRoles() {
- App app = new App();
- app.setId(new Long(1));
- app.setName("Default");
- return getAppRoles(app);
- }
-
- public UserApp getDefaultUserApp(){
- Set apps = getUserApps();
- Iterator appsItr = apps.iterator();
- UserApp userApp = null;
- //getting default app
- while(appsItr.hasNext()){
- UserApp tempApp = (UserApp)appsItr.next();
- if(tempApp.equals(new Long(1))){
- userApp = tempApp;
- break;
- }
- }
- return userApp;
- }
-
- public void setRoles(SortedSet<Role> roles) {
- App app = new App();
- app.setId(new Long(1));
- app.setName("Default");
- addAppRoles(app,roles);
- }
-
- public void removeRole(Long roleId) {
- Set apps = getUserApps();
- Iterator appsItr = apps.iterator();
- //getting default app
- while(appsItr.hasNext()){
- UserApp tempUserApp = (UserApp)appsItr.next();
- if(tempUserApp.getRole().getId().equals(roleId)){
- appsItr.remove();
- }
- }
-
- }
-
- @SuppressWarnings("unchecked")
- public void addRole(Role role){
- if(role!=null){
- SortedSet<Role> roles = getRoles();
- if(roles==null){
- roles = new TreeSet();
- }
- roles.add(role);
- setRoles(roles);
- }
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-import java.util.Set;
-import java.util.TreeSet;
-
-// Generated Aug 27, 2014 5:51:36 PM by Hibernate Tools 3.4.0.CR1
-
-/**
- * FnUserRole generated by hbm2java
- */
-@SuppressWarnings("rawtypes")
-public class UserApp implements java.io.Serializable, Comparable {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private Long userId;
- private App app;
- private Role role;
- private Short priority;
-
- public UserApp() {
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public void setUserId(Long userId) {
- this.userId = userId;
- }
-
- public App getApp() {
- return app;
- }
-
- public void setApp(App app) {
- this.app = app;
- }
-
- public Role getRole() {
- return role;
- }
-
- public void setRole(Role role) {
- this.role = role;
- }
-
- public Short getPriority() {
- return this.priority;
- }
-
- public void setPriority(Short priority) {
- this.priority = priority;
- }
-
- public boolean equals(Object other) {
- if ((this == other))
- return true;
- if ((other == null))
- return false;
- if (!(other instanceof UserApp))
- return false;
- UserApp castOther = (UserApp) other;
-
- return (this.getUserId().equals(castOther.getUserId()))
- && (this.getApp().getId().equals(castOther.getApp().getId()))
- && (this.getRole().getId().equals(castOther.getRole().getId()))
- && ((this.priority==null && castOther.getPriority()==null) || this.getPriority().equals(castOther.getPriority()));
- }
-
- public int hashCode() {
- int result = 17;
-
- result = 37 * result + (int) (this.getUserId()==null ? 0 : this.getUserId().intValue());
- result = 37 * result + (int) (this.getApp().getId()==null ? 0 : this.getApp().getId().intValue());
- result = 37 * result + (int) (this.getRole().getId()==null ? 0 : this.getRole().getId().intValue());
- result = 37 * result + (int) (this.priority==null ? 0 : this.priority);
- return result;
- }
-
- public int compareTo(Object other){
- UserApp castOther = (UserApp) other;
-
- Long c1 = (this.getUserId()==null ? 0 : this.getUserId()) + (this.getApp()==null||this.getApp().getId()==null ? 0 : this.getApp().getId()) + (this.getRole()==null||this.getRole().getId()==null ? 0 : this.getRole().getId()) + (this.priority==null ? 0 : this.priority);
- Long c2 = (castOther.getUserId()==null ? 0 : castOther.getUserId()) + (castOther.getApp()==null||castOther.getApp().getId()==null ? 0 : castOther.getApp().getId()) + (castOther.getRole()==null||castOther.getRole().getId()==null ? 0 : castOther.getRole().getId()) + (castOther.priority==null ? 0 : castOther.priority);
-
- return c1.compareTo(c2);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain;
-
-// Generated Aug 27, 2014 5:51:36 PM by Hibernate Tools 3.4.0.CR1
-
-/**
- * FnUserRoleId generated by hbm2java
- */
-public class UserAppId implements java.io.Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private Long userId;
- private App app;
- private Role role;
-
- public UserAppId() {
- super();
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public void setUserId(Long userId) {
- this.userId = userId;
- }
-
- public App getApp() {
- return app;
- }
-
- public void setApp(App app) {
- this.app = app;
- }
-
- public Role getRole() {
- return role;
- }
-
- public void setRole(Role role) {
- this.role = role;
- }
-
- public boolean equals(Object other) {
- if ((this == other))
- return true;
- if ((other == null))
- return false;
- if (!(other instanceof UserAppId))
- return false;
- UserAppId castOther = (UserAppId) other;
-
- return (this.getUserId() == castOther.getUserId())
- && (this.getApp().getId() == castOther.getApp().getId())
- && (this.getRole().getId() == castOther.getRole().getId());
- }
-
- public int hashCode() {
- int result = 17;
-
- result = 37 * result + (int) (this.getUserId()==null ? 0 : this.getUserId().intValue());
- result = 37 * result + (int) (this.getApp().getId()==null ? 0 : this.getApp().getId().intValue());
- result = 37 * result + (int) (this.getRole().getId()==null ? 0 : this.getRole().getId().intValue());
- return result;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.sessionmgt;
-
-public class TimeoutVO implements Comparable<TimeoutVO>{
-
- private String jSessionId;
- private Long sessionTimOutMilliSec;
-
- public TimeoutVO(){
-
- }
-
- public TimeoutVO(String _jSessionId, Long _sessionTimOutMilliSec) {
- setjSessionId(_jSessionId);
- setSessionTimOutMilliSec(_sessionTimOutMilliSec);
-
- }
-
- public String getjSessionId() {
- return jSessionId;
- }
-
- public void setjSessionId(String jSessionId) {
- this.jSessionId = jSessionId;
- }
-
- public Long getSessionTimOutMilliSec() {
- return sessionTimOutMilliSec;
- }
-
- public void setSessionTimOutMilliSec(Long sessionTimOutMilliSec) {
- this.sessionTimOutMilliSec = sessionTimOutMilliSec;
- }
-
- @Override
- public int compareTo(TimeoutVO o) {
- return sessionTimOutMilliSec.compareTo(o.sessionTimOutMilliSec);
- }
-
-
-
-
-
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.support;
-
-public class Attribute {
- public double width;
- public double top;
- public double left;
- public String name;
- public double height;
-
- public double getWidth() {
- return width;
- }
- public void setWidth(double width) {
- this.width = width;
- }
- public double getTop() {
- return top;
- }
- public void setTop(double top) {
- this.top = top;
- }
- public double getLeft() {
- return left;
- }
- public void setLeft(double left) {
- this.left = left;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public double getHeight() {
- return height;
- }
- public void setHeight(double height) {
- this.height = height;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.support;
-
-import java.io.Serializable;
-import java.util.HashSet;
-
-public class CollaborateList implements Serializable {
-
- private static final long serialVersionUID = -4104440747626736243L;
- private HashSet<String> userNameList = new HashSet<String>();
- private static CollaborateList userListData = new CollaborateList();
- private CollaborateList(){}
-
- public static CollaborateList getInstance(){
- return userListData;
- }
-
- public HashSet<String> getAllUserName(){
- return userNameList;
- }
-
- public static void addUserName(String name){
- final HashSet<String> allUserName = CollaborateList.getInstance().getAllUserName();
- if(allUserName.contains(name)){
- //System.out.println("cannot add this user");
- }else{
- allUserName.add(name);
- }
- }
-
- public static void delUserName(String name){
- final HashSet<String> allUserName = CollaborateList.getInstance().getAllUserName();
- allUserName.remove((String) name);
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.support;
-
-import java.util.List;
-import java.util.Map;
-
-public class Container {
-
- String id;
-
- public String name;
-
- Size size;
-
- Position p;
-
- public Map<String,Container> containerRowCol;
-
- public Map<String,Element> elementRowCol;
-
- int numOfRows;
-
- int numOfCols;
-
- double sum = 0;
-
- double interEleWd;
-
- double interEleH;
-
- double interEleToContainerWd;
-
- double interEleToContainerH;
-
- double interEleToInnerContainerWd;
-
- double interEleToInnerContainerH;
-
- public double top;
-
- public double left;
-
- public double height;
-
- public double width;
-
- public String visibilityType;
-
-
-
-
-
- public Container(String id, String name, int numOfRows, int numOfCols, double interEleWd, double interEleH,
- double interEleToContainerWd, double interEleToContainerH, double interEleToInnerContainerWd,
- double interEleToInnerContainerH) {
-
- this.id = id;
- this.name = name;
- this.numOfRows = numOfRows;
- this.numOfCols = numOfCols;
- this.interEleWd = interEleWd;
- this.interEleH = interEleH;
- this.interEleToContainerWd = interEleToContainerWd;
- this.interEleToContainerH = interEleToContainerH;
- this.interEleToInnerContainerWd = interEleToInnerContainerWd;
- this.interEleToInnerContainerH = interEleToInnerContainerH;
-
- }
-
-
- public List<Container> innerCList;
-
- public List<Element> elementList;
-
- public Container() {
-
- }
-
-
-
- public Map<String, Container> getContainerRowCol() {
- return containerRowCol;
- }
-
-
-
-
- public Map<String, Element> getElementRowCol() {
- return elementRowCol;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
-
- public void setInnerContainer(Map<String,Container> innerCon) {
- containerRowCol = innerCon;
- }
-
- public void setElements(Map<String,Element> innerE) {
- elementRowCol = innerE;
- }
-
-
- public Position getP() {
- return p;
- }
-
- public void setP(Position p) {
- this.p = p;
- }
-
-
- public void setTop(double top) {
- this.top = top;
- }
-
-
- public void setLeft(double left) {
- this.left = left;
- }
-
-
- public void setHeight(double height) {
- this.height = height;
- }
-
-
- public void setWidth(double width) {
- this.width = width;
- }
-
-
- public void setInnerCList(List<Container> innerCList) {
- this.innerCList = innerCList;
- }
-
-
-
- public void setElementList(List<Element> elementList) {
- this.elementList = elementList;
- }
-
- public void setVisibilityType(String visibilityType) {
- this.visibilityType = visibilityType;
- }
-
- public Size computeSize() {
- Size size = new Size();
- double width = 0;
- double height = 0;
- // System.out.println("Inside computesize");
- for (int i = 0; i<numOfRows; i++) {
- if ((containerRowCol != null && containerRowCol.containsKey(i+String.valueOf(numOfCols-1))) ||
- (elementRowCol!=null && elementRowCol.containsKey(i+String.valueOf(numOfCols-1)))) {
- for (int j = 0; j < numOfCols; j++) {
- if (containerRowCol!=null && containerRowCol.containsKey(i+String.valueOf(j))) {
- width+=containerRowCol.get(i+String.valueOf(j)).computeSize().getWidth();
- // System.out.println(containerRowCol.get(i+String.valueOf(j)).getName()+" "+
- // containerRowCol.get(i+String.valueOf(j)).computeSize().getWidth());
- }else if (elementRowCol!=null && elementRowCol.containsKey(i+String.valueOf(j)))
- width+=elementRowCol.get(i+String.valueOf(j)).computeSize().getWidth();
- }
- break;
- }
- }
- // System.out.println("Object name "+this.getName());
- if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers")
- || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") || this.getName().equals("Neo") || this.getName().equals("Support")) {
- width+=(numOfCols-1)*interEleWd+2*interEleToInnerContainerWd;
- } else {
- width+=(numOfCols-1)*interEleWd+2*interEleToContainerWd;
- }
- size.setWidth(width);
- for (int j = 0; j<numOfCols; j++) {
- // System.out.println("Inside computesize height "+numOfCols);
- // System.out.println(containerRowCol.toString());
- if ((containerRowCol != null && containerRowCol.containsKey(String.valueOf(numOfRows-1)+j)) ||
- (elementRowCol!= null && elementRowCol.containsKey(String.valueOf(numOfRows-1)+j))) {
- //System.out.println("Inside if");
- for (int i = 0; i < numOfRows; i++) {
- if (containerRowCol!= null && containerRowCol.containsKey(i+String.valueOf(j))) {
- height+=containerRowCol.get(i+String.valueOf(j)).computeSize().getHeight();
- //System.out.println("My C name "+this.getName()+":"+containerRowCol.get(i+String.valueOf(j)).computeSize().getHeight());
- }
- else if (elementRowCol!=null && elementRowCol.containsKey(i+String.valueOf(j)))
- height+=elementRowCol.get(String.valueOf(i)+String.valueOf(j)).computeSize().getHeight();
- }
- break;
- }
- }
- if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers")
- || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") || this.getName().equals("Neo") || this.getName().equals("Support")) {
- height+=(numOfRows-1)*interEleH+2*interEleToInnerContainerH+0.1;
- } else {
- if (this.getName().equals("VoLTE UE") || this.getName().equals("3G UE") || this.getName().equals("HC UE-A")
- || this.getName().equals("HC UE-B") || this.getName().equals("VNI UE") || this.getName().equals("PSTN")) {
- height+=(numOfRows-1)*interEleH+interEleToContainerH/2;
- }else
- height+=(numOfRows-1)*interEleH+2*interEleToContainerH;
- }
- size.setHeight(height);
- // System.out.println("C name "+this.getName()+" height "+height);
- // System.out.println("test C height "+this.getName()+" height "+height+" (numOfRows-1)*interEleH "+(numOfRows-1)*interEleH+
- // " interEleToContainerH "+interEleToContainerH/2);
- return size;
- }
-
-
-
- public void computeElementPositions() {
- double xsum = 0;
- double ysum = 0;
- for (int i=0; i<numOfRows; i++){
- for (int j=0; j<numOfCols; j++){
- if (containerRowCol != null && containerRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) {
- Container c = containerRowCol.get(String.valueOf(i)+ String.valueOf(j));
- Position p = new Position();
- //System.out.println("within container");
- p.x =j*interEleWd+xsum+this.getP().getX()+
- interEleToContainerWd;
- ysum = 0;
- for (int k=0; k<i; k++) {
- if (containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
- ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
- else if (elementRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
- ysum+= elementRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
- }
- p.y = i*interEleH+ysum+this.getP().getY() + interEleToContainerH;
- // containerCoord.add(c,p);
- xsum+= c.computeSize().getWidth();
- c.setP(p);
-
- } else if (elementRowCol!=null && elementRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) {
- Element e = elementRowCol.get(String.valueOf(i)+ String.valueOf(j));
- Position p = new Position();
- // System.out.println("i "+i+"j "+j);
- // System.out.println("element "+e.getName());
- // System.out.println("Is this "+this.getP());
- if (j==numOfCols-1) {
- for (int t=0; t<i; t++) {
- if (containerRowCol!=null && containerRowCol.containsKey(String.valueOf(t)+ String.valueOf(j-1))) {
- if (!elementRowCol.containsKey(String.valueOf(i)+ String.valueOf(j-1)) &&
- !containerRowCol.containsKey(String.valueOf(i)+ String.valueOf(j-1))) {
- xsum+=containerRowCol.get(String.valueOf(t)+ String.valueOf(j-1)).computeSize().getWidth();
- break;
- }
- }
- }
- }
- if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers")
- || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider")
- || this.getName().equals("Neo") || this.getName().equals("Support")) {
- p.x = j*interEleWd+xsum+this.getP().getX()+interEleToInnerContainerWd;
- }
- else if (this.getName().equals("VNI UE") || this.getName().equals("PSTN") || this.getName().equals("3G UE")
- || this.getName().equals("HC UE-A") || this.getName().equals("HC UE-B")) {
- p.x = j*interEleWd+xsum+this.getP().getX()+interEleToContainerWd-0.8;
- }else {
- p.x = j*interEleWd+xsum+this.getP().getX()+interEleToContainerWd;
- //System.out.println("element name "+e.getName()+" j*interEleWd "+j*interEleWd
- // +" xsum " +xsum+"this.getP().getX() "+this.getP().getX()+" interEleToContainerWd " +interEleToContainerWd+" p.x "+p.x);
- }
- ysum = 0;
- for (int k=0; k<i; k++) {
- if (containerRowCol!= null && containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
- ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
- else if (elementRowCol!=null && elementRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
- ysum+= elementRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
- else if (containerRowCol!= null) {
- for (int chk=j; chk>0; chk--) {
- if (containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(chk-1))) {
- if (containerRowCol.get(String.valueOf(k)+ String.valueOf(chk-1)).computeSize().getWidth()
- + containerRowCol.get(String.valueOf(k)+ String.valueOf(chk-1)).getP().getX() > p.x) {
- ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(chk-1)).computeSize().getHeight();
- break;
- }
- }
- }
- }
-
- }
- if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers")
- || this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider") || this.getName().equals("Neo") || this.getName().equals("Support")) {
- p.y = this.getP().getY()+ysum+i*interEleH+interEleToInnerContainerH+1;
- } else {
- // System.out.println("element name "+e.getName()+" this.getP().getY() "+this.getP().getY()
- // +" ysum " +ysum+" i*interEleH "+i*interEleH+" interEleToContainerH " +interEleToContainerH);
- if (e.getName().equals("")) {
- p.y = this.getP().getY()+ysum+i*interEleH+(interEleToContainerH);
- //System.out.println("test element name "+this.getName()+" Container height "+this.computeSize().getHeight()+" this.getP().getY() "+this.getP().getY()
- // +" ysum " +ysum+" i*interEleH "+i*interEleH+" interEleToContainerH-3 " +interEleToContainerH+" p.y "+p.y);
- }else
- p.y = this.getP().getY()+ysum+i*interEleH+interEleToContainerH;
- // System.out.println(e.getName()+"My contain this.getP().getY() "+this.getP().getY()
- // +"elements Y "+p.y);
- }
- xsum+= e.computeSize().getWidth();
- e.setP(p);
- //System.out.println("my element name "+e.getName()+" e.getP().getX() "+e.getP().getX());
- //System.out.println();
- }
- }
- xsum = 0;
- }
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.support;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-public class Domain {
- // Unique identifier of the domain
- String id;
- // List<Container> cList;
-
- public String name;
- Size size;
- Position p;
-
- //Attribute1 at;
-
- public Position getP() {
- return p;
- }
-
- public void setP(Position p) {
- this.p = p;
- }
-
- //Horizontal space between a pair of containers
- double interContWd = 1.0;
- //Vertical space between a pair of containers
- double interContH;
- double domainToLayoutWd;
- double domainToContH;
- double domainToLayoutH;
- int numOfRowsofContainer;
- int numOfColsofContainer;
- boolean indexChanged;
- Map<String,Container> containerRowCol;
- public Domain(String id, String name, double interContWd, double interContH, double domainToLayoutWd,
- double domainToLayoutH, double domainToContH, int numOfRowsofContainer, int numOfColsofContainer) {
- this.id = id;
- this.name = name;
- this.interContWd = interContWd;
- this.interContH = interContH;
- this.domainToLayoutWd = domainToLayoutWd;
- this.domainToLayoutH = domainToLayoutH;
- this.domainToContH = domainToContH;
- this.numOfRowsofContainer = numOfRowsofContainer;
- this.numOfColsofContainer = numOfColsofContainer;
- // at = new Attribute1();
- }
-
-
-
-
- public double top;
-
- public double left;
-
- public double height;
-
- public double width;
-
- public List<Container> containerList;
-
- public double newXafterColl;
-
- public double YafterColl;
-
- public void setNewXafterColl(double newXafterColl) {
- this.newXafterColl = newXafterColl;
- }
-
- public double getNewXafterColl() {
- return newXafterColl;
- }
-
- public double getYafterColl() {
- return YafterColl;
- }
-
- public void setYafterColl(double yafterColl) {
- YafterColl = yafterColl;
- }
-
- public void setDomainToLayoutWd(double domainToLayoutWd) {
- this.domainToLayoutWd = domainToLayoutWd;
- }
-
- public double getDomainToLayoutWd() {
- return domainToLayoutWd;
- }
-
- public double getTop() {
- return top;
- }
-
- public void setTop(double top) {
- this.top = top;
- }
-
- public double getLeft() {
- return left;
- }
-
- public void setLeft(double left) {
- this.left = left;
- }
-
- public double getHeight() {
- return height;
- }
-
- public void setHeight(double height) {
- this.height = height;
- }
-
- public double getWidth() {
- return width;
- }
-
- public void setWidth(double width) {
- this.width = width;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- public void setContainers(Map<String,Container> containerRowCol) {
- this.containerRowCol = containerRowCol;
- }
-
- public Map<String, Container> getContainerRowCol() {
- return containerRowCol;
- }
-
-
- /* public Attribute1 getAt() {
- return at;
- }
-
- public void setAt(Attribute1 at) {
- this.at = at;
- }*/
-
- public void setContainerList(List<Container> containerList) {
- // new ArrayList<Container>();
- this.containerList = containerList;
- }
-
-
-
-/* public boolean isCollapsed() {
- return collapsed;
- }
-
- public void setCollapsed(boolean collapsed) {
- this.collapsed = collapsed;
- }*/
-
- public boolean isIndexChanged() {
- return indexChanged;
- }
-
- public void setIndexChanged(boolean indexChanged) {
- this.indexChanged = indexChanged;
- }
-
- //Compute the size of any domain
- public Size computeSize() {
- size = new Size();
- size.setHeight(5);
- double width = 0;
- for (int i = 0; i < numOfRowsofContainer; i++) {
- if (containerRowCol!=null && containerRowCol.containsKey(String.valueOf(i)+String.valueOf(numOfColsofContainer-1))) {
- for (int j = 0; j < numOfColsofContainer; j++) {
- width+=containerRowCol.get(String.valueOf(i)+String.valueOf(j)).computeSize().getWidth();
- }
- break;
- }
-
- }
- width+=(numOfColsofContainer-1)*interContWd;
- if (this.getName().equals("VNI"))
- size.setWidth(width-4);
- else
- size.setWidth(width);
- return size;
- }
-
- public void computeConatinerPositions() {
-
- double xsum = 0;
- double ysum = 0;
- for (int i=0; i< numOfRowsofContainer; i++){
- for (int j=0; j<numOfColsofContainer; j++){
- if (containerRowCol!=null && containerRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) {
- Container c = containerRowCol.get(String.valueOf(i)+ String.valueOf(j));
- // System.out.println("container "+c.toString());
- Position p = new Position();
- if (this.getName().equals("VNI")) {
- p.x = j*(interContWd-2)+xsum+domainToLayoutWd;
- } else
- p.x = j*interContWd+xsum+domainToLayoutWd;
- // this.computeSize();
- // p.x = j*interContWd+xsum+this.getP().getX();
- ysum = 0;
- for (int k=0; k<i; k++) {
- // System.out.println("i value "+i);
- if (containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
- ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
- // System.out.println("Container height "+containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).getName()+
- // ":"+" "+containerRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight());
- else if (j>0 && containerRowCol.containsKey(String.valueOf(k)+ String.valueOf(j-1)) &&
- !containerRowCol.get(String.valueOf(i)+ String.valueOf(j)).getName().equals("AIC - Alpharetta")) {
- ysum+= containerRowCol.get(String.valueOf(k)+ String.valueOf(j-1)).computeSize().getHeight();
- }
- }
- //System.out.println("C name "+c.getName()+" ysum "+ysum+" domainToLayoutH "+domainToLayoutH+" this.computeSize().getHeight() "+
- // this.computeSize().getHeight()+" domainToContH "+domainToContH+" interContH "+interContH);
- p.y = domainToLayoutH+ysum+this.computeSize().getHeight()+
- domainToContH+i*interContH;
-
- c.setP(p);
- xsum+= c.computeSize().getWidth();
-
- }
- }
- xsum = 0;
-
- }
-
- }
-
-}
-
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.support;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.Date;
-import java.util.Set;
-
-import org.openecomp.portalsdk.core.domain.FusionVo;
-
-
-/* Super class from which all data objects descend */
-public class DomainVo extends FusionVo implements Serializable, Cloneable, Comparable {
-
- protected Long id;
- protected Date created;
- protected Date modified;
- protected Long createdId;
- protected Long modifiedId;
- protected Long rowNum;
-
- protected Serializable auditUserId;
-
- Set auditTrail = null;
-
- public DomainVo() {}
-
-
- public void setId(Long i) {
- id = i;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- public void setModified(Date modified) {
- this.modified = modified;
- }
-
- public void setCreatedId(Long createdId) {
- this.createdId = createdId;
- }
-
- public void setModifiedId(Long modifiedId) {
- this.modifiedId = modifiedId;
- }
-
- public void setAuditUserId(Serializable auditUserId) {
- this.auditUserId = auditUserId;
- }
-
- public void setRowNum(Long rowNum) {
- this.rowNum = rowNum;
- }
-
- public void setAuditTrail(Set auditTrail) {
- this.auditTrail = auditTrail;
- }
-
- public Long getId() {
- return id;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public Date getModified() {
- return modified;
- }
-
- public Long getCreatedId() {
- return createdId;
- }
-
- public Long getModifiedId() {
- return modifiedId;
- }
-
- public Serializable getAuditUserId() {
- return auditUserId;
- }
-
- public Long getRowNum() {
- return rowNum;
- }
-
- public Set getAuditTrail() {
- return auditTrail;
- }
-
-
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
-
-
- public Object copy() {
- return copy(false);
- }
-
-
- public Object copy(boolean isIdNull) {
- // let's create a "copy" of the object using serialization
- ByteArrayOutputStream baos = null;
- ByteArrayInputStream bais = null;
- ObjectOutputStream oos = null;
- ObjectInputStream ois = null;
-
- DomainVo newVo = null;
-
- try {
-
- baos = new ByteArrayOutputStream();
- oos = new ObjectOutputStream(baos);
- oos.writeObject(this);
-
- bais = new ByteArrayInputStream(baos.toByteArray());
- ois = new ObjectInputStream(bais);
- newVo = (DomainVo)ois.readObject();
-
- if (isIdNull) {
- newVo.setId(null);
- }
-
- }
- catch (Exception e) {
- e.printStackTrace();
- }
-
- return newVo;
- }
-
-
-
- public int compareTo(Object obj){
- Long c1 = getId();
- Long c2 = ((DomainVo)obj).getId();
-
- return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.support;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class Element {
-
- public String id;
- public String name;
-
- public double top;
-
- public double left;
-
- public double height;
-
- public String imgFileName;
-
- public String borderType;
-
- public String bgColor;
-
- public ElementDetails details;
-
- //public List<ElementDetails> details;
-
-
- public void setBgColor(String bgColor) {
- this.bgColor = bgColor;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- public void setTop(double top) {
- this.top = top;
- }
-
- public void setLeft(double left) {
- this.left = left;
- }
-
- public void setHeight(double height) {
- this.height = height;
- }
-
- public void setWidth(double width) {
- this.width = width;
- }
-
-
- public double width;
-
-
- public String getId() {
- return id;
- }
-
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
-
- Position p;
-
- public Position getP() {
- return p;
- }
-
- public void setP(Position p) {
- this.p = p;
- }
-
-
-
- public Element(String id, String name, String imgPath, String bgColor, String logical_group, String display_longname,
- String description, String primary_function, String key_interfaces, String location, String vendor, String vendor_shortname) {
- this.id = id;
- this.name = name;
- this.imgFileName = imgPath;
- this.bgColor = bgColor;
-
-
- }
-
- public Element(String id, String name) {
- this.id = id;
- this.name = name;
- }
-
- public Element(String id, String name, String imgFilename, String bgColor, String borderType, ElementDetails details) {
- this.id = id;
- this.name = name;
- this.imgFileName = imgFilename;
- this.bgColor = bgColor;
- this.borderType = borderType;
- this.details = details;
-
- }
-
-
- public void setBorderType(String borderType) {
- this.borderType = borderType;
- }
-
- public String getImgFileName() {
- return imgFileName;
- }
-
- public void setImgFileName(String imgFileName) {
- this.imgFileName = imgFileName;
- }
-
- public String getBorderType() {
- return borderType;
- }
-
-
-
- public ElementDetails getDetails() {
- return details;
- }
-
-
-
- public void setDetails(ElementDetails details) {
- this.details = details;
- }
-
- public Size computeSize() {
- Size size= new Size();
- size.setWidth(0.5*7.0);
- size.setHeight(0.5*3.0);
- // size.setWidth(0.5*10.0);
- // size.setHeight(0.5*6.0);
- return size;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.support;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class ElementDetails {
- public String logical_group;
- public String display_longname;
- public String description;
- public String primary_function;
- public String network_function;
- public String key_interfaces;
- public String location;
- public String vendor;
- public String vendor_shortname;
- public String enclosingContainer;
-
-
-// public Map<String,String> details1;
-
-// public ElementDetails(Map<String, String> details) {
-
- // this.details = new HashMap<String, String>();
- // this.details1 = details;
-// }
-
-
-
-
-
- public ElementDetails(String logical_group, String display_longname, String description, String primary_function, String network_function,
- String key_interfaces, String location, String vendor, String vendor_shortname, String enclosingContainer) {
-
- this.logical_group = logical_group;
- this.display_longname = display_longname;
- this.description = description;
- this.primary_function = primary_function;
- this.network_function = network_function;
- this.key_interfaces = key_interfaces;
- this.location = location;
- this.vendor = vendor;
- this.vendor_shortname = vendor_shortname;
- this.enclosingContainer = enclosingContainer;
- }
-
- public void setLogical_group(String logical_group) {
- this.logical_group = logical_group;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.support;
-
-import org.openecomp.portalsdk.core.FusionObject;
-
-public class FusionCommand implements FusionObject {
-
- private String task;
-
- public FusionCommand() {
- }
-
- public String getTask() {
- return task;
- }
-
- public void setTask(String task) {
- this.task = task;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.support;
-
-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 java.util.TreeMap;
-
-public class Layout {
- //width of the screen
-// double width;
- //height of the screen;
-// double height;
- // Total number of domains present on the screen and assume that
-
- public Map<String,Domain> domainRowCol;
-
- Map<String,Domain> originalDomainRowCol;
-
- //Horizontal space between a pair of domains
- double interDomainWd;
- //Vertical space between a pair of domains
- double interDomainH;
- //Computing the co-ordinates of any domain
- int numberofRowsofDomains;
-
- int numberofColsofDomains;
-
- Map<String, Domain> collapsedDomains;
-
- List<Domain> collapsedDomainsNewList;
-
- public List<Domain> getCollapsedDomainsNewList() {
- return collapsedDomainsNewList;
- }
-
- public void setCollapsedDomainsNewList(List<Domain> collapsedDomainsNewList) {
- this.collapsedDomainsNewList = collapsedDomainsNewList;
- }
-
- public void setCollapsedDomains(Map<String, Domain> collapsedDomains) {
- this.collapsedDomains = collapsedDomains;
- }
-
- public Map<String, Domain> getCollapsedDomains() {
- return collapsedDomains;
- }
-
- public int getNumberofColsofDomains() {
- return numberofColsofDomains;
- }
-
- public void setNumberofColsofDomains(int numberofColsofDomains) {
- this.numberofColsofDomains = numberofColsofDomains;
- }
-
- public Layout(Map<String,Domain> domainRowCol, double interDomainWd, double interDomainH,
- int numberofRowsofDomains, int numberofColsofDomains) {
-
- this.domainRowCol = domainRowCol;
- this.interDomainWd = interDomainWd;
- this.interDomainH = interDomainH;
- this.numberofRowsofDomains = numberofRowsofDomains;
- this.numberofColsofDomains = numberofColsofDomains;
- this.collapsedDomains = new HashMap<String, Domain>();
- this.originalDomainRowCol = new TreeMap<String,Domain>();
- //nline
- this.collapsedDomainsNewList = new ArrayList<Domain>();
- }
-
- public Map<String, Domain> getDomainRowCol() {
- return domainRowCol;
- }
-
- public void setDomainRowCol(Map<String, Domain> domainRowCol) {
- this.domainRowCol = domainRowCol;
- }
-
-
- public void computeDomainPositions() {
- double xsum = 0;
- double domainTolayout = 10.6;
- for (int i=0; i< numberofRowsofDomains; i++){
- for (int j=0; j<numberofColsofDomains; j++){
- if (domainRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) {
- Domain d = domainRowCol.get(String.valueOf(i)+ String.valueOf(j));
- Position p = new Position();
- if (j==0)
- //p.x = (j+1)* (interDomainWd+2.6) + xsum;
- p.x = domainTolayout;
- else
- // p.x = (j+1)* interDomainWd + xsum;
- p.x = j*interDomainWd + xsum + domainTolayout;
- if (getCollapsedDomainsNewList().size() > 0)
- p.x+= accountForPlusSpaceBefore(d);
- xsum+=d.computeSize().getWidth();
- double ysum=0;
- for (int k=0; k<i; k++) {
- if (domainRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
- ysum+= domainRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
- }
- // p.y = domainToLayoutH+ysum+this.computeSize().getHeight()+
- // domainToContH+i*interContH;
- p.y = (i+1)* interDomainH + ysum;
- d.setP(p);
-
- }
- }
- xsum = 0;
- }
- }
-
- public void computeDomainPositionsModified() {
- //double xsum = 0;
- // double domainTolayout = 10.6;
- for (int i=0; i< numberofRowsofDomains; i++){
- for (int j=0; j<numberofColsofDomains; j++){
- if (domainRowCol.containsKey(String.valueOf(i)+ String.valueOf(j))) {
- Domain d = domainRowCol.get(String.valueOf(i)+ String.valueOf(j));
- Position p = new Position();
- Map<String,Container> enclosedContainers = d.getContainerRowCol();
- for (Map.Entry<String, Container> entry : enclosedContainers.entrySet()) {
- if (entry.getKey().equals("00")) {
- double containerX = entry.getValue().getP().getX();
- p.x = containerX;
- double ysum=0;
- for (int k=0; k<i; k++) {
- if (domainRowCol.containsKey(String.valueOf(k)+ String.valueOf(j)))
- ysum+= domainRowCol.get(String.valueOf(k)+ String.valueOf(j)).computeSize().getHeight();
- }
- p.y = (i+1)* interDomainH + ysum;
- d.setP(p);
- break;
- }
- }
- }
- }
- }
-
-
- }
- public Layout collapseDomainModified(String domainsToCollapse) {
-
- if(domainsToCollapse == null || domainsToCollapse.isEmpty())
- return null;
-
- Map<String,Domain> updatedRC = new HashMap<String, Domain>();
-
- for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) {
- updatedRC.put(copyEntry.getKey(), copyEntry.getValue());
- // System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
- }
-
- Map<String, Domain> updatedRCSorted = new TreeMap<String, Domain>(updatedRC);
-
- Map<String, Domain> collapsedDomainMap = getCollapsedDomains();
-
- List<Domain> collapsedDomainNewL = getCollapsedDomainsNewList();
-
-
- if (collapsedDomainNewL.size() == 0) {
- for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) {
- originalDomainRowCol.put(copyEntry.getKey(), copyEntry.getValue());
- // System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
- }
- }
-
-
- Map<String, Domain> updatedRCSortedTrunc = new TreeMap<String, Domain>();
-
- int colToDelete = 0;
- for (Map.Entry<String, Domain> entry : updatedRCSorted.entrySet()) {
- if (entry.getValue().getName().equals(domainsToCollapse)) {
- if (entry.getValue().isIndexChanged()) {
- collapsedDomainMap.put("0"+String.valueOf(Integer.parseInt(entry.getKey())+1), entry.getValue());
-
- }
- //Domain toRemove = entry.getValue();
- else {
- collapsedDomainMap.put(entry.getKey(),entry.getValue());
- }
-
- collapsedDomainNewL.add(entry.getValue());
- setNumberofColsofDomains(getNumberofColsofDomains()-1);
- updatedRC.remove(entry.getKey());
- colToDelete = Character.getNumericValue(entry.getKey().toCharArray()[1]);
- break;
- }
- }
-
-
- for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) {
- updatedRCSortedTrunc.put(copyEntry.getKey(), copyEntry.getValue());
- //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
- }
-
- for (Map.Entry<String, Domain> rmv : updatedRCSorted.entrySet()) {
- if (Character.getNumericValue(rmv.getKey().toCharArray()[1]) <= colToDelete) {
- updatedRCSortedTrunc.remove(rmv.getKey());
- }
- }
-
-
- /* for (Map.Entry<String, Domain> entry : updatedRCSortedTrunc.entrySet()) {
- System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
- }*/
-
- for (Map.Entry<String, Domain> updateOthers : updatedRCSortedTrunc.entrySet()) {
- char update[] = updateOthers.getKey().toCharArray();
- int charToupdate = Character.getNumericValue(update[1]);
- --charToupdate;
- String resultRowCol = String.valueOf(update[0])+String.valueOf(charToupdate);
- updateOthers.getValue().setIndexChanged(true);
- updatedRC.put(resultRowCol, updateOthers.getValue());
- updatedRC.remove(updateOthers.getKey());
-
- }
- setDomainRowCol(updatedRC);
-
- /* for (Map.Entry<String, Domain> entry : updatedRC.entrySet()) {
- System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
- }*/
-
- double currDistFromLftM = 11.0;
- int orgColofCollapsedd = -1;
- int orgColofDisplayedd = -1;
- for (Map.Entry<String,Domain> cd : updatedRC.entrySet()) {
- /*for (Domain pl : collapsedDomainNewL) {
- for (Map.Entry<String, Domain> colCheck : originalDomainRowCol.entrySet()) {
- if (colCheck.getValue().getName().equals(pl.getName())) {
- orgColofCollapsedd = Character.getNumericValue(colCheck.getKey().toCharArray()[1]);
- break;
- }
- }
-
- for (Map.Entry<String, Domain> colCheckk : originalDomainRowCol.entrySet()) {
- if (colCheckk.getValue().getName().equals(cd.getValue().getName())) {
- orgColofDisplayedd = Character.getNumericValue(colCheckk.getKey().toCharArray()[1]);
- break;
- }
- }
-
- if (orgColofCollapsedd < orgColofDisplayedd) {
- currDistFromLftM+= 3;
- }
- }*/
- Domain d = cd.getValue();
- double accountPlus = accountForPlusSpaceBefore(d);
- // currDistFromLftM+= accountForPlusSpaceBefore(d);
- d.setDomainToLayoutWd(currDistFromLftM+accountPlus);
- d.computeConatinerPositions();
- for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
- Container c = entry1.getValue();
- c.computeSize();
- c.computeElementPositions();
- if (c.getContainerRowCol() != null) {
- for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
- Container inner = entryInner.getValue();
- inner.computeElementPositions();
- }
- }
- }
- currDistFromLftM += d.computeSize().getWidth()+2;
-
- }
-
-
-
-
- //nline
- // Insert method invocation
- updatePlusPosition(collapsedDomainNewL, updatedRC);
-
- //order changed
- setCollapsedDomains(collapsedDomainMap);
- setCollapsedDomainsNewList(collapsedDomainNewL);
-
-
- computeDomainPositionsModified();
- return this;
- }
-
-
-
- public Layout collapseDomainNew(String domainsToCollapse) {
-
- if(domainsToCollapse == null || domainsToCollapse.isEmpty())
- return null;
-
- Map<String,Domain> updatedRC = new HashMap<String, Domain>();
-
- for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) {
- updatedRC.put(copyEntry.getKey(), copyEntry.getValue());
- //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
- }
-
- Map<String, Domain> updatedRCSorted = new TreeMap<String, Domain>(updatedRC);
-
- Map<String, Domain> collapsedDomainMap = getCollapsedDomains();
-
- List<Domain> collapsedDomainNewL = getCollapsedDomainsNewList();
-
-
- if (collapsedDomainNewL.size() == 0) {
- for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) {
- originalDomainRowCol.put(copyEntry.getKey(), copyEntry.getValue());
- // System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
- }
- }
-
-
- Map<String, Domain> updatedRCSortedTrunc = new TreeMap<String, Domain>();
-
- int colToDelete = 0;
- for (Map.Entry<String, Domain> entry : updatedRCSorted.entrySet()) {
- if (entry.getValue().getName().equals(domainsToCollapse)) {
- if (entry.getValue().isIndexChanged()) {
- collapsedDomainMap.put("0"+String.valueOf(Integer.parseInt(entry.getKey())+1), entry.getValue());
-
- }
- //Domain toRemove = entry.getValue();
- else {
- collapsedDomainMap.put(entry.getKey(),entry.getValue());
- }
-
- collapsedDomainNewL.add(entry.getValue());
- setNumberofColsofDomains(getNumberofColsofDomains()-1);
- updatedRC.remove(entry.getKey());
- colToDelete = Character.getNumericValue(entry.getKey().toCharArray()[1]);
- break;
- }
- }
-
-
- for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) {
- updatedRCSortedTrunc.put(copyEntry.getKey(), copyEntry.getValue());
- //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
- }
-
- for (Map.Entry<String, Domain> rmv : updatedRCSorted.entrySet()) {
- if (Character.getNumericValue(rmv.getKey().toCharArray()[1]) <= colToDelete) {
- updatedRCSortedTrunc.remove(rmv.getKey());
- }
- }
-
-
- /* for (Map.Entry<String, Domain> entry : updatedRCSortedTrunc.entrySet()) {
- System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
- }*/
-
- for (Map.Entry<String, Domain> updateOthers : updatedRCSortedTrunc.entrySet()) {
- char update[] = updateOthers.getKey().toCharArray();
- int charToupdate = Character.getNumericValue(update[1]);
- --charToupdate;
- String resultRowCol = String.valueOf(update[0])+String.valueOf(charToupdate);
- updateOthers.getValue().setIndexChanged(true);
- updatedRC.put(resultRowCol, updateOthers.getValue());
- updatedRC.remove(updateOthers.getKey());
-
- }
- setDomainRowCol(updatedRC);
-
- double currDistFromLftM = 11.0;
-
- boolean isDisplayed;
- for (Map.Entry<String,Domain> orgEntry : originalDomainRowCol.entrySet()) {
- isDisplayed = false;
- for (Map.Entry<String,Domain> cd : updatedRC.entrySet()) {
- if (cd.getValue().getName().equals(orgEntry.getValue().getName())) {
- Domain d = cd.getValue();
- d.setDomainToLayoutWd(currDistFromLftM);
- d.computeConatinerPositions();
- for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
- Container c = entry1.getValue();
- c.computeSize();
- c.computeElementPositions();
- if (c.getContainerRowCol() != null) {
- for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
- Container inner = entryInner.getValue();
- inner.computeElementPositions();
- }
- }
- }
- currDistFromLftM += d.computeSize().getWidth()+1;
- isDisplayed = true;
- break;
- }
- }
-
- if (!isDisplayed) {
- Domain myCollapsed = orgEntry.getValue();
- myCollapsed.setNewXafterColl(currDistFromLftM);
- myCollapsed.setYafterColl(myCollapsed.getP().getY());
- currDistFromLftM += 4;
- }
- }
-
- setCollapsedDomains(collapsedDomainMap);
- setCollapsedDomainsNewList(collapsedDomainNewL);
-
-
- computeDomainPositionsModified();
- return this;
-
- }
-
-
- public Layout collapseDomain(String domainsToCollapse) {
-
- Map<String,Domain> updatedRC = new HashMap<String, Domain>();
-
- for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) {
- updatedRC.put(copyEntry.getKey(), copyEntry.getValue());
- //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
- }
-
- Map<String, Domain> updatedRCSorted = new TreeMap<String, Domain>(updatedRC);
-
- Map<String, Domain> collapsedDomainMap = getCollapsedDomains();
-
- if (collapsedDomainMap.size() == 0) {
- for (Map.Entry<String, Domain> copyEntry : domainRowCol.entrySet()) {
- originalDomainRowCol.put(copyEntry.getKey(), copyEntry.getValue());
- // System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
- }
- }
-
-
- // List<Domain> collapsedDomainsList = getCollapsedDomains();
-
- /* for (Map.Entry<String, Domain> entry : updatedRCSorted.entrySet()) {
- System.out.println("Sorted Key: "+entry.getKey());
- }*/
-
- double prevDomXCordinate = 0.0;
- Map<String, Domain> updatedRCSortedTrunc = new TreeMap<String, Domain>();
- // for (String dToCollapse : domainsToCollapse) {
- int colToDelete = 0;
- for (Map.Entry<String, Domain> entry : updatedRCSorted.entrySet()) {
- if (entry.getValue().getName().equals(domainsToCollapse)) {
- if (entry.getValue().isIndexChanged())
- collapsedDomainMap.put("0"+String.valueOf(Integer.parseInt(entry.getKey())+1), entry.getValue());
- //Domain toRemove = entry.getValue();
- else
- collapsedDomainMap.put(entry.getKey(),entry.getValue());
- prevDomXCordinate = entry.getValue().getP().getX();
- entry.getValue().getP().setX(prevDomXCordinate-2);
- // toRemove.setCollapsed(true);
- setNumberofColsofDomains(getNumberofColsofDomains()-1);
- updatedRC.remove(entry.getKey());
- colToDelete = Character.getNumericValue(entry.getKey().toCharArray()[1]);
- // collapsedDomainList.put(entry.getKey(),entry.getValue());
- break;
- }
- }
-
- /* for (Map.Entry<String, Domain> entry : updatedRC.entrySet()) {
- System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
- }*/
-
- setCollapsedDomains(collapsedDomainMap);
-
- for (Map.Entry<String, Domain> copyEntry : updatedRCSorted.entrySet()) {
- updatedRCSortedTrunc.put(copyEntry.getKey(), copyEntry.getValue());
- //System.out.println("copyEntry.getKey() "+copyEntry.getKey()+ " copyEntry.getValue() "+copyEntry.getValue());
- }
-
- for (Map.Entry<String, Domain> rmv : updatedRCSorted.entrySet()) {
- if (Character.getNumericValue(rmv.getKey().toCharArray()[1]) <= colToDelete) {
- updatedRCSortedTrunc.remove(rmv.getKey());
- }
- }
-
-
- /* for (Map.Entry<String, Domain> entry : updatedRCSortedTrunc.entrySet()) {
- System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
- }*/
-
- for (Map.Entry<String, Domain> updateOthers : updatedRCSortedTrunc.entrySet()) {
- // if (!updateOthers.getValue().getName().equals(dToCollapse)) {
- // if ((int)updateOthers.getKey().toCharArray()[1] > colToDelete) {
- char update[] = updateOthers.getKey().toCharArray();
- int charToupdate = Character.getNumericValue(update[1]);
- --charToupdate;
- String resultRowCol = String.valueOf(update[0])+String.valueOf(charToupdate);
- // update[1] = (char)charToupdate;
- // updatedRC.put(String.valueOf(update), updateOthers.getValue());
- updateOthers.getValue().setIndexChanged(true);
- updatedRC.put(resultRowCol, updateOthers.getValue());
- updatedRC.remove(updateOthers.getKey());
- // }
- // }
- }
-
- // }
- setDomainRowCol(updatedRC);
-
-
-
- for (Map.Entry<String, Domain> entry : updatedRCSortedTrunc.entrySet()) {
- Domain d = entry.getValue();
- // if (d.getName().equals("Datacenter with AIC") || d.getName().equals("VNI")) {
- // d.setDomainToLayoutWd(d.getDomainToLayoutWd()-33);
- if (collapsedDomains.size() == 2 && collapsedDomains.containsKey("00") && collapsedDomains.containsKey("01") && domainsToCollapse.equals("RAN")) {
- if (d.getName().equals("USP"))
- d.setDomainToLayoutWd(prevDomXCordinate);
- else if (d.getName().equals("VNI"))
- d.setDomainToLayoutWd(prevDomXCordinate+8);
- else
- d.setDomainToLayoutWd(prevDomXCordinate+10);
- //System.out.println("Inside RAN EPC");
- }
- else if (domainsToCollapse.equals("RAN") && !d.getName().equals("EPC") && collapsedDomains.size() < 3)
- d.setDomainToLayoutWd(prevDomXCordinate+11);
- else if (domainsToCollapse.equals("RAN") && collapsedDomains.size() == 3 && collapsedDomains.containsKey("01") && collapsedDomains.containsKey("04")) {
- if (d.getName().equals("USP"))
- d.setDomainToLayoutWd(prevDomXCordinate);
- else
- d.setDomainToLayoutWd(prevDomXCordinate+10);
- }
-
- else if (collapsedDomains.containsKey("00") && collapsedDomains.size() == 3 && collapsedDomains.containsKey("01") && collapsedDomains.containsKey("02")) {
- //System.out.println("Inside test");
- if (d.getName().equals("VNI"))
- d.setDomainToLayoutWd(prevDomXCordinate+10);
- else
- d.setDomainToLayoutWd(prevDomXCordinate);
-
- }
-
- else if (collapsedDomains.containsKey("00") && collapsedDomains.size() == 3 && collapsedDomains.containsKey("01") && collapsedDomains.containsKey("03")) {
- //System.out.println("Inside test");
- if (d.getName().equals("VNI"))
- d.setDomainToLayoutWd(prevDomXCordinate+10);
- else
- d.setDomainToLayoutWd(prevDomXCordinate);
-
- }
-
-
-
- else {
- d.setDomainToLayoutWd(prevDomXCordinate);
- }
- d.computeConatinerPositions();
- prevDomXCordinate = d.getP().getX();
- for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
- Container c = entry1.getValue();
- c.computeSize();
- c.computeElementPositions();
- if (c.getContainerRowCol() != null) {
- for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
- Container inner = entryInner.getValue();
- inner.computeElementPositions();
- }
- }
- }
- // }
- // System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
- }
- // setNumberofColsofDomains(getNumberofColsofDomains()-1);
- computeDomainPositions();
- return this;
- /* CoordinateMain cm = new CoordinateMain();
- try {
- cm.convertToYAML(this);
- } catch (Exception e) {
-
- }*/
-
- }
-
- public Layout uncollapseDomainModified(String domainToUnCollapse) {
- Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol);
- Map<String, Domain> updateDomains = new TreeMap<String,Domain>();
- Map<String, Domain> collapsedDomainList = getCollapsedDomains();
- Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList);
-
- List<Domain> domainstoUpd = new ArrayList<Domain>();
-
- int colToUnCollapse = 99;
-
- Domain domainToInsert = null;
-
- if (collapsedDomains.size() == 0) {
- for (Map.Entry<String, Domain> unindexDomain : originalDomainRowCol.entrySet()) {
- Domain dm = unindexDomain.getValue();
- dm.setIndexChanged(false);
- }
- }
-
-
- for (Map.Entry<String, Domain> entry : collapsedDomainListSorted.entrySet()) {
- if (entry.getValue().getName().equals(domainToUnCollapse)) {
- colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]);
- domainToInsert = entry.getValue();
- collapsedDomainList.remove(entry.getKey());
- break;
- }
- }
-
- domainstoUpd.add(domainToInsert);
-
- //for (Map.Entry<String, Domain> e : originalDomainRowCol.entrySet())
- // System.out.println("Original key value"+e.getKey()+":"+e.getValue().getName());
-
- int lastKeyCol = -1;
- for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) {
- int currcol = Character.getNumericValue(entry.getKey().toCharArray()[1]);
- if (currcol < colToUnCollapse) {
- for (Map.Entry<String, Domain> currDomainsEntry : currentDomainsSorted.entrySet()) {
- if (currDomainsEntry.getValue().getName().equals(entry.getValue().getName())) {
- updateDomains.put(currDomainsEntry.getKey(), currDomainsEntry.getValue());
- lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]);
- break;
- }
- }
- } else {
- String newKey = "0"+String.valueOf(lastKeyCol+1);
- if (currcol == colToUnCollapse) {
- updateDomains.put(newKey, domainToInsert);
- ++lastKeyCol;
- } else {
- for (Map.Entry<String, Domain> currDomainsEnt : currentDomainsSorted.entrySet()) {
- if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) {
- updateDomains.put(newKey, currDomainsEnt.getValue());
- domainstoUpd.add(currDomainsEnt.getValue());
- ++lastKeyCol;
- // lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]);
- break;
- }
- }
- }
-
- }
- }
-
- setNumberofColsofDomains(getNumberofColsofDomains()+1);
- setDomainRowCol(updateDomains);
- setCollapsedDomains(collapsedDomainList);
-
- //for (Map.Entry<String, Domain> e : updateDomains.entrySet())
- // System.out.println("me Updatedomains key value"+e.getKey()+":"+e.getValue().getName());
-
- // for (int i = 1; i < domainstoUpd.size(); i++) {
- for (int i = 0; i < domainstoUpd.size(); i++) {
- Domain d = domainstoUpd.get(i);
- double newX = 0.0;
- if (i+1 < domainstoUpd.size())
- // newX = domainstoUpd.get(i-1).getP().getX()+domainstoUpd.get(i-1).computeSize().getWidth()+5;
- newX = domainstoUpd.get(i+1).getP().getX();
- //d.setDomainToLayoutWd(domainstoUpd.get(i+1).getP().getX());
- else
- newX = domainstoUpd.get(i).getP().getX()+32;
- // d.setDomainToLayoutWd(domainstoUpd.get(i).getP().getX()+38);
- /* if (i > 0) {
- if (d.getWidth() < domainstoUpd.get(i-1).getWidth())
- newX+= domainstoUpd.get(i-1).getWidth() - d.getWidth();
- else if (d.getWidth() > domainstoUpd.get(i-1).getWidth())
- newX-= d.getWidth() - domainstoUpd.get(i-1).getWidth() ;
- } else {
- if (d.getWidth() < domainInserted.getWidth())
- newX+= domainInserted.getWidth() - d.getWidth();
- else if (d.getWidth() > domainInserted.getWidth())
- newX-= d.getWidth() - domainInserted.getWidth() ;
- }*/
- if (d.getName().equals("Datacenter with AIC"))
- newX+= 2;
- d.setDomainToLayoutWd(newX);
- /* if (i == 0)
- d.setDomainToLayoutWd(domainInserted.getP().getX()+domainInserted.getWidth());
- else
- d.setDomainToLayoutWd(domainstoUpd.get(i-1).getP().getX()+domainstoUpd.get(i-1).getWidth());*/
- d.computeConatinerPositions();
- for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
- Container c = entry1.getValue();
- c.computeSize();
- c.computeElementPositions();
- if (c.getContainerRowCol() != null) {
- for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
- Container inner = entryInner.getValue();
- inner.computeElementPositions();
- }
- }
- }
- // }
- // System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
- }
-
- computeDomainPositions();
- return this;
-
- }
-
-
-
- public Layout uncollapseDomain(String domainToCollapse) {
- Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol);
- Map<String, Domain> updateDomains = new TreeMap<String,Domain>();
- Map<String, Domain> collapsedDomainList = getCollapsedDomains();
- Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList);
-
- List<Domain> domainstoUpd = new ArrayList<Domain>();
- /* for (Map.Entry<String, Domain> entry : collapsedDomainListSorted.entrySet()) {
- if (entry.getValue().getName().equals("domainToCollapse")) {
- if (currentDomainsSorted != null) {
- if (!currentDomainsSorted.containsKey(entry.getKey())) {
- updateDomains.put(entry.getKey(), entry.getValue());
- collapsedDomainList.remove(entry.getKey());
- break;
- } else {
- int colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]);
- for (Map.Entry<String, Domain> curr : currentDomainsSorted.entrySet()) {
- if (Character.getNumericValue(curr.getKey().toCharArray()[1]) < colToUnCollapse) {
- updateDomains.put(curr.getKey(),curr.getValue());
- } else {
- updateDomains.put(curr.getKey()+1,curr.getValue());
-
- }
- }
- updateDomains.put(entry.getKey(), entry.getValue());
- }
- }
-
-
- }
- }*/
-
- Domain domainInserted = null;
- for (Map.Entry<String, Domain> entry : collapsedDomainListSorted.entrySet()) {
- if (entry.getValue().getName().equals(domainToCollapse)) {
- domainInserted = entry.getValue();
- if (currentDomainsSorted != null) {
- int colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]);
- for (Map.Entry<String, Domain> curr : currentDomainsSorted.entrySet()) {
- if (Character.getNumericValue(curr.getKey().toCharArray()[1]) < colToUnCollapse) {
- updateDomains.put(curr.getKey(),curr.getValue());
- } else {
- updateDomains.put("0"+String.valueOf(Integer.parseInt(curr.getKey())+1),curr.getValue());
- domainstoUpd.add(curr.getValue());
- }
- }
- }
- updateDomains.put(entry.getKey(), entry.getValue());
- collapsedDomainList.remove(entry.getKey());
- break;
-
- }
- }
- setNumberofColsofDomains(getNumberofColsofDomains()+1);
- setDomainRowCol(updateDomains);
- setCollapsedDomains(collapsedDomainList);
-
- //for (Map.Entry<String, Domain> e : updateDomains.entrySet())
- // System.out.println("Updatedomains key value"+e.getKey()+":"+e.getValue().getName());
-
-
- for (int i = 0; i < domainstoUpd.size(); i++) {
- Domain d = domainstoUpd.get(i);
- double newX = 0.0;
- if (i+1 < domainstoUpd.size())
- newX = domainstoUpd.get(i+1).getP().getX();
- //d.setDomainToLayoutWd(domainstoUpd.get(i+1).getP().getX());
- else
- newX = domainstoUpd.get(i).getP().getX()+38;
- // d.setDomainToLayoutWd(domainstoUpd.get(i).getP().getX()+38);
- /* if (i > 0) {
- if (d.getWidth() < domainstoUpd.get(i-1).getWidth())
- newX+= domainstoUpd.get(i-1).getWidth() - d.getWidth();
- else if (d.getWidth() > domainstoUpd.get(i-1).getWidth())
- newX-= d.getWidth() - domainstoUpd.get(i-1).getWidth() ;
- } else {
- if (d.getWidth() < domainInserted.getWidth())
- newX+= domainInserted.getWidth() - d.getWidth();
- else if (d.getWidth() > domainInserted.getWidth())
- newX-= d.getWidth() - domainInserted.getWidth() ;
- }*/
- if (d.getName().equals("Datacenter with AIC"))
- newX+= 5;
- d.setDomainToLayoutWd(newX);
- /* if (i == 0)
- d.setDomainToLayoutWd(domainInserted.getP().getX()+domainInserted.getWidth());
- else
- d.setDomainToLayoutWd(domainstoUpd.get(i-1).getP().getX()+domainstoUpd.get(i-1).getWidth());*/
- d.computeConatinerPositions();
- for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
- Container c = entry1.getValue();
- c.computeSize();
- c.computeElementPositions();
- if (c.getContainerRowCol() != null) {
- for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
- Container inner = entryInner.getValue();
- inner.computeElementPositions();
- }
- }
- }
- // }
- // System.out.println("Sorted key: "+entry.getKey()+" Sorted value: "+entry.getValue().getName());
- }
-
- computeDomainPositions();
- return this;
- }
-
- public Layout uncollapseDomainNew(String domainToUnCollapse) {
- Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol);
- Map<String, Domain> updateDomains = new TreeMap<String,Domain>();
- Map<String, Domain> collapsedDomainList = getCollapsedDomains();
- Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList);
-
- List<Domain> domainstoUpd = new ArrayList<Domain>();
-
- //nline
- List<Domain> collapsedDomainNewLL = getCollapsedDomainsNewList();
-
- int colToUnCollapse = 99;
-
- Domain domainToInsert = null;
-
- //nline
- // if (collapsedDomains.size() == 0) {
- if (collapsedDomainNewLL.size() == 0) {
- for (Map.Entry<String, Domain> unindexDomain : originalDomainRowCol.entrySet()) {
- Domain dm = unindexDomain.getValue();
- dm.setIndexChanged(false);
- }
- }
-
-
- for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) {
- if (entry.getValue().getName().equals(domainToUnCollapse)) {
- colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]);
- domainToInsert = entry.getValue();
- collapsedDomainList.remove(entry.getKey());
- //nline
- collapsedDomainNewLL.remove(entry.getValue());
- break;
- }
- }
-
- domainstoUpd.add(domainToInsert);
-
- // for (Map.Entry<String, Domain> e : originalDomainRowCol.entrySet())
- // System.out.println("Original key value"+e.getKey()+":"+e.getValue().getName());
-
- int lastKeyCol = -1;
- for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) {
- int currcol = Character.getNumericValue(entry.getKey().toCharArray()[1]);
- if (currcol < colToUnCollapse) {
- for (Map.Entry<String, Domain> currDomainsEntry : currentDomainsSorted.entrySet()) {
- if (currDomainsEntry.getValue().getName().equals(entry.getValue().getName())) {
- updateDomains.put(currDomainsEntry.getKey(), currDomainsEntry.getValue());
- lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]);
- break;
- }
- }
- } else {
- String newKey = "0"+String.valueOf(lastKeyCol+1);
- if (currcol == colToUnCollapse) {
- updateDomains.put(newKey, domainToInsert);
- ++lastKeyCol;
- } else {
- for (Map.Entry<String, Domain> currDomainsEnt : currentDomainsSorted.entrySet()) {
- if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) {
- updateDomains.put(newKey, currDomainsEnt.getValue());
- domainstoUpd.add(currDomainsEnt.getValue());
- ++lastKeyCol;
- // lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]);
- break;
- }
- }
- }
-
- }
- }
-
- setNumberofColsofDomains(getNumberofColsofDomains()+1);
- setDomainRowCol(updateDomains);
-
- //for (Map.Entry<String, Domain> e : updateDomains.entrySet())
- // System.out.println("me Updatedomains key value"+e.getKey()+":"+e.getValue().getName());
-
-
-
- double currDistFromLftMargin = 11.0;
- for (Map.Entry<String,Domain> cd : updateDomains.entrySet()) {
- Domain d = cd.getValue();
- double accountPlus = accountForPlusSpaceBefore(d);
- d.setDomainToLayoutWd(currDistFromLftMargin+accountPlus);
- d.computeConatinerPositions();
- for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
- Container c = entry1.getValue();
- c.computeSize();
- c.computeElementPositions();
- if (c.getContainerRowCol() != null) {
- for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
- Container inner = entryInner.getValue();
- inner.computeElementPositions();
- }
- }
- }
- currDistFromLftMargin += d.computeSize().getWidth()+2;
-
- }
-
- //nline
- updatePlusPosition(collapsedDomainNewLL, updateDomains);
-
- //order changed
- setCollapsedDomains(collapsedDomainList);
-
- //nline
- setCollapsedDomainsNewList(collapsedDomainNewLL);
-
-
- computeDomainPositionsModified();
- return this;
-
- }
-
- public Layout uncollapseDomainNew1(String domainToUnCollapse) {
-
- if(domainToUnCollapse == null || domainToUnCollapse.isEmpty())
- return null;
-
- Map<String, Domain> currentDomainsSorted = new TreeMap<String,Domain>(domainRowCol);
- Map<String, Domain> updateDomains = new TreeMap<String,Domain>();
- Map<String, Domain> collapsedDomainList = getCollapsedDomains();
- Map<String, Domain> collapsedDomainListSorted = new TreeMap<String, Domain>(collapsedDomainList);
-
- List<Domain> domainstoUpd = new ArrayList<Domain>();
-
- //nline
- List<Domain> collapsedDomainNewLL = getCollapsedDomainsNewList();
-
- int colToUnCollapse = 99;
-
- Domain domainToInsert = null;
-
- //nline
- // if (collapsedDomains.size() == 0) {
- if (collapsedDomainNewLL.size() == 0) {
- for (Map.Entry<String, Domain> unindexDomain : originalDomainRowCol.entrySet()) {
- Domain dm = unindexDomain.getValue();
- dm.setIndexChanged(false);
- }
- }
-
-
- for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) {
- if (entry.getValue().getName().equals(domainToUnCollapse)) {
- colToUnCollapse = Character.getNumericValue(entry.getKey().toCharArray()[1]);
- domainToInsert = entry.getValue();
- collapsedDomainList.remove(entry.getKey());
- //nline
- collapsedDomainNewLL.remove(entry.getValue());
- break;
- }
- }
-
- domainstoUpd.add(domainToInsert);
-
- //for (Map.Entry<String, Domain> e : originalDomainRowCol.entrySet())
- // System.out.println("Original key value"+e.getKey()+":"+e.getValue().getName());
-
- int lastKeyCol = -1;
- for (Map.Entry<String, Domain> entry : originalDomainRowCol.entrySet()) {
- int currcol = Character.getNumericValue(entry.getKey().toCharArray()[1]);
- if (currcol < colToUnCollapse) {
- for (Map.Entry<String, Domain> currDomainsEntry : currentDomainsSorted.entrySet()) {
- if (currDomainsEntry.getValue().getName().equals(entry.getValue().getName())) {
- updateDomains.put(currDomainsEntry.getKey(), currDomainsEntry.getValue());
- lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]);
- break;
- }
- }
- } else {
- String newKey = "0"+String.valueOf(lastKeyCol+1);
- if (currcol == colToUnCollapse) {
- updateDomains.put(newKey, domainToInsert);
- ++lastKeyCol;
- } else {
- for (Map.Entry<String, Domain> currDomainsEnt : currentDomainsSorted.entrySet()) {
- if (currDomainsEnt.getValue().getName().equals(entry.getValue().getName())) {
- updateDomains.put(newKey, currDomainsEnt.getValue());
- domainstoUpd.add(currDomainsEnt.getValue());
- ++lastKeyCol;
- // lastKeyCol = Character.getNumericValue(currDomainsEntry.getKey().toCharArray()[1]);
- break;
- }
- }
- }
-
- }
- }
-
- setNumberofColsofDomains(getNumberofColsofDomains()+1);
- setDomainRowCol(updateDomains);
-
- //for (Map.Entry<String, Domain> e : updateDomains.entrySet())
- // System.out.println("me Updatedomains key value"+e.getKey()+":"+e.getValue().getName());
-
-
-
-
- double currDistFromLftM = 11.0;
-
- boolean isDisplayed;
- for (Map.Entry<String,Domain> orgEntry : originalDomainRowCol.entrySet()) {
- isDisplayed = false;
- for (Map.Entry<String,Domain> cd : updateDomains.entrySet()) {
- if (cd.getValue().getName().equals(orgEntry.getValue().getName())) {
- Domain d = cd.getValue();
- d.setDomainToLayoutWd(currDistFromLftM);
- d.computeConatinerPositions();
- for (Map.Entry<String, Container> entry1 : d.getContainerRowCol().entrySet()) {
- Container c = entry1.getValue();
- c.computeSize();
- c.computeElementPositions();
- if (c.getContainerRowCol() != null) {
- for (Map.Entry<String, Container> entryInner : c.getContainerRowCol().entrySet()) {
- Container inner = entryInner.getValue();
- inner.computeElementPositions();
- }
- }
- }
- currDistFromLftM += d.computeSize().getWidth()+1;
- isDisplayed = true;
- break;
- }
- }
-
- if (!isDisplayed) {
- Domain myCollapsed = orgEntry.getValue();
- myCollapsed.setNewXafterColl(currDistFromLftM);
- currDistFromLftM += 4;
- }
- }
-
- // plus.setNewXafterColl(distOfCollFrmLft+1.5);
-
- //order changed
- setCollapsedDomains(collapsedDomainList);
-
- //nline
- setCollapsedDomainsNewList(collapsedDomainNewLL);
-
-
- computeDomainPositionsModified();
- return this;
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- private void updatePlusPosition(List<Domain> collapsedDNewL, Map<String, Domain> displayedDomainMap) {
- List<Domain> copyCollapseList = new ArrayList<Domain>();
-
- for (Domain copyCollapse : collapsedDNewL) {
- copyCollapseList.add(copyCollapse);
- }
-
- //double distOfCollFrmLft = 0.0;
- int orgColofCollapsed = -1;
- int orgColofDisplayed = -1;
- int orgColofDisplayedOtherPlus = -1;
- int orgColofInterDomainPlus = -1;
- List<Domain> dsplyList = new ArrayList<Domain>();
-
- for (Domain plus : collapsedDNewL) {
- double distOfCollFrmLft = 0.0;
- for (Map.Entry<String, Domain> colCheck : originalDomainRowCol.entrySet()) {
- if (colCheck.getValue().getName().equals(plus.getName())) {
- orgColofCollapsed = Character.getNumericValue(colCheck.getKey().toCharArray()[1]);
- break;
- }
- }
- for (Map.Entry<String, Domain> displayedEntry : displayedDomainMap.entrySet()) {
-
- for (Map.Entry<String, Domain> colCheck1 : originalDomainRowCol.entrySet()) {
- if (colCheck1.getValue().getName().equals(displayedEntry.getValue().getName())) {
- orgColofDisplayed = Character.getNumericValue(colCheck1.getKey().toCharArray()[1]);
- break;
- }
- }
- if (orgColofDisplayed < orgColofCollapsed) {
- distOfCollFrmLft+= displayedEntry.getValue().computeSize().getWidth();
-
-
- /* if (dsplyList.size() > 0) {
- Domain lastAdded = dsplyList.get(dsplyList.size()-1);
- int orgColofLastAdded = -1;
- for (Map.Entry<String, Domain> colCh : originalDomainRowCol.entrySet()) {
- if (colCh.getValue().getName().equals(lastAdded.getName())) {
- orgColofLastAdded = Character.getNumericValue(colCh.getKey().toCharArray()[1]);
- break;
- }
- }
- if (Math.abs(orgColofDisplayed - orgColofLastAdded) == 1) {
- boolean adjDomainsWithPlus = false;
- for (Domain colp : copyCollapseList) {
- if (!colp.getName().equals(plus.getName())) {
- for (Map.Entry<String, Domain> colCk2 : originalDomainRowCol.entrySet()) {
- if (colCk2.getValue().getName().equals(colp.getName())) {
- orgColofInterDomainPlus = Character.getNumericValue(colCk2.getKey().toCharArray()[1]);
- break;
- }
- }
- if (orgColofInterDomainPlus > orgColofLastAdded && orgColofInterDomainPlus < orgColofDisplayed) {
- adjDomainsWithPlus = true;
- break;
- }
- }
- }
- if (!adjDomainsWithPlus)
- distOfCollFrmLft+=interDomainWd;
- }
- }
- dsplyList.add(displayedEntry.getValue()); */
-
-
-
- }
-
- }
-
- for (Domain collp : copyCollapseList) {
- if (!collp.getName().equals(plus.getName())) {
- for (Map.Entry<String, Domain> colCheck2 : originalDomainRowCol.entrySet()) {
- if (colCheck2.getValue().getName().equals(collp.getName())) {
- orgColofDisplayedOtherPlus = Character.getNumericValue(colCheck2.getKey().toCharArray()[1]);
- break;
- }
- }
- if (orgColofDisplayedOtherPlus < orgColofCollapsed) {
- distOfCollFrmLft+=3.0;
- }
- }
- }
-
- plus.setNewXafterColl(distOfCollFrmLft+1.5);
-
-
- }
- }
-
-
- private double accountForPlusSpaceBefore(Domain d) {
-
- int orgColofCollapsed = 0;
- int orgColofDisplayed = 0;
- double distFromLftM = 0.0;
-
- for (Map.Entry<String, Domain> colCheckk : originalDomainRowCol.entrySet()) {
- if (colCheckk.getValue().getName().equals(d.getName())) {
- orgColofDisplayed = Character.getNumericValue(colCheckk.getKey().toCharArray()[1]);
- break;
- }
- }
-
- for (Domain collapsed : getCollapsedDomainsNewList()) {
- for (Map.Entry<String, Domain> colCheck : originalDomainRowCol.entrySet()) {
- if (colCheck.getValue().getName().equals(collapsed.getName())) {
- orgColofCollapsed = Character.getNumericValue(colCheck.getKey().toCharArray()[1]);
- break;
- }
- }
-
- if (orgColofCollapsed < orgColofDisplayed) {
- distFromLftM+= 2;
- }
- }
- return distFromLftM;
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.support;
-
-import java.io.Serializable;
-
-
-public class NameValueId implements Serializable {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private String lab;
- private String val;
-
- public NameValueId() {
- }
-
- public NameValueId(String value, String label) {
- setVal(value);
- setLab(label);
- }
-
-
- public String getLab() {
- return lab;
- }
-
-
- public String getVal() {
- return val;
- }
-
-
- public void setLab(String label) {
- this.lab = label;
- }
-
-
- public void setVal(String value) {
- this.val = value;
- }
-
-
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
-
- if (o == null) {
- return false;
- }
-
- if (!(o instanceof NameValueId)) {
- return false;
- }
-
- final NameValueId nameValueId = (NameValueId)o;
-
- if (!getVal().equals(nameValueId.getVal())) {
- return false;
- }
-
- if (!getLab().equals(nameValueId.getLab())) {
- return false;
- }
-
- return true;
- }
-
-
- public int hashCode() {
- return getVal().hashCode();
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.support;
-
-public class Position {
- double x;
- double y;
-
- public double getX() {
- return x;
- }
- public void setX(double x) {
- this.x = x;
- }
- public double getY() {
- return y;
- }
- public void setY(double y) {
- this.y = y;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.domain.support;
-
-public class Size {
- private double width;
- private double height;
-
- public double getWidth() {
- return width;
- }
- public void setWidth(double width) {
- this.width = width;
- }
- public double getHeight() {
- return height;
- }
- public void setHeight(double height) {
- this.height = height;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.drools;
-
-public interface DroolsRuleService {
-
- public void init(String... params);
- public String getResultsString();
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.drools;
-
-
-/**
- *
- * This is POC test class to execute sample rules
- */
-public class DroolsRuleServiceImpl implements DroolsRuleService{
-
-
- private String state;
- private String resultsString;
-
- public DroolsRuleServiceImpl() {
-
- }
-
- public void init(String... params) {
- this.state = params[0];
- }
-
-
-
- public String getState() {
- return state;
- }
-
- public String accessLabel() {
- return "Drools POC Test";
- }
-
- public String getResultsString() {
- return resultsString;
- }
-
- public void setResultsString(String resultsString) {
- this.resultsString = resultsString;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.exception;
-
-import org.springframework.web.bind.annotation.ControllerAdvice;
-import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.servlet.ModelAndView;
-
-@ControllerAdvice
-public class FusionExceptionResolver {
-
- @ExceptionHandler(UrlAccessRestrictedException.class)
- public ModelAndView handleUrlAccessException(UrlAccessRestrictedException ex) {
- ModelAndView model = new ModelAndView("error");
- model.addObject("errMsg", ex.getMessage());
- return model;
-
- }
- @ExceptionHandler(SessionExpiredException.class)
- public ModelAndView handleSessionException(SessionExpiredException ex) {
- ModelAndView model = new ModelAndView("error");
- model.addObject("errMsg", ex.getMessage());
- return model;
- }
- @ExceptionHandler(Exception.class)
- public ModelAndView handleAllException(Exception ex) {
- ModelAndView model = new ModelAndView("error");
- model.addObject("errMsg", ex.getMessage());
- return model;
-
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.exception;
-
-import org.openecomp.portalsdk.core.exception.support.FusionRuntimeException;
-
-public class SessionExpiredException extends FusionRuntimeException {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public static final String MESSAGE = "Your session has expired. Please login again.";
-
- public SessionExpiredException() {
- super(MESSAGE);
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.exception;
-
-import org.openecomp.portalsdk.core.exception.support.FusionRuntimeException;
-
-public class UrlAccessRestrictedException extends FusionRuntimeException {
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public static final String MESSAGE = "Authorization Denied";
-
- public UrlAccessRestrictedException() {
- super(MESSAGE);
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.exception.support;
-
-import org.openecomp.portalsdk.core.FusionObject;
-
-public interface FusionException extends FusionObject {}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.exception.support;
-
-public class FusionRuntimeException extends RuntimeException implements FusionException {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public FusionRuntimeException() {
- this("");
- }
-
- public FusionRuntimeException(String message) {
- super(message);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.interceptor;
-
-import java.net.HttpURLConnection;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import org.openecomp.portalsdk.core.controller.FusionBaseController;
-import org.openecomp.portalsdk.core.domain.App;
-import org.openecomp.portalsdk.core.exception.UrlAccessRestrictedException;
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager;
-import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
-import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.service.LoginService;
-import org.openecomp.portalsdk.core.service.UrlAccessService;
-import org.openecomp.portalsdk.core.service.WebServiceCallService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.method.HandlerMethod;
-import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
-
-public class ResourceInterceptor extends HandlerInterceptorAdapter {
- public static final String APP_METADATA = "APP.METADATA";
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ResourceInterceptor.class);
-
- @Autowired
- private DataAccessService dataAccessService;
- @Autowired
- private LoginService loginService;
- @Autowired
- private WebServiceCallService webServiceCallService;
-
- private AbstractCacheManager cacheManager;
-
- @Autowired
- UrlAccessService urlAccessService;
-
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
- throws Exception {
- String uri = request.getRequestURI();
- String url = uri.substring(uri.indexOf("/", 1) + 1);
- logger.info(EELFLoggerDelegate.debugLogger, "Url - " + url);
- logger.info(EELFLoggerDelegate.debugLogger, "lastIndexOf - " + uri.substring(uri.lastIndexOf("/") + 1));
- if (handler instanceof HandlerMethod) {
- HandlerMethod method = (HandlerMethod) handler;
- FusionBaseController controller = (FusionBaseController) method.getBean();
- if (!controller.isAccessible()) {
- if (controller.isRESTfulCall()) {
- // check user authentication for RESTful calls
- String secretKey = null;
- try {
- if (!webServiceCallService.verifyRESTCredential(secretKey, request.getHeader("username"),
- request.getHeader("password"))) {
- logger.error(EELFLoggerDelegate.errorLogger, "Error accesing RESTful service. Un-authorized",AlarmSeverityEnum.MINOR);
- throw new UrlAccessRestrictedException();
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Error authenticating RESTful service :" + e,AlarmSeverityEnum.MINOR);
- //throw new UrlAccessRestrictedException();
- HttpSession httpSession = request.getSession();
- ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
- return false;
- }
- }
- if (!urlAccessService.isUrlAccessible(request, url)) {
- logger.error(EELFLoggerDelegate.errorLogger, "Error accesing URL. Un-authorized",AlarmSeverityEnum.MINOR);
- throw new UrlAccessRestrictedException();
- }
- }
- }
-
- logger.debug("successfully authorized rest call");
- logger.info(EELFLoggerDelegate.debugLogger, "successfully authorized rest call");
- handleSessionUpdates(request);
- logger.debug("handled session updates for synchronization");
- logger.info(EELFLoggerDelegate.debugLogger, "handled session updates for synchronization");
- return super.preHandle(request, response, handler);
- }
-
- /**
- *
- * @param request
- */
- protected void handleSessionUpdates(HttpServletRequest request) {
-
- App app = null;
- Object appObj = getCacheManager().getObject(APP_METADATA);
- if (appObj == null) {
- app = findApp();
- getCacheManager().putObject(APP_METADATA, app);
-
- } else {
- app = (App) appObj;
- }
-
- String ecompRestURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
- String decreptedPwd = "";
- try {
- decreptedPwd = CipherUtil.decrypt(app.getAppPassword(),
- SystemProperties.getProperty(SystemProperties.Decryption_Key));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Could not decrypt Password" + e.getMessage(),AlarmSeverityEnum.MINOR);
- }
-
- PortalTimeoutHandler.handleSessionUpdatesNative(request, app.getUsername(), decreptedPwd,
- PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), ecompRestURL, null);
- }
-
- public App findApp() {
- List<?> list = null;
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where id = 1");
- list = getDataAccessService().getList(App.class, criteria.toString(), null, null);
- return (list == null || list.size() == 0) ? null : (App) list.get(0);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- public LoginService getLoginService() {
- return loginService;
- }
-
- public void setLoginService(LoginService loginService) {
- this.loginService = loginService;
- }
-
- @Autowired
- public void setCacheManager(AbstractCacheManager cacheManager) {
- this.cacheManager = cacheManager;
- }
-
- public AbstractCacheManager getCacheManager() {
- return cacheManager;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.interceptor;
-
-import java.net.URLEncoder;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import org.openecomp.portalsdk.core.controller.FusionBaseController;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.exception.SessionExpiredException;
-import org.openecomp.portalsdk.core.listener.CollaborateListBindingListener;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.web.method.HandlerMethod;
-import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
-
-public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionTimeoutInterceptor.class);
-
- public SessionTimeoutInterceptor() {
- }
-
- /**
- * Checks all requests for valid session information. If not found,
- * redirects to a controller that will establish a valid session.
- */
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
- throws Exception {
- if (handler instanceof HandlerMethod) {
- HandlerMethod method = (HandlerMethod) handler;
- FusionBaseController controller = (FusionBaseController) method.getBean();
- if (!controller.isAccessible() && !controller.isRESTfulCall()) {
- try {
- // getSession() throws SessionExpiredException
- HttpSession session = AppUtils.getSession(request);
- User user = UserUtils.getUserSession(request);
- // check if user is logging out
- if (request.getRequestURI().indexOf("logout.htm") > -1) {
- session.removeAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME);
- throw new SessionExpiredException();
- } else if (user == null) {
- // Jump to the redirection code
- throw new Exception("preHandle: user not found in session");
- } else {
- // session binding listener will add this value to the
- // map, and with session replication the listener will
- // fire in all tomcat instances
- session.setAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME,
- new CollaborateListBindingListener(user.getOrgUserId()));
- }
- } catch (Exception ex) {
- // get the path within the webapp that the user requested (no host name etc.)
- final String forwardUrl = request.getRequestURI().substring(request.getContextPath().length() + 1)
- + (request.getQueryString() == null ? "" : "?" + request.getQueryString());
- final String forwardUrlParm = "forwardURL=" + URLEncoder.encode(forwardUrl, "UTF-8");
- final String singleSignonPrefix = "/single_signon.htm?";
- if (ex instanceof SessionExpiredException) {
- // Session is expired; send to portal.
- // Redirect to an absolute path in the webapp; e.g., "/context/single_signon.htm"
- final String redirectUrl = request.getContextPath() + singleSignonPrefix + "redirectToPortal=Yes&" + forwardUrlParm;
- logger.debug(EELFLoggerDelegate.debugLogger, "preHandle: session is expired, redirecting to {}",
- redirectUrl);
- response.sendRedirect(redirectUrl);
- return false;
- } else {
- // Other issue; do not send to portal.
- // Redirect to an absolute path in the webapp; e.g., "/context/single_signon.htm"
- final String redirectUrl = request.getContextPath() + singleSignonPrefix + forwardUrlParm;
- logger.debug(EELFLoggerDelegate.debugLogger, "preHandle: took exception {}, redirecting to {}",
- ex.getMessage(), redirectUrl);
- response.sendRedirect(redirectUrl);
- return false;
- }
- }
- }
- }
-
- return super.preHandle(request, response, handler);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.interfaces;
-
-public interface SecurityInterface {
- public boolean isAccessible();
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.listener;
-
-import javax.servlet.ServletContext;
-import javax.servlet.annotation.WebListener;
-
-import org.openecomp.portalsdk.core.lm.FusionLicenseManager;
-import org.openecomp.portalsdk.core.lm.FusionLicenseManagerUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.ApplicationListener;
-import org.springframework.context.event.ContextRefreshedEvent;
-import org.springframework.stereotype.Component;
-
-@WebListener
-@Component
-public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> {
-
- @Autowired
- ServletContext context;
- @Autowired
- FusionLicenseManager lm;
- @Autowired
- FusionLicenseManagerUtils fusionLicenseManagerUtils;
-
-
- public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) {
- int licenseStatus = fusionLicenseManagerUtils.verifyLicense(context);
- context.setAttribute("licenseVerification", licenseStatus);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.listener;
-
-import java.io.Serializable;
-
-import javax.servlet.http.HttpSessionBindingEvent;
-import javax.servlet.http.HttpSessionBindingListener;
-
-import org.openecomp.portalsdk.core.domain.support.CollaborateList;
-
-public class CollaborateListBindingListener implements HttpSessionBindingListener, Serializable {
-
- private static final long serialVersionUID = 1L;
- private String userName;
- public static final String SESSION_ATTR_NAME = "CollaborateListSessionAttrName";
-
- public CollaborateListBindingListener(String _userName) {
- userName = _userName;
- }
-
- @Override
- public void valueBound(HttpSessionBindingEvent event) {
- final CollaborateListBindingListener value = ((CollaborateListBindingListener) event.getValue());
- CollaborateList.addUserName(value.getUserName());
-
- }
-
- @Override
- public void valueUnbound(HttpSessionBindingEvent event) {
- final CollaborateListBindingListener value = ((CollaborateListBindingListener) event.getValue());
- if (value != null)
- CollaborateList.delUserName(value.getUserName());
- }
-
- public String getUserName() {
- return userName;
- }
-
- public void setUserName(String userName) {
- this.userName = userName;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.listener;
-
-import javax.servlet.annotation.WebListener;
-import javax.servlet.http.HttpSession;
-import javax.servlet.http.HttpSessionEvent;
-import javax.servlet.http.HttpSessionListener;
-
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
-
-@WebListener
-public class UserSessionListener implements HttpSessionListener{
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserSessionListener.class);
-
- public void sessionCreated(HttpSessionEvent event){
-
- }
-
- /**
- * Removes sessions from the context scoped HashMap when they expire
- * or are invalidated.
- */
- public void sessionDestroyed(HttpSessionEvent event){
- try {
- HttpSession session = event.getSession();
- session.removeAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME);
-
- // Object user = session.getAttribute(SystemProperties.getProperty("user.attribute.name"));
-
- //if( user != null)
- // {
- session.removeAttribute(CollaborateListBindingListener.SESSION_ATTR_NAME);
- //CollaborateList.getInstance().delUserName(user.getOrgUserId());
- // }
-
- }
- catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "sessionDestroyed" + e.getMessage(),AlarmSeverityEnum.MINOR);
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.lm;
-
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.ServletContext;
-
-//import de.schlichtherle.license.LicenseContent;
-
-public interface FusionLicenseManager {
-
-
- public static final int DEVELOPER_LICENSE = 0;
- public static final int EXPIRED_LICENSE = 1;
- public static final int VALID_LICENSE = 2;
- public static final int INVALID_LICENSE = 3;
- public static final int OPENSOURCE_LICENSE = 4;
-
- public void initKeyStoreParam();
-
- public void initCipherParam();
-
- public void initLicenseParam();
-
- public void doInitWork();
-
- public int installLicense();
-
- public int verifyLicense(ServletContext context);
-
- //public LicenseContent createLicenseContent(Map<String, String> clientInfoMap, List<String> ipAddressList);
-
- public void generateLicense(Map<String, String> clientInfoMap, List<String> ipAddressList) throws Exception;
-
- public String nvl(String s);
-
- public Date getExpiredDate();
-
- public void setExpiredDate(Date expiredDate);
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.lm;
-
-import java.util.Date;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.util.SystemProperties;
-//import org.openecomp.portalapp.lm.FusionLicenseManagerImpl;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-import org.springframework.web.context.WebApplicationContext;
-import org.springframework.web.servlet.support.RequestContextUtils;
-
-@Component
-public class FusionLicenseManagerUtils {
-
- @Autowired
- private FusionLicenseManager licenseManager;
-
- @Autowired
- private SystemProperties sysProps;
- static {
- }
-
- public int verifyLicense(ServletContext context) {
- if(sysProps == null) {
- try {
- sysProps = new SystemProperties();
- sysProps.setServletContext(context);
-// sysProps.load();
-// licenseManager = new FusionLicenseManagerImpl(new LicenseableClassImpl());
- System.out.println(licenseManager);
- licenseManager.installLicense();
- }
- catch(Exception ex) {
- ex.printStackTrace();
- }
- }
-
-
-
-// WebApplicationContext ctx =RequestContextUtils.getWebApplicationContext(request);
-// int flag = ((FusionLicenseManager)ctx.getBean("fusionLicenseManager")).verifyLicense(request);
-// logger.debug("****************FLAG ******************** " + flag);
-// return flag;
-// return 2;
- return licenseManager.verifyLicense(context);
- }
-
- public static Date getLicenseExpiryDate(HttpServletRequest request) {
- WebApplicationContext ctx =RequestContextUtils.getWebApplicationContext(request);
- return ((FusionLicenseManager)ctx.getBean("fusionLicenseManager")).getExpiredDate();
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.lm;
-
-import java.io.*;
-
-/**
- * created by Alvin Alexander of http://devdaily.com.
- * modified by Sundar Ramalingam
- */
-public interface LicenseableClass
-{
- public String getApplicationName();
- public InputStream getPublicKeystoreAsInputStream() throws FileNotFoundException;
- public String getAlias();
- public String getPublicKeystorePassword();
- public String getKeyPasswd();
- public String getCipherParamPassword();
- public Class getClassToLicense();
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.logging.aspect;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-
-@Target({ElementType.METHOD, ElementType.TYPE})
-@Retention(RetentionPolicy.RUNTIME)
-public @interface AuditLog {
- String value() default "";
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.logging.aspect;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.logging.format.AuditLogFormatter;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.AppService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import com.att.eelf.configuration.Configuration;
-
-@org.springframework.context.annotation.Configuration
-public class EELFLoggerAdvice {
-
- @Autowired
- AppService appService;
-
- EELFLoggerDelegate adviceLogger = EELFLoggerDelegate.getLogger(EELFLoggerAdvice.class);
-
- // DateTime Format according to the ECOMP Application Logging Guidelines.
- private static final SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
-
- /**
- * Gets the current date and time in expected ECOMP log format.
- *
- * @return Current date and time
- */
- public static String getCurrentDateTimeUTC() {
- String currentDateTime = ecompLogDateFormat.format(new Date());
- return currentDateTime;
- }
-
- /**
- *
- * @param securityEventType
- * @param args
- * @param passOnArgs
- * @return One-element array containing an empty String object.
- */
- public Object[] before(SecurityEventTypeEnum securityEventType, Object[] args, Object[] passOnArgs) {
- try {
- String className = "";
- if (passOnArgs[0] != null) {
- className = passOnArgs[0].toString();
- }
-
- String methodName = "";
- if (passOnArgs[1] != null) {
- methodName = passOnArgs[1].toString();
- }
-
- String appName = appService.getDefaultAppName();
- if (appName == null || appName == "") {
- appName = SystemProperties.SDK_NAME;
- }
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className);
-
- // Initialize Request defaults only for controller methods.
- MDC.put(className + methodName + SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC());
- MDC.put(SystemProperties.TARGET_ENTITY, appName + "_BE");
- MDC.put(SystemProperties.TARGET_SERVICE_NAME, methodName);
- if (securityEventType != null) {
- MDC.put(className + methodName + SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC());
- HttpServletRequest req = null;
- if (args[0] != null && args[0] instanceof HttpServletRequest) {
- req = (HttpServletRequest) args[0];
- logger.setRequestBasedDefaultsIntoGlobalLoggingContext(req, appName);
- }
- }
- logger.debug(EELFLoggerDelegate.debugLogger, (methodName + " was invoked."));
- } catch (Exception e) {
- adviceLogger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred in EELFLoggerAdvice.before() method. Details: " + e.getMessage());
- }
-
- return new Object[] { "" };
- }
-
- /**
- *
- * @param securityEventType
- * @param result
- * @param args
- * @param returnArgs
- * @param passOnArgs
- */
- public void after(SecurityEventTypeEnum securityEventType, String result, Object[] args, Object[] returnArgs,
- Object[] passOnArgs) {
- try {
- String className = "";
- if (passOnArgs[0] != null) {
- className = passOnArgs[0].toString();
- }
-
- String methodName = "";
- if (passOnArgs[1] != null) {
- methodName = passOnArgs[1].toString();
- }
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className);
-
- String appName = appService.getDefaultAppName();
- if (appName == null || appName == "") {
- appName = SystemProperties.SDK_NAME;
- }
-
- if (MDC.get(SystemProperties.TARGET_SERVICE_NAME) == null
- || MDC.get(SystemProperties.TARGET_SERVICE_NAME) == "") {
- MDC.put(SystemProperties.TARGET_SERVICE_NAME, methodName);
- }
-
- if (MDC.get(SystemProperties.TARGET_ENTITY) == null || MDC.get(SystemProperties.TARGET_ENTITY) == "") {
- MDC.put(SystemProperties.TARGET_ENTITY, appName + "_BE");
- }
-
- MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP,
- MDC.get(className + methodName + SystemProperties.METRICSLOG_BEGIN_TIMESTAMP));
- MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, getCurrentDateTimeUTC());
- this.calculateDateTimeDifference(MDC.get(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP),
- MDC.get(SystemProperties.METRICSLOG_END_TIMESTAMP));
-
- logger.info(EELFLoggerDelegate.metricsLogger, methodName + " operation is completed.");
- logger.debug(EELFLoggerDelegate.debugLogger, "Finished executing " + methodName + ".");
-
- if (securityEventType != null) {
-
- MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
- MDC.get(className + methodName + SystemProperties.AUDITLOG_BEGIN_TIMESTAMP));
- MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, getCurrentDateTimeUTC());
- this.calculateDateTimeDifference(MDC.get(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
- MDC.get(SystemProperties.AUDITLOG_END_TIMESTAMP));
-
- this.logSecurityMessage(logger, securityEventType, result, methodName);
-
- // clear when finishes audit logging
- MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
- MDC.remove(SystemProperties.PARTNER_NAME);
- MDC.remove(SystemProperties.MDC_LOGIN_ID);
- MDC.remove(SystemProperties.PROTOCOL);
- MDC.remove(SystemProperties.FULL_URL);
- MDC.remove(Configuration.MDC_SERVICE_NAME);
- MDC.remove(SystemProperties.RESPONSE_CODE);
- MDC.remove(SystemProperties.STATUS_CODE);
- MDC.remove(className + methodName + SystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(SystemProperties.AUDITLOG_END_TIMESTAMP);
- }
-
- MDC.remove(className + methodName + SystemProperties.METRICSLOG_BEGIN_TIMESTAMP);
- MDC.remove(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP);
- MDC.remove(SystemProperties.METRICSLOG_END_TIMESTAMP);
- MDC.remove(SystemProperties.MDC_TIMER);
- MDC.remove(SystemProperties.TARGET_ENTITY);
- MDC.remove(SystemProperties.TARGET_SERVICE_NAME);
- } catch (Exception e) {
- adviceLogger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred in EELFLoggerAdvice.after() method. Details: " + e.getMessage());
- }
- }
-
- /**
- *
- * @param logger
- * @param securityEventType
- * @param result
- * @param restMethod
- */
- private void logSecurityMessage(EELFLoggerDelegate logger, SecurityEventTypeEnum securityEventType, String result,
- String restMethod) {
- StringBuilder additionalInfoAppender = new StringBuilder();
- String auditMessage = "";
-
- additionalInfoAppender.append(String.format("%s request was received.", restMethod));
-
- // Status code
- MDC.put(SystemProperties.STATUS_CODE, result);
-
- String fullURL = MDC.get(SystemProperties.FULL_URL);
- if (fullURL != null && fullURL != "") {
- additionalInfoAppender.append(" Request-URL:" + MDC.get(SystemProperties.FULL_URL));
- }
-
- auditMessage = AuditLogFormatter.getInstance().createMessage(MDC.get(SystemProperties.PROTOCOL),
- securityEventType.name(), MDC.get(SystemProperties.MDC_LOGIN_ID), additionalInfoAppender.toString());
-
- logger.info(EELFLoggerDelegate.auditLogger, auditMessage);
- }
-
- /**
- *
- * @param beginDateTime
- * @param endDateTime
- */
- private void calculateDateTimeDifference(String beginDateTime, String endDateTime) {
- if (beginDateTime != null && endDateTime != null) {
- try {
- Date beginDate = ecompLogDateFormat.parse(beginDateTime);
- Date endDate = ecompLogDateFormat.parse(endDateTime);
- String timeDifference = String.format("%d ms", endDate.getTime() - beginDate.getTime());
- MDC.put(SystemProperties.MDC_TIMER, timeDifference);
- } catch (Exception e) {
- adviceLogger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred in EELFLoggerAdvice.calculateDateTimeDifference() method. Details: "
- + e.getMessage());
- }
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.logging.aspect;
-
-import org.aspectj.lang.ProceedingJoinPoint;
-import org.aspectj.lang.annotation.Around;
-import org.aspectj.lang.annotation.Aspect;
-import org.aspectj.lang.annotation.Pointcut;
-import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
-import org.springframework.beans.factory.annotation.Autowired;
-
-
-@Aspect
-@org.springframework.context.annotation.Configuration
-public class EELFLoggerAspect {
-
- @Autowired
- EELFLoggerAdvice advice;
-
- /*
- * Point-cut expression to handle all INCOMING_REST_MESSAGES
- */
- @Pointcut("execution(public * org.openecomp.portalsdk.core.controller.*.*(..))")
- public void incomingAuditMessages() {}
-
- @Around("incomingAuditMessages() && @annotation(auditLog)")
- public Object logAuditMethodAround(ProceedingJoinPoint joinPoint, AuditLog auditLog) throws Throwable {
- return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
- }
-
- @Around("incomingAuditMessages() && @within(auditLog)")
- public Object logAuditMethodClassAround(ProceedingJoinPoint joinPoint, AuditLog auditLog) throws Throwable {
- return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
- }
-
- /*
- * Point cut expression to capture metrics logging
- */
- @Pointcut("execution(public * *(..))")
- public void publicMethod() {}
-
- @Around("publicMethod() && @within(metricsLog)")
- public Object logMetricsClassAround(ProceedingJoinPoint joinPoint, MetricsLog metricsLog) throws Throwable {
- return this.logAroundMethod(joinPoint, null);
- }
-
- @Around("publicMethod() && @annotation(metricsLog)")
- public Object logMetricsMethodAround(ProceedingJoinPoint joinPoint, MetricsLog metricsLog) throws Throwable {
- return this.logAroundMethod(joinPoint, null);
- }
-
- private Object logAroundMethod(ProceedingJoinPoint joinPoint, SecurityEventTypeEnum securityEventType) throws Throwable {
- //Before
- Object[] passOnArgs = new Object[] {joinPoint.getSignature().getDeclaringType().getName(),joinPoint.getSignature().getName()};
- Object[] returnArgs = advice.before(securityEventType, joinPoint.getArgs(), passOnArgs);
-
- //Execute the actual method
- Object result = null;
- String restStatus = "COMPLETE";
- try {
- result = joinPoint.proceed();
- } catch(Exception e) {
- restStatus = "ERROR";
- }
-
- //After
- advice.after(securityEventType, restStatus, joinPoint.getArgs(), returnArgs, passOnArgs);
-
- return result;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.logging.aspect;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-
-@Target({ElementType.METHOD, ElementType.TYPE})
-@Retention(RetentionPolicy.RUNTIME)
-public @interface MetricsLog {
- String value() default "";
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.logging.format;
-
-public enum AlarmSeverityEnum {
- CRITICAL,
- MAJOR,
- MINOR,
- INFORMATIONAL,
- NONE,
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.logging.format;
-
-public enum AppMessagesEnum {
- /*
- 100-199 Security/Permission Related
- - Authentication problems (from external client, to external server)
- - Certification errors
- -
-
- 200-299 Availability/Timeout Related
- - connectivity error
- - connection timeout
-
- 300-399 Data Access/Integrity Related
- - Data in graph in invalid(E.g. no creator is found for service)
- - Artifact is missing in ES, but exists in graph.
-
- 400-499 Schema Interface Type/Validation
- - received Pay-load checksum is invalid
- - received JSON is not valid
-
- 500-599 Business/Flow Processing Related
- - check out to service is not allowed
- - Roll-back is done
- - failed to generate heat file
-
-
- 600-899 Reserved - do not use
-
- 900-999 Unknown Errors
- - Unexpected exception
- */
-
- BeUebAuthenticationError(ErrorCodesEnum.BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR100E", "An Authentication failure occurred during access to UEB server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
-
- BeRestApiAuthenticationError(ErrorCodesEnum.BERESTAPIAUTHENTICATIONERROR, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR101E", "Rejected an incoming REST API request due to invalid credentials", "", "Please check application credentials defined in Database or properties files."),
-
- InternalAuthenticationInfo(ErrorCodesEnum.INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR199I", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
-
- InternalAuthenticationWarning(ErrorCodesEnum.INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
- "ERR199W", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
-
- InternalAuthenticationError(ErrorCodesEnum.INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR199E", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
-
- InternalAuthenticationFatal(ErrorCodesEnum.INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL,
- "ERR199F", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
-
- BeHealthCheckError(ErrorCodesEnum.BeHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR200E", "ECOMP-PORTAL Back-end probably lost connectivity to either one of the following components: MySQL DB, UEB Cluster", "", "Please check the logs for more information."),
-
- BeHealthCheckMySqlError(ErrorCodesEnum.BEHEALTHCHECKMYSQLERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR201E", "ECOMP-PORTAL Back-end probably lost connectivity to MySQL DB", "", "Check connectivity to MYSQL is configured correctly under system.properties file."),
-
- BeHealthCheckUebClusterError(ErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR203E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "", "Check connectivity to UEB cluster which is configured under portal.properties file."),
-
- FeHealthCheckError(ErrorCodesEnum.FEHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR204E", "Unable to connect to a valid ECOMP-PORTAL Back-end Server.", "", "Please check connectivity from this FE instance towards BE or BE Load Balancer."),
-
- BeHealthCheckRecovery(ErrorCodesEnum.BEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR205I", "ECOMP-PORTAL Back-end Recovery to either one of the following components: MySQL DB, UEB Cluster", "", "Please check logs for more specific information about the problem."),
-
- BeHealthCheckMySqlRecovery(ErrorCodesEnum.BEHEALTHCHECKMYSQLRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR206I", "ECOMP-PORTAL Back-end connection recovery to MySQL DB", "", "Please check logs for more specific information about the problem."),
-
- BeHealthCheckUebClusterRecovery(ErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR208I", "ECOMP-PORTAL Back-end connection recovery to UEB Cluster", "", "Please check logs for more specific information about the problem."),
-
- FeHealthCheckRecovery(ErrorCodesEnum.FEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR209I", "Connectivity to ECOMP-PORTAL Front-end Server is recovered", "", "Please check logs for more specific information about the problem."),
-
- BeUebConnectionError(ErrorCodesEnum.BEUEBCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR210E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
-
- BeUebUnkownHostError(ErrorCodesEnum.BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR211E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Cannot reach host: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
-
- BeUebRegisterOnboardingAppError(ErrorCodesEnum.BEUEBREGISTERONBOARDINGAPPERROR, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR212E", "Failed to register the On-boarding application with UEB Communication server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
-
- BeHttpConnectionError(ErrorCodesEnum.BEHTTPCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR213E", "It could be that communication to an external application might resulted an exception or failed to reach the external application",
- "Details: {0}.", "Please check logs for more information."),
-
- InternalConnectionInfo(ErrorCodesEnum.INTERNALCONNECTIONINFO_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR299I", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
-
- InternalConnectionWarning(ErrorCodesEnum.INTERNALCONNECTIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
- "ERR299W", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
-
- InternalConnectionError(ErrorCodesEnum.INTERNALCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR299E", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
-
- InternalConnectionFatal(ErrorCodesEnum.INTERNALCONNECTIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL,
- "ERR299F", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
-
- BeUebObjectNotFoundError(ErrorCodesEnum.BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR303E", "Error occurred during access to U-EB Server.", "Data not found: {0}.", "An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic."),
-
- BeUserMissingError(ErrorCodesEnum.BEUSERMISSINGERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR310E", "User is not found", "", "User {0} must be added to the corresponding application with proper user roles."),
-
- BeUserInactiveWarning(ErrorCodesEnum.BEUSERINACTIVEWARNING_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
- "ERR313W", "User is found but in-active", "", "User {0} must be added to the corresponding application with proper user roles."),
-
- BeUserAdminPrivilegesInfo(ErrorCodesEnum.BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
- "ERR314W", "User is found but don't have administrative privileges", "", "User {0} should be given administrator role for the corresponding application to perform the necessary actions."),
-
- BeInvalidJsonInput(ErrorCodesEnum.BEINVALIDJSONINPUT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR405E", "Failed to convert JSON input to object", "", "Please check logs for more information."),
-
- BeIncorrectHttpStatusError(ErrorCodesEnum.BEINCORRECTHTTPSTATUSERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR407E", "Communication to an external application is resulted in with Incorrect Http response code", "", "Please check logs for more information."),
-
- BeInitializationError(ErrorCodesEnum.BEINITIALIZATIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR500E", "ECOMP-PORTAL Back-end was not initialized properly", "", "Please check logs for more information."),
-
- BeUebSystemError(ErrorCodesEnum.BEUEBSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR502E", "Error occurred during access to U-EB Server", "Details: {0}.", "An error occurred in {1} distribution mechanism. Please check the logs for more information."),
-
- BeDaoSystemError(ErrorCodesEnum.BEDAOSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR505E", "Performing DDL or DML operations on database might have failed", "", "Please check MySQL DB health or look at the logs for more details."),
-
- BeSystemError(ErrorCodesEnum.BESYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR506E", "Unexpected error during operation", "", "Please check logs for more information."),
-
- BeExecuteRollbackError(ErrorCodesEnum.BEEXECUTEROLLBACKERROR, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR507E", "Roll-back operation towards database has failed", "", "Please check MYSQL DB health or look at the logs for more details."),
-
- FeHttpLoggingError(ErrorCodesEnum.FEHTTPLOGGINGERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.ERROR,
- "ERR517E", "Error when logging FE HTTP request/response", "", "Please check MYSQL DB health or look at the logs for more details."),
-
- FePortalServletError(ErrorCodesEnum.FEPORTALSERVLETERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR518E", "Error when trying to access FE Portal page.", "", "Please check logs for more information."),
-
- BeDaoCloseSessionError(ErrorCodesEnum.BEDAOCLOSESESSIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR519E", "Close local session operation with database failed", "", "Please check MYSQL DB health or look at the logs form more details."),
-
- BeRestApiGeneralError(ErrorCodesEnum.BERESTAPIGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR900E", "Unexpected error during ECOMP-PORTAL Back-end REST API execution", "", "Please check error log for more information."),
-
- FeHealthCheckGeneralError(ErrorCodesEnum.FEHEALTHCHECKGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR901E", "General error during FE Health Check", "", "Please check error log for more information."),
-
- InternalUnexpectedInfo(ErrorCodesEnum.INTERNALUNEXPECTEDINFO_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR999I", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
-
- InternalUnexpectedWarning(ErrorCodesEnum.INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
- "ERR999W", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
-
- InternalUnexpectedError(ErrorCodesEnum.INTERNALUNEXPECTEDERROR_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR999E", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
-
- InternalUnexpectedFatal(ErrorCodesEnum.INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL,
- "ERR999F", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
-
- ;
-
- ErrorTypeEnum eType;
- AlarmSeverityEnum alarmSeverity;
- ErrorCodesEnum messageCode;
- ErrorSeverityEnum errorSeverity;
- String errorCode;
- String errorDescription;
- String details;
- String resolution;
-
- AppMessagesEnum(ErrorCodesEnum messageCode, ErrorTypeEnum eType, AlarmSeverityEnum alarmSeverity, ErrorSeverityEnum errorSeverity, String errorCode, String errorDescription,
- String details, String resolution) {
- this.messageCode = messageCode;
- this.eType = eType;
- this.alarmSeverity = alarmSeverity;
- this.errorSeverity = errorSeverity;
- this.errorCode = errorCode;
- this.errorDescription = errorDescription;
- this.details = details;
- this.resolution = resolution;
- }
-
- public String getDetails() {
- return this.details;
- }
-
- public String getResolution() {
- return this.resolution;
- }
- public String getErrorCode() {
- return this.errorCode;
- }
-
- public String getErrorDescription() {
- return this.errorDescription;
- }
-
- public ErrorSeverityEnum getErrorSeverity() {
- return this.errorSeverity;
- }
-
- public void setErrorSeverity(ErrorSeverityEnum errorSeverity) {
- this.errorSeverity = errorSeverity;
- }
-
- public ErrorCodesEnum getMessageCode() {
- return messageCode;
- }
-
- public void setMessageCode(ErrorCodesEnum messageCode) {
- this.messageCode = messageCode;
- }
-
- public AlarmSeverityEnum getAlarmSeverity() {
- return alarmSeverity;
- }
-
- public void setAlarmSeverity(AlarmSeverityEnum alarmSeverity) {
- this.alarmSeverity = alarmSeverity;
- }
-
- public ErrorTypeEnum getErrorType() {
- return eType;
- }
-
- public void setErrorType(ErrorTypeEnum eType) {
- this.eType = eType;
- }
-}
+++ /dev/null
-###
-# ================================================================================
-# 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.
-# ================================================================================
-###
-########################################################################
-#Resource key=Error Code|Message text|Resolution text |Description text
-#######
-#Newlines can be utilized to add some clarity ensuring continuing line
-#has atleast one leading space
-#ResourceKey=\
-# ERR0000E\
-# Sample error msg txt\
-# Sample resolution msg\
-# Sample description txt
-#
-######
-#Error code classification category
-#100 Permission errors
-#200 Availability errors/Timeouts
-#300 Data errors
-#400 Schema Interface type/validation errors
-#500 Business process errors
-#900 Unknown errors
-#
-########################################################################
-
-#Health check
-BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT=\
- ERR100E|\
- Authentication problem towards U-EB server. Reason: {0}.|\
- An Authentication failure occurred during access to UEB server. Please check that UEB keys are configured correctly under fusion.properties file.|
-
-BERESTAPIAUTHENTICATIONERROR =\
- ERR101E|\
- Rejected an incoming REST API request to {0} from {1} due to invalid credentials.|\
- Please check application credentials defined in Database or portal.properties file.|
-
-INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT=\
- ERR199I|\
- Internal authentication problem. Description: {0}.|
-
-INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT=\
- ERR199W|\
- Internal authentication problem. Description: {0}.|
-
-INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT=\
- ERR199E|\
- Internal authentication problem. Description: {0}.|
-
-INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT=\
- ERR199F|\
- Internal authentication problem. Description: {0}.|
-
-BEHEALTHCHECKERROR=\
- ERR200E|\
- {0} probably lost connectivity to either one of the following components: MySQL DB, UEB Cluster. Please check the logs for more information.|
-
-BEHEALTHCHECKMYSQLERROR=\
- ERR201E|\
- {0} probably lost connectivity to MySQL DB. Please check the logs for more information.|\
- Check connectivity to MYSQL is configured correctly under system.properties file.|
-
-BEHEALTHCHECKUEBCLUSTERERROR=\
- ERR203E|\
- {0} probably lost connectivity to UEB Cluster. Please check the logs for more information.|\
- Check connectivity to UEB cluster which is configured under portal.properties file.|
-
-BEHEALTHCHECKRECOVERY=\
- ERR205I|\
- {0} Recovery to either one of the following components: MySQL DB, UEB Cluster.|
-
-BEHEALTHCHECKMYSQLRECOVERY=\
- ERR206I|\
- {0} connection recovery to MySQL DB.|
-
-BEHEALTHCHECKUEBCLUSTERRECOVERY=\
- ERR208I|\
- {0} connection recovery to UEB Cluster.|
-
-FEHEALTHCHECKRECOVERY=\
- ERR209I|\
- Connectivity to {0} Server is recovered.|
-
-#UEB communication
-BEUEBCONNECTIONERROR_ONE_ARGUMENT=\
- ERR210E|\
- Connection problem towards U-EB server. Reason: {0}.|\
- Please check that that parameter uebServers in portal.properties points to a valid UEB Cluster.|
-
-BEUEBSYSTEMERROR=\
- ERR502E|\
- Error occurred during access to U-EB Server. Operation: {0}.|\
- An error occurred in {1} distribution mechanism. Please check the logs for more information.|
-
-BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT=\
- ERR211E|\
- Connection problem towards U-EB server. Cannot reach host {0}.|\
- Please check that that parameter uebServers in portal.properties points to a valid UEB Cluster.|
-
-#Onboarding apps
-BEUEBREGISTERONBOARDINGAPPERROR=\
- ERR212E|\
- Unable to register the On-boarding application with the U-EB server. Reason: {0}.|\
- Please check that that parameter uebServers in system.properties points to a valid UEB Cluster.|
-
-#HTTP communication
-BEHTTPCONNECTIONERROR_ONE_ARGUMENT=\
- ERR213E|\
- HTTP connection to an external application is failed. Reason: {0}.|\
- Please check the logs for more information.|
-
-INTERNALCONNECTIONINFO_ONE_ARGUMENT=\
- ERR299I|\
- Internal Connection problem. Description: {0}.|
-
-INTERNALCONNECTIONWARNING_ONE_ARGUMENT=\
- ERR299W|\
- Internal Connection problem. Description: {0}.|
-
-INTERNALCONNECTIONERROR_ONE_ARGUMENT=\
- ERR299E|\
- Internal Connection problem. Description: {0}.|
-
-INTERNALCONNECTIONFATAL_ONE_ARGUMENT=\
- ERR299F|\
- Internal Connection problem. Description: {0}.|
-
-BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT=\
- ERR303E|\
- Error occurred during access to U-EB Server. Data not found: {0}.|\
- An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic.|
-
-#Login error codes
-BEUSERMISSINGERROR_ONE_ARGUMENT=\
- ERR310E|\
- User {0} requested is not found.|
-
-BEUSERINACTIVEWARNING_ONE_ARGUMENT=\
- ERR313W|\
- User {0} is found but inactive.|
-
-BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT=\
- ERR314W|\
- User {0} is found but don't have administrative privileges.|
-
-BEINVALIDJSONINPUT=\
- ERR405E|\
- Failed to convert JSON input to object.|\
- Please check error logs for more information.|
-
-BEINCORRECTHTTPSTATUSERROR=\
- ERR407E|\
- Incorrect HttpResponse Received.|\
- Please check error & metrics logs for more information.|
-
-BEINITIALIZATIONERROR=\
- ERR500E|\
- BE was not initialized properly.|
-
-BEDAOSYSTEMERROR=\
- ERR505E|\
- Operation towards database failed.|\
- Please check MySQL DB health or look at the logs for more details.|
-
-BESYSTEMERROR=\
- ERR506E|\
- Unexpected error during operation.|
-
-BEEXECUTEROLLBACKERROR=\
- ERR507E|\
- Roll-back operation towards database failed.|\
- Please check MYSQL DB health or look at the logs for more details.|
-
-FEHTTPLOGGINGERROR=\
- ERR517E|\
- Error when logging FE HTTP request/response.|
-
-BEDAOCLOSESESSIONERROR=\
- ERR519E|\
- Close local session operation with database failed.|\
- Please check MYSQL DB health or look at the logs form more details.|
-
-BERESTAPIGENERALERROR=\
- ERR900E|\
- Unexpected error during BE REST API execution.|\
- Please check error log for more information.|
-
-FEHEALTHCHECKGENERALERROR=\
- ERR901E|\
- General error during FE Health Check.|
-
-INTERNALUNEXPECTEDINFO_ONE_ARGUMENT=\
- ERR999I|\
- Unexpected error. Description: {0}.|
-
-INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT=\
- ERR999W|\
- Unexpected error. Description: {0}.|
-
-INTERNALUNEXPECTEDERROR_ONE_ARGUMENT=\
- ERR999E|\
- Unexpected error. Description: {0}.|
-
-INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT=\
- ERR999F|\
- Unexpected error. Description: {0}.|
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.logging.format;
-
-import java.text.MessageFormat;
-import java.util.Map;
-
-import org.openecomp.portalsdk.core.util.SystemProperties;
-
-public class AuditLogFormatter {
- //Singleton
- private static AuditLogFormatter instance = new AuditLogFormatter();
-
- public static AuditLogFormatter getInstance() {
-
- return instance;
- }
-
- public String createMessage(String protocol,String set,
- String loginId, String message) {
-
- Object[] securityMessageArgs = prepareFormatArgs(
- protocol,
- set,
- loginId,
- message );
-
- return MessageFormat.format(SystemProperties.SECURITY_LOG_TEMPLATE, securityMessageArgs);
- }
-
- /**
- * A method for normalizing the security log field - returns
- * the @Param defaultValue in case the entry is null or empty.
- * If the @param entry is not empty, a single quotation is added to it.
- *
- * @param entry the entry
- * @param defaultValue The default value in case the entry is empty
- * @return String (formatted)
- */
- private String formatEntry(Object entry, String defaultValue) {
- return (entry!=null && !entry.toString().isEmpty()) ? addSingleQuotes(entry.toString()): defaultValue;
-
- }
-
- private String addSingleQuotes(String s) {
- if (null!=s && !s.isEmpty()) {
- s = SystemProperties.SINGLE_QUOTE+s+SystemProperties.SINGLE_QUOTE;
- }
- return s;
- }
-
-
- /**
- * This method prepares an Object array of arguments that would be passed
- * to the MessageFormat.format() method, to format the security log.
- *
- * @param protocol
- * @param set
- * @param loginId
- * @param accessingClient
- * @param isSuccess
- * @param message
- * @return
- */
- private Object[] prepareFormatArgs(String protocol,String set,
- String loginId, String message) {
-
- Object[] messageFormatArgs = {
- formatEntry(protocol, SystemProperties.NA),
- formatEntry(set, SystemProperties.NA),
- formatEntry(loginId, SystemProperties.UNKNOWN),
- message
- };
- return messageFormatArgs;
- }
-
-
- public String createMessage(Map<String, String> logArgsMap) {
-
- Object[] securityMessageArgs = prepareFormatArgs(
- logArgsMap.get(SystemProperties.PROTOCOL),
- logArgsMap.get(SystemProperties.SECURIRY_EVENT_TYPE),
- logArgsMap.get(SystemProperties.LOGIN_ID),
- logArgsMap.get(SystemProperties.ADDITIONAL_INFO)
- );
-
- return MessageFormat.format(SystemProperties.SECURITY_LOG_TEMPLATE, securityMessageArgs);
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.logging.format;
-
-import com.att.eelf.i18n.EELFResolvableErrorEnum;
-//import com.att.eelf.i18n.EELFResourceManager;
-
-public enum ErrorCodesEnum implements EELFResolvableErrorEnum {
- BERESTAPIAUTHENTICATIONERROR,
- BEHTTPCONNECTIONERROR_ONE_ARGUMENT,
- BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT,
-
- INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT,
- INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT,
- INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT,
- INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT,
-
- BEHEALTHCHECKRECOVERY,
- BEHEALTHCHECKMYSQLRECOVERY,
- BEHEALTHCHECKUEBCLUSTERRECOVERY,
- FEHEALTHCHECKRECOVERY,
- BeHEALTHCHECKERROR,
-
- BEHEALTHCHECKMYSQLERROR,
- BEHEALTHCHECKUEBCLUSTERERROR,
- FEHEALTHCHECKERROR,
- BEUEBCONNECTIONERROR_ONE_ARGUMENT,
- BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT,
- BEUEBREGISTERONBOARDINGAPPERROR,
-
- INTERNALCONNECTIONINFO_ONE_ARGUMENT,
- INTERNALCONNECTIONWARNING_ONE_ARGUMENT,
- INTERNALCONNECTIONERROR_ONE_ARGUMENT,
- INTERNALCONNECTIONFATAL_ONE_ARGUMENT,
-
- BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT,
- BEUSERMISSINGERROR_ONE_ARGUMENT,
-
- BEUSERINACTIVEWARNING_ONE_ARGUMENT,
- BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT,
-
- BEINVALIDJSONINPUT,
- BEINCORRECTHTTPSTATUSERROR,
-
- BEINITIALIZATIONERROR,
- BEUEBSYSTEMERROR,
- BEDAOSYSTEMERROR,
- BESYSTEMERROR,
- BEEXECUTEROLLBACKERROR,
-
- FEHTTPLOGGINGERROR,
- FEPORTALSERVLETERROR,
- BEDAOCLOSESESSIONERROR,
-
- BERESTAPIGENERALERROR,
- FEHEALTHCHECKGENERALERROR,
-
- INTERNALUNEXPECTEDINFO_ONE_ARGUMENT,
- INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT,
- INTERNALUNEXPECTEDERROR_ONE_ARGUMENT,
- INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT,
-
- ;
-
- /**
- * Static initializer to ensure the resource bundles for this class are loaded...
- * Here this application loads messages from three bundles
- */
- //static {
- // EELFResourceManager.loadMessageBundle("com/att/fusion/core/logging/format/ApplicationCodes");
- //}
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.logging.format;
-
-public enum ErrorSeverityEnum {
- INFO,
- WARN,
- ERROR,
- FATAL,
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.logging.format;
-
-public enum ErrorTypeEnum {
- RECOVERY,
- CONFIG_ERROR,
- SYSTEM_ERROR,
- DATA_ERROR,
- CONNECTION_PROBLEM,
- AUTHENTICATION_PROBLEM
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.logging.logic;
-
-import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
-import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
-import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
-import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
-import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
-import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
-import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
-
-import java.net.InetAddress;
-import java.text.MessageFormat;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.aspect.EELFLoggerAdvice;
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.format.AppMessagesEnum;
-import org.openecomp.portalsdk.core.logging.format.ErrorSeverityEnum;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.slf4j.MDC;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.att.eelf.configuration.SLF4jWrapper;
-
-public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger {
-
- public static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();
- public static EELFLogger applicationLogger = EELFManager.getInstance().getApplicationLogger();
- public static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
- public static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
- public static EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger();
- private String className;
- private static ConcurrentMap<String, EELFLoggerDelegate> classMap = new ConcurrentHashMap<String, EELFLoggerDelegate>();
-
- public EELFLoggerDelegate(String _className) {
- super(_className);
- className = _className;
- }
-
- /**
- * Convenience method that gets a logger for the specified class.
- *
- * @see #getLogger(String)
- *
- * @param clazz
- * @return Instance of EELFLoggerDelegate
- */
- public static EELFLoggerDelegate getLogger(Class<?> clazz) {
- return getLogger(clazz.getName());
- }
-
- /**
- * Gets a logger for the specified class name. If the logger does not
- * already exist in the map, this creates a new logger.
- *
- * @param className
- * If null or empty, uses EELFLoggerDelegate as the class name.
- * @return Instance of EELFLoggerDelegate
- */
- public static EELFLoggerDelegate getLogger(String className) {
- if (className == null || className == "")
- className = EELFLoggerDelegate.class.getName();
- EELFLoggerDelegate delegate = classMap.get(className);
- if (delegate == null) {
- delegate = new EELFLoggerDelegate(className);
- classMap.put(className, delegate);
- }
- return delegate;
- }
-
- /**
- * Logs a message at the lowest level: trace.
- *
- * @param logger
- * @param msg
- */
- public void trace(EELFLogger logger, String msg) {
- if (logger.isTraceEnabled()) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.trace(msg);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
- }
-
- /**
- * Logs a message with parameters at the lowest level: trace.
- *
- * @param logger
- * @param msg
- * @param arguments
- */
- public void trace(EELFLogger logger, String msg, Object... arguments) {
- if (logger.isTraceEnabled()) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.trace(msg, arguments);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
- }
-
- /**
- * Logs a message and throwable at the lowest level: trace.
- *
- * @param logger
- * @param msg
- * @param th
- */
- public void trace(EELFLogger logger, String msg, Throwable th) {
- if (logger.isTraceEnabled()) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.trace(msg, th);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
- }
-
- /**
- * Logs a message at the second-lowest level: debug.
- *
- * @param logger
- * @param msg
- */
- public void debug(EELFLogger logger, String msg) {
- if (logger.isDebugEnabled()) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.debug(msg);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
- }
-
- /**
- * Logs a message with parameters at the second-lowest level: debug.
- *
- * @param logger
- * @param msg
- * @param arguments
- */
- public void debug(EELFLogger logger, String msg, Object... arguments) {
- if (logger.isDebugEnabled()) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.debug(msg, arguments);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
- }
-
- /**
- * Logs a message and throwable at the second-lowest level: debug.
- *
- * @param logger
- * @param msg
- * @param th
- */
- public void debug(EELFLogger logger, String msg, Throwable th) {
- if (logger.isDebugEnabled()) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.debug(msg, th);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
- }
-
- /**
- * Logs a message at info level.
- *
- * @param logger
- * @param msg
- */
- public void info(EELFLogger logger, String msg) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.info(msg);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
-
- /**
- * Logs a message with parameters at info level.
- *
- * @param logger
- * @param msg
- * @param arguments
- */
- public void info(EELFLogger logger, String msg, Object... arguments) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.info(msg, arguments);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
-
- /**
- * Logs a message and throwable at info level.
- *
- * @param logger
- * @param msg
- * @param th
- */
- public void info(EELFLogger logger, String msg, Throwable th) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.info(msg, th);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
-
- /**
- * Logs a message at warn level.
- *
- * @param logger
- * @param msg
- */
- public void warn(EELFLogger logger, String msg) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.warn(msg);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
-
- /**
- * Logs a message with parameters at warn level.
- *
- * @param logger
- * @param msg
- * @param arguments
- */
- public void warn(EELFLogger logger, String msg, Object... arguments) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.warn(msg, arguments);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
-
- /**
- * Logs a message and throwable at warn level.
- *
- * @param logger
- * @param msg
- * @param th
- */
- public void warn(EELFLogger logger, String msg, Throwable th) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.warn(msg, th);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
-
- /**
- * Logs a message at error level.
- *
- * @param logger
- * @param msg
- */
- public void error(EELFLogger logger, String msg) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.error(msg);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
-
- /**
- * Logs a message with parameters at error level.
- *
- * @param logger
- * @param msg
- * @param arguments
- */
- public void error(EELFLogger logger, String msg, Object... arguments) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.warn(msg, arguments);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
-
- /**
- * Logs a message and throwable at error level.
- *
- * @param logger
- * @param msg
- * @param th
- */
- public void error(EELFLogger logger, String msg, Throwable th) {
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.warn(msg, th);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
-
- /**
- * Logs a message with the associated alarm severity at error level.
- *
- * @param logger
- * @param msg
- * @param severtiy
- */
- public void error(EELFLogger logger, String msg, AlarmSeverityEnum severtiy) {
- MDC.put(MDC_ALERT_SEVERITY, severtiy.name());
- MDC.put(SystemProperties.MDC_CLASS_NAME, className);
- logger.error(msg);
- MDC.remove(MDC_ALERT_SEVERITY);
- MDC.remove(SystemProperties.MDC_CLASS_NAME);
- }
-
- /**
- * Initializes the logger context.
- */
- public void init() {
- setGlobalLoggingContext();
- final String msg = "############################ Logging is started. ############################";
- // These loggers emit the current date-time without being told.
- info(applicationLogger, msg);
- error(errorLogger, msg);
- debug(debugLogger, msg);
- // Audit and metrics logger must be told start AND stop times
- final String currentDateTime = EELFLoggerAdvice.getCurrentDateTimeUTC();
- // Set the MDC with audit properties
- MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, currentDateTime);
- MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, currentDateTime);
- info(auditLogger, msg);
- MDC.remove(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(SystemProperties.AUDITLOG_END_TIMESTAMP);
- // Set the MDC with metrics properties
- MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, currentDateTime);
- MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, currentDateTime);
- info(metricsLogger, msg);
- MDC.remove(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP);
- MDC.remove(SystemProperties.METRICSLOG_END_TIMESTAMP);
- }
-
- /**
- * Logs a standard message identified by the specified enum, using the
- * specified parameters, at error level. Alarm and error severity are taken
- * from the specified enum argument.
- *
- * @param epMessageEnum
- * @param param
- */
- public void logEcompError(AppMessagesEnum epMessageEnum, String... param) {
- try {
- AlarmSeverityEnum alarmSeverityEnum = epMessageEnum.getAlarmSeverity();
- ErrorSeverityEnum errorSeverityEnum = epMessageEnum.getErrorSeverity();
-
- MDC.put(MDC_ALERT_SEVERITY, alarmSeverityEnum.name());
- MDC.put("ErrorCode", epMessageEnum.getErrorCode());
- MDC.put("ErrorDescription", epMessageEnum.getErrorDescription());
-
- String resolution = this.formatMessage(epMessageEnum.getDetails() + " " + epMessageEnum.getResolution(),
- (Object[]) param);
- if (errorSeverityEnum == ErrorSeverityEnum.WARN) {
- errorLogger.warn(resolution);
- } else if (errorSeverityEnum == ErrorSeverityEnum.INFO) {
- errorLogger.info(resolution);
- } else {
- errorLogger.error(resolution);
- }
- } catch (Exception e) {
- errorLogger.error("Failed to log the error code. Details: " + UserUtils.getStackTrace(e));
- } finally {
- MDC.remove("ErrorCode");
- MDC.remove("ErrorDescription");
- MDC.remove(MDC_ALERT_SEVERITY);
- }
- }
-
- /**
- * Builds a message using a template string and the arguments.
- *
- * @param message
- * @param args
- * @return
- */
- private String formatMessage(String message, Object... args) {
- StringBuilder sbFormattedMessage = new StringBuilder();
- if (args != null && args.length > 0 && message != null && message != "") {
- MessageFormat mf = new MessageFormat(message);
- sbFormattedMessage.append(mf.format(args));
- } else {
- sbFormattedMessage.append(message);
- }
-
- return sbFormattedMessage.toString();
- }
-
- /**
- * Loads all the default logging fields into the MDC context.
- */
- private void setGlobalLoggingContext() {
- MDC.put(MDC_SERVICE_INSTANCE_ID, "");
- MDC.put(MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.toString());
- try {
- MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
- MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
- MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID));
- } catch (Exception e) {
- }
- }
-
- public static void mdcPut(String key, String value) {
- MDC.put(key, value);
- }
-
- public static String mdcGet(String key) {
- return MDC.get(key);
- }
-
- public static void mdcRemove(String key) {
- MDC.remove(key);
- }
-
- /**
- * Loads the RequestId/TransactionId into the MDC which it should be
- * receiving with an each incoming REST API request. Also, configures few
- * other request based logging fields into the MDC context.
- *
- * @param req
- * @param appName
- */
- public void setRequestBasedDefaultsIntoGlobalLoggingContext(HttpServletRequest req, String appName) {
- // Load the default fields
- setGlobalLoggingContext();
-
- // Load the request based fields
- if (req != null) {
- // Load the Request into MDC context.
- String requestId = UserUtils.getRequestId(req);
- MDC.put(MDC_KEY_REQUEST_ID, requestId);
-
- // Load user agent into MDC context, if available.
- String accessingClient = "Unknown";
- accessingClient = req.getHeader(SystemProperties.USERAGENT_NAME);
- if (accessingClient != null && accessingClient != "" && (accessingClient.contains("Mozilla")
- || accessingClient.contains("Chrome") || accessingClient.contains("Safari"))) {
- accessingClient = appName + "_FE";
- }
- MDC.put(SystemProperties.PARTNER_NAME, accessingClient);
-
- // Protocol, Rest URL & Rest Path
- String restURL = "";
- MDC.put(SystemProperties.FULL_URL, SystemProperties.UNKNOWN);
- MDC.put(SystemProperties.PROTOCOL, SystemProperties.HTTP);
- restURL = UserUtils.getFullURL(req);
- if (restURL != null && restURL != "") {
- MDC.put(SystemProperties.FULL_URL, restURL);
- if (restURL.toLowerCase().contains("https")) {
- MDC.put(SystemProperties.PROTOCOL, SystemProperties.HTTPS);
- }
- }
-
- // Rest Path
- MDC.put(MDC_SERVICE_NAME, req.getServletPath());
-
- // Client IPAddress i.e. IPAddress of the remote host who is making
- // this request.
- String clientIPAddress = "";
- clientIPAddress = req.getHeader("X-FORWARDED-FOR");
- if (clientIPAddress == null) {
- clientIPAddress = req.getRemoteAddr();
- }
- MDC.put(SystemProperties.CLIENT_IP_ADDRESS, clientIPAddress);
-
- // Load loginId into MDC context.
- MDC.put(SystemProperties.MDC_LOGIN_ID, "Unknown");
-
- String loginId = "";
- User user = UserUtils.getUserSession(req);
- if (user != null) {
- loginId = user.getLoginId();
- }
-
- if (loginId != null && loginId != "") {
- MDC.put(SystemProperties.MDC_LOGIN_ID, loginId);
- }
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.menu;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.FusionObject;
-import org.openecomp.portalsdk.core.domain.MenuData;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-
-@SuppressWarnings("rawtypes")
-public class MenuBuilder implements FusionObject {
-
- @Autowired
- private DataAccessService dataAccessService;
-
- public MenuBuilder() {
- }
-
- @SuppressWarnings("unchecked")
- public Set getMenu(String menuSetName, DataAccessService dataAccessService) {
-
- Set menu = null;
- MenuData root = null;
-
- HashMap params = new HashMap();
-
- params.put("menu_set_cd", menuSetName);
-
- // execute a query of the latest configuration of the FN_MENU table for the given menu_set_cd.
- List menuItems = dataAccessService.executeNamedQuery(SystemProperties.getProperty(SystemProperties.MENU_QUERY_NAME), params, null);
-
- Iterator i = menuItems.iterator();
- if (i.hasNext()) {
- root = (MenuData)i.next();
- menu = root.getChildMenus();
- }
-
- return menu;
- }
-
- @SuppressWarnings("unchecked")
- public Set getMenu(String menuSetName) {
-
- Set menu = null;
- MenuData root = null;
-
- HashMap params = new HashMap();
-
- params.put("menu_set_cd", menuSetName);
-
- // execute a query of the latest configuration of the FN_MENU table for the given menu_set_cd.
- List menuItems = getDataAccessService().executeNamedQuery(SystemProperties.getProperty(SystemProperties.MENU_QUERY_NAME), params, null);
-
- Iterator i = menuItems.iterator();
- if (i.hasNext()) {
- root = (MenuData)i.next();
- menu = root.getChildMenus();
- }
-
- return menu;
- }
-
- public static Set filterMenu(Set menus, HttpServletRequest request) {
- Iterator j = menus.iterator();
-
- while (j.hasNext()) {
- MenuData menuItem = (MenuData)j.next();
-
- if (!UserUtils.isAccessible(request, menuItem.getFunctionCd())) {
- // remove the menu if the user doesn't have access to it
- j.remove();
- }
- else {
- // if an accessible menu has a child menu, let's filter that recursively
-
- Set childMenus = menuItem.getChildMenus();
- if (childMenus != null && childMenus.size() > 0) {
- filterMenu(childMenus, request);
- }
-
- }
- }
-
- return menus;
- }
-
-
- public static String getUrlHtml(MenuData menuData) {
- String html = "";
-
- if (menuData.getExternalUrl() != null && menuData.getExternalUrl().length() > 0) {
- html = menuData.getExternalUrl();
- }
- else if (menuData.getServlet() != null && menuData.getServlet().length() > 0) {
- html = "/" + menuData.getServlet();
- }
- else if (menuData.getAction() != null && menuData.getAction().length() > 0) {
- html = "/" + menuData.getAction();
- }
-
- return html;
- }
-
-
- public static String getTargetHtml(MenuData menuData) {
- String html = "";
-
- if (menuData.getTarget() != null && menuData.getTarget().length() > 0) {
- html = "target=\"" + menuData.getTarget() + "\"";
- }
-
- return html;
- }
-
-
- public static String getQueryStringHtml(MenuData menuData) {
- String html = "";
-
- if (menuData.getQueryString() != null && menuData.getQueryString().length() > 0) {
- html = "?" + menuData.getQueryString();
- }
-
- return html;
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
-}
-
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.menu;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Properties;
-
-import javax.servlet.ServletContext;
-
-import org.openecomp.portalsdk.core.util.SystemProperties;
-
-
-/*
- MenuProperties contains a list of constants used during the creation,
- privilege screening, and rendering of the application menu.
-*/
-public class MenuProperties {
- private MenuProperties() {
- // cannot instantiate
- }
-
- @SuppressWarnings("rawtypes")
- private static HashMap menuProperties = new HashMap();
-
- // keys used to reference values in the menu.properties file
- public static final String WIDTH = "width";
- public static final String LEFT_POSITION = "left_position";
- public static final String TOP_POSITION = "top_position";
- public static final String FONT_COLOR = "font_color";
- public static final String MOUSEOVER_FONT_COLOR = "mouseover_font_color";
- public static final String BACKGROUND_COLOR = "background_color";
- public static final String MOUSEOVER_BACKGROUND_COLOR = "mouseover_background_color";
- public static final String BORDER_COLOR = "border_color";
- public static final String SEPARATOR_COLOR = "separator_color";
- public static final String IMAGE_SRC = "image_src";
- public static final String IMAGE_SRC_LEFT = "image_src_left";
- public static final String IMAGE_SRC_OVER = "image_src_over";
- public static final String IMAGE_SRC_LEFT_OVER = "image_src_left_over";
- public static final String EVALUATE_UPON_TREE_SHOW = "evaluate_upon_tree_show";
- public static final String EVALUATE_UPON_TREE_HIDE = "evaluate_upon_tree_hide";
- public static final String TOP_IS_PERMANENT = "top_is_permanent";
- public static final String TOP_IS_HORIZONTAL = "top_is_horizontal";
- public static final String TREE_IS_HORIZONTAL = "tree_is_horizontal";
- public static final String POSITION_UNDER = "position_under";
- public static final String TOP_MORE_IMAGES_VISIBLE = "top_more_images_visible";
- public static final String TREE_MORE_IMAGES_VISIBLE = "tree_more_images_visible";
- public static final String RIGHT_TO_LEFT = "right_to_left";
- public static final String DISPLAY_ON_CLICK = "display_on_click";
- public static final String TOP_IS_VARIABLE_WIDTH = "top_is_variable_width";
- public static final String TREE_IS_VARIABLE_WIDTH = "tree_is_variable_width";
- public static final String TOP_KEEP_IN_WINDOW_X = "top_keep_in_window_x";
- public static final String TOP_KEEP_IN_WINDOW_Y = "top_keep_in_window_y";
- public static final String MENU_ID_ADMIN = "menu_id_admin";
- public static final String MENU_ID_LOGOUT = "menu_id_logout";
- public static final String MENU_FRAME = "menu_frame";
- public static final String MAIN_FRAME = "main_frame";
- public static final String NESTED_MAIN_FRAME = "nested_main_frame";
- public static final String ROLE_FUNCTIONS_TAG = "role_functions_tag";
-
- public static final String MAX_DISPLAYABLE_ADMIN_MENU_SORT_ORDER = "max_displayable_admin_menu_sort_order";
- public static final String MENU_PROPERTIES_FILENAME_KEY = "menu_properties_filename";
- public static final String DEFAULT_SERVLET_NAME = "dispatcher";
- public static final String DEFAULT_TARGET = "_self";
-
- public static final String TOP_MENU_CLASS = "top_menu_class";
- public static final String TOP_MENU_LINK_CLASS = "top_menu_link_class";
-
- public static final String ON_MOUSE_OUT_TRAILER = "on_mouse_out_trailer";
- public static final String ON_MOUSE_OVER_TRAILER = "on_mouse_over_trailer";
- public static final String ON_CLICK_TRAILER = "on_click_trailer";
-
- public static final String MENU_ID_PREFIX = "menu_id_prefix";
-
-
- @SuppressWarnings("unchecked")
- public static void loadFromFile(ServletContext servletContext, String filename, String menuSetName) throws IOException {
- Properties p = new Properties();
-
- if (filename == null) {
- filename = SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_PROPERTIES_NAME);
- }
-
- p.load(servletContext.getResourceAsStream(SystemProperties.getProperty(SystemProperties.MENU_PROPERTIES_FILE_LOCATION) + filename));
- menuProperties.put(menuSetName, p);
- } // loadMenuProperties
-
- public static String getProperty(String key) {
- return getProperty(key, SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME));
- }
-
- public static String getProperty(String key, String menuSetName) {
- Properties p = (Properties)menuProperties.get(menuSetName);
- return p.getProperty(key);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.objectcache;
-
-import java.io.*;
-
-import org.openecomp.portalsdk.core.objectcache.support.*;
-
-
-public abstract class AbstractCacheManager implements FusionCacheManager {
- public AbstractCacheManager() {
- super();
- // TODO Auto-generated constructor stub
- }
-
- public Object getObject(String key) {
- // TODO Auto-generated method stub
- return null;
- }
-
- public void putObject(String key, Object objectToCache) {
- // TODO Auto-generated method stub
- }
-
- public boolean isObjectInCache(String key) {
- // TODO Auto-generated method stub
- return false;
- }
-
- public void removeObject(String key) {
- // TODO Auto-generated method stub
- }
-
- public void clearCache() {
- // TODO Auto-generated method stub
- }
-
- public void configure() throws IOException {
- // TODO Auto-generated method stub
-
- }
-}
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.objectcache.jcs;
-
-import org.apache.jcs.engine.control.event.behavior.IElementEvent;
-import org.apache.jcs.engine.control.event.behavior.IElementEventConstants;
-import org.apache.jcs.engine.control.event.behavior.IElementEventHandler;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
-public class JCSCacheEventHandler implements IElementEventHandler, IElementEventConstants {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JCSCacheEventHandler.class);
-
- public JCSCacheEventHandler() {
- super();
- }
-
- public void handleElementEvent(IElementEvent event) {
- // Handle code for various event notifications on cached elements by JCS.
- switch (event.getElementEvent()) {
- case ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND:
- logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND occurred for element " + event);
- break;
- case ELEMENT_EVENT_EXCEEDED_MAXLIFE_ONREQUEST:
- logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_MAXLIFE_ONREQUEST occurred for element " + event);
- break;
- case ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND:
- logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND occurred for element " + event);
- break;
- case ELEMENT_EVENT_EXCEEDED_IDLETIME_ONREQUEST:
- logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_EXCEEDED_IDLETIME_ONREQUEST occurred for element " + event);
- break;
- case ELEMENT_EVENT_SPOOLED_DISK_AVAILABLE:
- logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_SPOOLED_DISK_AVAILABLE occurred for element " + event);
- break;
- case ELEMENT_EVENT_SPOOLED_DISK_NOT_AVAILABLE:
- logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_SPOOLED_DISK_NOT_AVAILABLE occurred for element " + event);
- break;
- case ELEMENT_EVENT_SPOOLED_NOT_ALLOWED:
- logger.error(EELFLoggerDelegate.errorLogger, "Event ELEMENT_EVENT_SPOOLED_NOT_ALLOWED occurred for element " + event);
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.objectcache.jcs;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-import java.util.Vector;
-
-import javax.annotation.PostConstruct;
-import javax.servlet.ServletContext;
-
-import org.apache.jcs.JCS;
-import org.apache.jcs.access.exception.CacheException;
-import org.apache.jcs.engine.CacheConstants;
-import org.apache.jcs.engine.behavior.IElementAttributes;
-import org.apache.jcs.engine.control.CompositeCacheManager;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.web.context.ServletContextAware;
-
-public abstract class JCSCacheManager extends AbstractCacheManager implements CacheConstants, ServletContextAware {
-
- public static String LOOKUP_OBJECT_CACHE_NAME = "lookUpObjectCache";
- public static String JCS_CONFIG_FILE_PATH = "cache_config_file_path";
- public static String CACHE_LOAD_ON_STARTUP = "cache_load_on_startup";
- public static String CACHE_PROPERTY_VALUE_TRUE = "true";
- public static String CACHE_CONTROL_SWITCH_ON = "1";
- public static String CACHE_CONTROL_SWITCH_OFF = "0";
- public static String CACHE_CONTROL_SWITCH = "cache_switch";
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JCSCacheManager.class);
-
- private static JCS lookUpCache;
- private ServletContext servletContext;
-
- private Properties cacheConfigProperties = null;
- private final Vector<String> jscManagedCacheList = new Vector<String>();
-
- private DataAccessService dataAccessService;
-
- public JCSCacheManager() {
- super();
- jscManagedCacheList.add(LOOKUP_OBJECT_CACHE_NAME);
- }
-
- @PostConstruct
- public void configure() throws IOException {
- super.configure();
-
- String jcsConfigFilePath = SystemProperties.getProperty(JCS_CONFIG_FILE_PATH);
- // getProperty throws if the key is missing; but check anyhow.
- if (jcsConfigFilePath == null || jcsConfigFilePath.length() == 0)
- throw new IOException("configure: failed to get value for config property " + JCS_CONFIG_FILE_PATH);
- InputStream jcsConfigInputStream = getServletContext().getResourceAsStream(jcsConfigFilePath);
- if (jcsConfigInputStream == null)
- throw new IOException("configure: failed to open stream for config property " + JCS_CONFIG_FILE_PATH
- + " with name " + jcsConfigFilePath);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "configure: loading cache properties from classpath resource {} ", jcsConfigFilePath);
- Properties p = new Properties();
- p.load(jcsConfigInputStream);
- jcsConfigInputStream.close();
-
- CompositeCacheManager ccm = CompositeCacheManager.getUnconfiguredInstance();
- ccm.configure(p);
- setCacheConfigProperties(p);
-
- try {
- initializeLookUpCache();
- } catch (CacheException ce) {
- throw new IOException("configure: failed to initialize lookup cache", ce);
- }
-
- }
-
- private void initializeLookUpCache() throws CacheException {
- lookUpCache = JCS.getInstance(LOOKUP_OBJECT_CACHE_NAME);
-
- JCSCacheEventHandler eventHandler = new JCSCacheEventHandler();
- IElementAttributes elementAttributes = lookUpCache.getDefaultElementAttributes();
-
- elementAttributes.addElementEventHandler(eventHandler);
-
- lookUpCache.setDefaultElementAttributes(elementAttributes);
-
- if (CACHE_PROPERTY_VALUE_TRUE.equalsIgnoreCase(SystemProperties.getProperty(CACHE_LOAD_ON_STARTUP))) {
- loadDataOnStartUp();
- }
- }
-
- public Object getObject(String key) {
- if (CACHE_CONTROL_SWITCH_ON.equalsIgnoreCase(SystemProperties.getProperty(CACHE_CONTROL_SWITCH))) {
- if (lookUpCache == null)
- return null;
- else
- return lookUpCache.get(key);
- } else
- return null;
- }
-
- public void putObject(String key, Object objectToCache) {
- try {
- if (CACHE_CONTROL_SWITCH_ON.equalsIgnoreCase(SystemProperties.getProperty(CACHE_CONTROL_SWITCH))) {
- if (lookUpCache != null) {
- lookUpCache.put(key, objectToCache);
- }
- }
- } catch (CacheException ce) {
- logger.error(EELFLoggerDelegate.errorLogger, "putObject: failed to put the object with key " + key, ce);
- }
- }
-
- public void clearCache(String region) {
- try {
- if (region.equals(LOOKUP_OBJECT_CACHE_NAME))
- lookUpCache.clear();
- } catch (CacheException ce) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "clearCache: failed to clear the cache for the region " + region, ce);
- }
- }
-
- public void clearCache() {
- clearCache(LOOKUP_OBJECT_CACHE_NAME);
- }
-
- private void loadDataOnStartUp() {
- loadLookUpCache();
- }
-
- public abstract void loadLookUpCache();
-
- public void refreshLookUpCache() {
- clearCache(LOOKUP_OBJECT_CACHE_NAME);
- loadLookUpCache();
- }
-
- public Properties getCacheConfigProperties() {
- return cacheConfigProperties;
- }
-
- public void setCacheConfigProperties(Properties cacheConfigProperties) {
- this.cacheConfigProperties = cacheConfigProperties;
- }
-
- public Vector<String> getJscManagedCacheList() {
- return jscManagedCacheList;
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- public ServletContext getServletContext() {
- return servletContext;
- }
-
- public void setServletContext(ServletContext servletContext) {
- this.servletContext = servletContext;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.objectcache.support;
-
-import java.io.*;
-
-import org.openecomp.portalsdk.core.FusionObject;
-
-public interface FusionCacheManager extends FusionObject {
-
- Object getObject(String key);
- void putObject(String key, Object objectToCache);
- boolean isObjectInCache(String key);
-
- void removeObject(String key);
- void clearCache();
- void configure() throws IOException;
-}
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.client;
-
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.stereotype.Component;
-
-/**
- *
- *
- * Use this class to get access to ApplicationContext for classes who were not created by Spring.
- */
-
-
-@Component
-public class AppContextManager implements ApplicationContextAware{
- private static ApplicationContext _appCtx;
-
- @Override
- public void setApplicationContext(ApplicationContext ctx){
- _appCtx = ctx;
- }
-
- public static ApplicationContext getAppContext(){
- return _appCtx;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.session;
-
-public class TestClass {
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.sso;
-
-public class TestClass {
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.ueb;
-
-import java.io.IOException;
-import java.security.GeneralSecurityException;
-import java.util.LinkedList;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentLinkedQueue;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-
-import com.att.nsa.cambria.client.CambriaClientBuilders;
-import com.att.nsa.cambria.client.CambriaConsumer;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-/**
- * Provides a consumer that reads messages from a UEB topic. Intended to be
- * passed to a separate thread as its runnable object.
- */
-public class Consumer implements Runnable {
-
- private final Log logger = LogFactory.getLog(getClass());
-
- private final LinkedList<String> urlList = Helper.uebUrlList();
- private final ConcurrentLinkedQueue<UebMsg> queue;
- private final WaitingRequestersQueueList waitingRequestersList;
- private final String consumerKey, consumerSecret, topicName, consumerGroupName;
-
- /**
- * Accepts coordinates needed to subscribe to a UEB topic, as well as the
- * queues for passing along messages that arrive.
- *
- * @param consumerKey
- * UEB key used to subscribe to the topic
- * @param consumerSecret
- * UEB secret used to subscribe to the topic
- * @param topicName
- * UEB topic name
- * @param queue
- * Queue to receive UEB messages. All inbound messages are
- * enqueued here; ignored if null.
- * @param waitingRequestersList
- * Collection of queues to receive UEB messages that arrive in
- * response to requests; i.e., emulating a synchronous request
- * via pub/sub.
- */
- public Consumer(String consumerKey, String consumerSecret, String topicName, String consumerGroupName,
- ConcurrentLinkedQueue<UebMsg> queue, WaitingRequestersQueueList waitingRequestersList) {
- this.consumerKey = consumerKey;
- this.consumerSecret = consumerSecret;
- this.topicName = topicName;
- this.consumerGroupName = consumerGroupName;
- this.queue = queue;
- this.waitingRequestersList = waitingRequestersList;
- }
-
- /**
- * Subscribes to a topic using credentials as supplied to the constructor.
- * Distributes messages appropriately as they arrive:
- * <UL>
- * <LI>If the queue is not null, adds the message to the queue.
- * <LI>If the message's getMsgId() method returns non-null and the ID is
- * found in the collection of waiting requesters, adds the message in that
- * requester's queue.
- * </UL>
- *
- * This is intended to be called in a long running thread as a listener for
- * any published messages on a topic. Typical async pub/sub model. We use a
- * filter of "0" to prevent collisions with P2P messages with unique filter
- * ids.
- */
- protected void consume() throws IOException, UebException, GeneralSecurityException {
- final String id = UUID.randomUUID().toString();
-
- CambriaConsumer cc = null;
- cc = new CambriaClientBuilders.ConsumerBuilder()
- .usingHosts(urlList)
- .authenticatedBy(consumerKey, consumerSecret)
- .onTopic (topicName)
- .knownAs (consumerGroupName,id)
- .waitAtServer (15*1000)
- .receivingAtMost (1000)
- .build();
-
- while (true) {
- for (String msg : cc.fetch()) {
- logger.debug(" <== consume from topicName " + topicName + " msg: " + msg);
- UebMsg uebMsg = new ObjectMapper().readValue(msg, UebMsg.class);
- if (queue != null) {
- // Add to general queue allowing listeners to act on any
- // incoming messages. We don't know if a listener is
- // also going to be a responder to a synchronous
- // request. So put all received messages on the general
- // listener queue.
- queue.add(uebMsg);
- if (logger.isDebugEnabled())
- logger.debug("Added msg to queue " + this.queue + " queue count = " + queue.size() + " msg :"
- + uebMsg.getPayload());
- }
- if (waitingRequestersList != null && uebMsg.getMsgId() != null) {
- // If a msgId is present, this could be a synchronous
- // reply. Here we add it to the waiting requester's
- // queue if we find a requester waiting for this msgId.
- if (!(uebMsg.getMsgId()
- .equals(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_DEFAULT_MSG_ID)))) {
- waitingRequestersList.addMsg(uebMsg.getMsgId(), uebMsg);
- }
- }
- }
- if (Thread.interrupted()) {
- logger.warn(Thread.currentThread() + " interrupted, exiting");
- break;
- }
- Helper.sleep(10);
- }
-
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Runnable#run()
- */
- @Override
- public void run() {
- try {
- consume();
- } catch (Exception ex) {
- Thread t = Thread.currentThread();
- t.getUncaughtExceptionHandler().uncaughtException(t, ex);
- }
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.ueb;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * Provides a convenience method for fetching the functional menu for a user
- * from the ECOMP Portal via UEB.
- */
-public class FunctionalMenu {
-
- private static final Log logger = LogFactory.getLog(FunctionalMenu.class);
-
- /**
- * Makes a synchronous call to ECOMP Portal to get JSON with the functional
- * menu, which arrives as the payload of the returned UEB message.
- *
- * @param userId
- * User ID as known on the ECOMP Portal for customizing the
- * functional menu appropriately
- * @return JSON with functional menu
- * @throws UebException
- */
- public static String get(String userId) throws UebException {
- String returnString = null;
- logger.info("Making use of UEB communication and Requesting functional menu for user " + userId);
- UebMsg funcMenuUebMsg = null;
- UebMsg msg = new UebMsg();
- msg.putMsgType(UebMsgTypes.UEB_MSG_TYPE_GET_FUNC_MENU);
- msg.putUserId(userId);
- funcMenuUebMsg = UebManager.getInstance().requestReply(msg);
- if (funcMenuUebMsg != null) {
- if (funcMenuUebMsg.getPayload().startsWith("Error:")) {
- logger.error("getFunctionalMenu received an error in UEB msg = " + funcMenuUebMsg.getPayload());
- } else {
- returnString = funcMenuUebMsg.getPayload();
- }
- }
- return returnString;
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.ueb;
-
-import java.util.LinkedList;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-
-/**
- * Provides utility methods.
- */
-public class Helper {
-
- private static final Log logger = LogFactory.getLog(Helper.class);
-
- /**
- * Parses a comma-separated list of UEB servers from properties file into a
- * list.
- *
- * @return List of UEB server names
- */
- public static LinkedList<String> uebUrlList() {
- LinkedList<String> urlList = null;
- String url = PortalApiProperties.getProperty(PortalApiConstants.UEB_URL_LIST);
- if (url == null) {
- logger.error("uebUrlList: failed to get property " + PortalApiConstants.UEB_URL_LIST);
- return null;
- }
- urlList = new LinkedList<String>();
- for (String u : url.split(",")) {
- urlList.add(u.trim());
- }
- return urlList;
- }
-
- public static void sleep(int milliseconds) {
- try {
- Thread.sleep(milliseconds);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.ueb;
-
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.security.GeneralSecurityException;
-import java.util.LinkedList;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-
-import com.att.nsa.cambria.client.CambriaBatchingPublisher;
-import com.att.nsa.cambria.client.CambriaClientBuilders;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.ObjectWriter;
-
-/**
- * Provides a publisher that sends messages to a UEB topic.
- *
- * Utilizes AT&T's UEB/Cambria subscriber/publisher messaging service.
- */
-public class Publisher {
-
- private final Log logger = LogFactory.getLog(getClass());
-
- protected final LinkedList<String> urlList = Helper.uebUrlList();
-
- private final String topicName;
- private final String publisherKey;
- private final String publisherSecret;
-
- /**
- * Accepts coordinates needed to publish to a UEB topic.
- *
- * @param publisherKey
- * UEB key used to publish to the topic
- * @param publisherSecret
- * UEB secret used to publish to the topic
- * @param topicName
- * UEB topic name
- */
- public Publisher(String publisherKey, String publisherSecret, String topicName) {
- this.publisherKey = publisherKey;
- this.publisherSecret = publisherSecret;
- this.topicName = topicName;
- logger.info("Publisher instantiated for topic " + topicName);
- }
-
- /**
- * Creates a publisher, subscribes to the topic, sends the specified message
- * to the topic, then closes the publisher. This ensures that the single
- * message goes immediately. UEB is designed for high throughput and tries
- * to batch up multiple messages in each send, but this method wants the
- * single message to go immediately.
- *
- * @param uebMsg
- * Message object to send as the payload.
- * @throws UebException
- * If anything goes wrong, including JSON serialization of the
- * specified message object.
- */
- public void send(UebMsg uebMsg) throws UebException {
- String msg = null;
-
- CambriaBatchingPublisher pub;
- try {
- pub = new CambriaClientBuilders.PublisherBuilder()
- .authenticatedBy(publisherKey, publisherSecret).usingHosts(urlList).onTopic(topicName).build();
- } catch (MalformedURLException e1) {
- logger.error("pub.build Exception ", e1);
- throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, e1, topicName, null, msg);
- } catch (GeneralSecurityException e1) {
- logger.error("pub.build Exception ", e1);
- throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, e1, topicName, null, msg);
- }
-
- try {
- ObjectWriter mapper = new ObjectMapper().writer().withDefaultPrettyPrinter();
- msg = mapper.writeValueAsString(uebMsg);
- } catch (JsonProcessingException e) {
- throw new UebException(PortalApiConstants.ECOMP_UEB_INVALID_MSG, topicName, null, null);
- }
-
- try {
- logger.debug("Publishing to " + topicName + " msg: " + msg);
- int NumSent = pub.send(PortalApiConstants.ECOMP_GENERAL_UEB_PARTITION, msg);
- if (NumSent == 0) {
- throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, topicName, null, msg);
- }
- } catch (IOException ex) {
- logger.error("Failed to publish", ex);
- throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, ex, topicName, null, msg);
- }
-
- try {
- // close the publisher to make sure everything's sent before exiting
- pub.close(5, TimeUnit.SECONDS);
- } catch (Exception ex) {
- logger.error("pub.close Exception ", ex);
- throw new UebException(PortalApiConstants.ECOMP_UEB_UNKNOWN_PUBLISH_ERROR, ex, topicName, null, msg);
- }
-
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.ueb;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * A thin wrapper around ConcurrentHashMap that stores a queue for each
- * Requester that is waiting for a Reply. When a reply is received that has a
- * matching msgId, that requesters queue is populated with the reply message.
- *
- * Primarily for Portal core to track the remote applications that have placed
- * requests; never used by those applications.
- */
-public class PublisherList {
-
- private final Log logger = LogFactory.getLog(getClass());
-
- private final Map<String, Publisher> map;
-
- public PublisherList() {
- map = new ConcurrentHashMap<>();
- }
-
- public void addPublisherToMap(String topicName, Publisher publisher) {
- if (this.map.containsKey(topicName)) {
- logger.error("Publisher already exists for " + topicName);
- } else {
- this.map.put(topicName, publisher);
- }
- }
-
- public Publisher getPublisher(String topicName) {
- return this.map.get(topicName);
- }
-
- public void removePublisherFromMap(String topicName) {
- this.map.remove(topicName);
- }
-
- public String toString() {
- StringBuffer sb = new StringBuffer();
- sb.append("Map contains " + this.map.size() + " Publishers.");
- for (Map.Entry<String, Publisher> entry : this.map.entrySet()) {
- String key = entry.getKey().toString();
- Publisher pub = entry.getValue();
- sb.append("Entry msgId, " + key + " publisher" + pub);
- }
- return sb.toString();
- }
-
- public int size() {
- return this.map.size();
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.ueb;
-
-import java.io.IOException;
-import java.security.GeneralSecurityException;
-import java.util.LinkedList;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-
-import com.att.nsa.apiClient.http.HttpClient;
-import com.att.nsa.apiClient.http.HttpException;
-import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
-import com.att.nsa.cambria.client.CambriaClientBuilders;
-import com.att.nsa.cambria.client.CambriaClientFactory;
-import com.att.nsa.cambria.client.CambriaTopicManager;
-
-/**
- * Provides methods to facilitate creating topics, and adding publishers and
- * subscribers to existing topics.
- *
- * Utilizes UEB/Cambria subscriber/publisher messaging service.
- */
-public class TopicManager {
-
- private final Log logger = LogFactory.getLog(getClass());
-
- /**
- * Creates a topic with the specified information.
- *
- * @param key
- * Topic key
- * @param secret
- * Topic secret key
- * @param topicName
- * Topic name
- * @param topicDescription
- * Topic description
- * @throws HttpException
- * @throws CambriaApiException
- * @throws IOException
- */
- public void createTopic(String key, String secret, String topicName, String topicDescription)
- throws HttpException, CambriaApiException, IOException {
- final LinkedList<String> urlList = Helper.uebUrlList();
- if (logger.isInfoEnabled()) {
- logger.info("==> createTopic");
- logger.info("topicName: " + topicName);
- logger.info("topicDescription: " + topicDescription);
- }
- CambriaTopicManager tm =null;
- try {
- tm = CambriaClientFactory.createTopicManager(null, urlList, key, secret);
- } catch (GeneralSecurityException e) {
- logger.error("pub.build Exception ", e);
- throw new CambriaApiException(topicName);
- }
- tm.createTopic(topicName, topicDescription, 1, 1);
- }
-
- /**
- * Modifies the specified topic to accept a subscriber using the specified
- * key.
- *
- * @param topicOwnerKey
- * @param topicOwnerSecret
- * @param subscriberKey
- * @param topicName
- * @throws HttpException
- * @throws CambriaApiException
- * @throws IOException
- */
- public void addSubscriber(String topicOwnerKey, String topicOwnerSecret, String subscriberKey, String topicName)
- throws HttpException, CambriaApiException, IOException {
- logger.info("==> addSubscriber to topic " + topicName);
- final LinkedList<String> urlList = Helper.uebUrlList();
- CambriaTopicManager tm = null;
- try {
- tm = new CambriaClientBuilders.TopicManagerBuilder().usingHosts(urlList).authenticatedBy(topicOwnerKey, topicOwnerSecret).build();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //old version num : CambriaClientFactory.createTopicManager(urlList, topicOwnerKey,topicOwnerSecret);
- tm.allowConsumer(topicName, subscriberKey);
- }
-
- /**
- * Modifies the specified topic to accept a publisher using the specified
- * key.
- *
- * @param topicOwnerKey
- * @param topicOwnerSecret
- * @param publisherKey
- * @param topicName
- * @throws HttpException
- * @throws CambriaApiException
- * @throws IOException
- */
-
- @SuppressWarnings("deprecation")
- public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey, String topicName)
- throws HttpException, CambriaApiException, IOException {
- logger.info("==> addPublisher to topic " + topicName);
- final LinkedList<String> urlList = Helper.uebUrlList();
- CambriaTopicManager tm =null;
- try {
- tm = CambriaClientFactory.createTopicManager(HttpClient.ConnectionType.HTTPS, urlList, topicOwnerKey,
- topicOwnerSecret);
- } catch (GeneralSecurityException e) {
- logger.error("pub.build Exception ", e);
- throw new CambriaApiException(topicName);
- }
- tm.allowProducer(topicName, publisherKey);
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.ueb;
-
-/**
- * Stores UEB-specific information including topic, message ID and message body.
- */
-public class UebException extends Exception {
-
- private static final long serialVersionUID = 1L;
- private String topicName = null;
- private String msgId = null;
- private String msg = null;
-
- public UebException(String errorMsg, String topicName, String msgId, String msg) {
- super(errorMsg);
- this.topicName = topicName;
- this.msgId = msgId;
- this.msg = msg;
- }
-
- public UebException(String errorMsg, Throwable ex, String topicName, String msgId, String msg) {
- super(errorMsg, ex);
- this.topicName = topicName;
- this.msgId = msgId;
- this.msg = msg;
- }
-
- public UebException(String msg, Throwable ex) {
- super(msg, ex);
- }
-
- public UebException(Throwable ex) {
- super(ex);
- }
-
- public String getUebMsg() {
- return this.msg;
- }
-
- public String getTopicName() {
- return this.topicName;
- }
-
- public String getMsgId() {
- return this.msgId;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.ueb;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-
-/**
- * Manages UEB interactions and provides methods for publishing requests,
- * replies and others.
- */
-public class UebManager {
-
- private final Log logger = LogFactory.getLog(getClass());
-
- private WaitingRequestersQueueList waitingRequestersQueueList;
- private PublisherList publisherList = new PublisherList();
- private static UebManager uebManager = null;
-
- private final String inTopicName;
- private final String consumerGroupName;
- private final String outTopicName;
- private final String appUebKey;
- private final String appUebSecret;
-
- private Publisher appPublisher;
- private Thread listenerThread;
- private boolean bThisIsEcompPortalServer = false;
-
- /**
- * Constructor initializes fields and validates values obtained from
- * properties.
- *
- * The picture below is a simplified view of the relationships among ECOMP
- * Portal and applications communicating via UEB:
- *
- * <PRE>
- * ECOMP out to many.
- * App out to only ECOMP.
- *
- * |----------------|<---------------------------------------------
- * | | | | |
- * | |---------------------------> App 1 ------ | |
- * | ECOMP Portal |---------------------------> App 2 --------- |
- * | | ... |
- * | |---------------------------> App n -----------
- * |----------------|
- * </PRE>
- *
- * @throws IOException
- */
- protected UebManager() throws UebException {
- waitingRequestersQueueList = null;
- listenerThread = null;
- outTopicName = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME);
- inTopicName = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME);
- appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
- appUebSecret = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET);
- String consGrp = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_CONSUMER_GROUP_NAME);
-
- if (outTopicName == null || outTopicName.length() == 0)
- throw new UebException("Failed to get property " + PortalApiConstants.ECOMP_PORTAL_INBOX_NAME, null, null,
- null);
- if (inTopicName == null || inTopicName.length() == 0)
- throw new UebException("Failed to get property " + PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME, null,
- null, null);
- if (consGrp == null || consGrp.length() == 0)
- throw new UebException("Failed to get property " + PortalApiConstants.UEB_APP_CONSUMER_GROUP_NAME, null,
- null, null);
- if (appUebKey == null || appUebKey.length() == 0)
- throw new UebException("Failed to get property " + PortalApiConstants.UEB_APP_KEY, null, null, null);
- if (appUebSecret == null || appUebSecret.length() == 0)
- throw new UebException("Failed to get property " + PortalApiConstants.UEB_APP_SECRET, null, null, null);
- List<String> uebUrlList = Helper.uebUrlList();
- if (uebUrlList == null || uebUrlList.size() == 0)
- throw new UebException("Failed to get property" + PortalApiConstants.UEB_URL_LIST, null, null, null);
- // A bit of magic: if consumer group is a magic token, generate one.
- consumerGroupName = (PortalApiConstants.UEB_APP_CONSUMER_GROUP_NAME_GENERATOR.equals(consGrp)
- ? UUID.randomUUID().toString() : consGrp);
- }
-
- /**
- * Gets the static instance, creating it if necessary.
- *
- * @return Instance of UebManager
- * @throws IOException
- */
- public static synchronized UebManager getInstance() throws UebException {
- if (uebManager == null) {
- uebManager = new UebManager();
- }
- return uebManager;
- }
-
- /**
- * Answers whether the getInstance() method has previously been called.
- *
- * @return True if a static instance is available, else false.
- */
- public static boolean isInstanceAvailable() {
- return uebManager != null;
- }
-
- /**
- * Creates a list of waiting requesters, creates and a consumer using cached
- * information, and starts a new thread to run the consumer that listens for
- * messages published to the inbound topic configured in the constructor.
- *
- * @param inboxQueue
- * Queue supplied to the consumer. If not null, the consumer will
- * enqueue every message it receives.
- */
- public void initListener(ConcurrentLinkedQueue<UebMsg> inboxQueue) throws UebException {
- waitingRequestersQueueList = new WaitingRequestersQueueList();
- Consumer runnable = new Consumer(appUebKey, appUebSecret, inTopicName, consumerGroupName, inboxQueue,
- waitingRequestersQueueList);
- this.listenerThread = new Thread(runnable, "UEBConsumerThread");
- this.listenerThread.start();
- Helper.sleep(400); // UEB functions more reliably when we give this some
- // time
-
- logger.info("UEBManager instance starting... " + inTopicName + " listener thread "
- + this.listenerThread.getName() + " state = " + this.listenerThread.getState());
-
- /*
- * ECOMP Portal manages a dynamic list of outbound topics and so the
- * outTopicName is initialized in this logic with the same value as the
- * inbound topic. The real outbound topics name will be added to the
- * publisher list for ECOMP Portal. For an SDK/App instance only one
- * publisher is needed, appPublisher.
- */
- if (inTopicName.equalsIgnoreCase(outTopicName)) {
- this.bThisIsEcompPortalServer = true;
- } else {
- appPublisher = new Publisher(appUebKey, appUebSecret, outTopicName);
- Helper.sleep(400);
- }
- }
-
- /**
- * Creates and adds a publisher to the list for the specified topic. This
- * should only be called by the ECOMP Portal App, other Apps have just one
- * publisher and use appPublisher
- *
- * @param topicName
- */
- public void addPublisher(String topicName) {
- logger.info("UEBManager adding publisher for " + topicName);
- Publisher outBoxToAppPublisher = new Publisher(appUebKey, appUebSecret, topicName);
- publisherList.addPublisherToMap(topicName, outBoxToAppPublisher);
- }
-
- /**
- * Removes a publisher from the list for the specified topic.
- *
- * This should only be called by the ECOMP Portal App, other Apps have just
- * one publisher and use appPublisher
- *
- * @param topicName
- */
- public void removePublisher(String topicName) {
- logger.info("UEBManager removing publisher for " + topicName);
- publisherList.removePublisherFromMap(topicName);
- }
-
- /**
- * Adds the default ECOMP message ID to the message and sends the message to
- * the topic.
- *
- * @param msg
- * @throws UebException
- */
- public void publish(UebMsg msg) throws UebException {
- msg.putMsgId(PortalApiConstants.ECOMP_DEFAULT_MSG_ID);
- appPublisher.send(msg);
- }
-
- /**
- * Sends the message using the default publisher.
- *
- * @param msg
- * @throws UebException
- */
- public void publishReply(UebMsg msg) throws UebException {
- // Caller populates msgId with the echoed value from the request
- appPublisher.send(msg);
- }
-
- /**
- * Sends the message using the appropriate publisher for the specified
- * topic.
- *
- * @param msg
- * @param topicName
- * @throws UebException
- */
- public void publishEP(UebMsg msg, String topicName) throws UebException {
- Publisher publisher = publisherList.getPublisher(topicName);
- if (publisher != null) {
- msg.putMsgId(PortalApiConstants.ECOMP_DEFAULT_MSG_ID);
- publisher.send(msg);
- }
- }
-
- /**
- * Publishes a reply using the appropriate publisher for the specified
- * topic.
- *
- * @param msg
- * @param topicName
- * @throws UebException
- */
- public void publishReplyEP(UebMsg msg, String topicName) throws UebException {
- // Caller populates msgId with the echoed value from the request
- Publisher publisher = publisherList.getPublisher(topicName);
- if (publisher != null) {
- publisher.send(msg);
- }
- }
-
- /**
- * Sends the specified message using the specified publisher, and waits for
- * a reply. Retransmits if no reply is received in 5 seconds; gives up after
- * 3 retries.
- *
- * @param msg
- * @param publisher
- * @return Message from a remote publisher, or null if timeout happens.
- * @throws UebException
- */
- public UebMsg requestReplyUsingPublisher(UebMsg msg, Publisher publisher) throws UebException {
- UebMsg reply = null;
- if (waitingRequestersQueueList == null) {
- logger.error("requestReplyUsingPublisher called but listener thread not initialized");
- } else {
- // Storing a non-default message ID identifies this as a synchronous
- // request
- msg.putMsgId(UUID.randomUUID().toString());
-
- /*
- * Create a queue for this request, the consumer thread will insert
- * the reply on this queue
- */
- LinkedBlockingQueue<UebMsg> replyQueue = new LinkedBlockingQueue<UebMsg>();
- waitingRequestersQueueList.addQueueToMap(msg.getMsgId(), replyQueue);
-
- /*
- * Send the request
- */
- publisher.send(msg);
-
- /*
- * Wait for reply up to 3 * 5 = 15 seconds
- */
- int reTransmits = 0;
- int maxRetransmits = 3;
- int retransmitTimeMs = 5000;
- long sendTimeStamp = System.currentTimeMillis();
- while (reTransmits < maxRetransmits) {
- if ((reply = replyQueue.poll()) != null)
- break;
-
- long now = System.currentTimeMillis();
- if (now - sendTimeStamp > retransmitTimeMs) {
- logger.debug("Retransmitting send... msg = " + msg.getPayload() + msg.getMsgId());
- publisher.send(msg);
- sendTimeStamp = System.currentTimeMillis();
- reTransmits++;
- }
- }
- waitingRequestersQueueList.removeQueueFromMap(msg.getMsgId());
- if (reTransmits == maxRetransmits)
- throw new UebException(PortalApiConstants.ECOMP_UEB_TIMEOUT_ERROR, inTopicName, null, msg.toString());
-
- }
- return reply;
- }
-
- /**
- * Sends the specified message using the default publisher and waits for a
- * reply.
- *
- * @param msg
- * @return Message from a remote publisher, or null if timeout happens.
- * @throws UebException
- */
- public UebMsg requestReply(UebMsg msg) throws UebException {
- return requestReplyUsingPublisher(msg, appPublisher);
- }
-
- /**
- * Sends the specified message using the publisher appropriate for the
- * specified topic name, and waits for a reply.
- *
- * @param msg
- * @param topicName
- * @return Message from a remote publisher, or null if timeout happens.
- * @throws UebException
- */
- public UebMsg requestReplyEP(UebMsg msg, String topicName) throws UebException {
- UebMsg returnMsg = null;
- Publisher publisher = publisherList.getPublisher(topicName);
- if (publisher != null) {
- returnMsg = requestReplyUsingPublisher(msg, publisher);
- }
- return returnMsg;
- }
-
- /**
- * Publishes the payload as a UEB widget-notification message on the default
- * publisher. Intended for use by Apps inter widget communication, not EP
- * itself.
- *
- * @param payload
- * @param userId
- */
- public void postWidgetNotification(String payload, String userId) throws UebException {
- UebMsg msg = new UebMsg();
- msg.putPayload(payload);
- msg.putUserId(userId);
- msg.putMsgType(UebMsgTypes.UEB_MSG_TYPE_WIDGET_NOTIFICATION);
- this.publish(msg);
- }
-
- /**
- * Interrupts the long-running thread that runs the consumer.
- */
- public void shutdown() {
- if (this.listenerThread != null) {
- this.listenerThread.interrupt();
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.ueb;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class UebMsg {
-
- private final Log logger = LogFactory.getLog(getClass());
-
- private String version;
- private String msgId;
- private long timeStamp;
- private String payload;
- private String msgType;
- private String userId;
- private String sourceTopicName;
- private String sourceIP;
- private String sourceHostName;
-
- /**
- * Creates a new object and populates the fields source IP, source topic,
- * time stamp, version, and message id.
- */
- public UebMsg() {
- InetAddress ip;
- try {
- ip = InetAddress.getLocalHost();
- // Do not attempt to get name, why wait on DNS every time?
- // sourceHostName = ip.getHostName();
- sourceIP = ip.getHostAddress();
- } catch (UnknownHostException e) {
- sourceHostName = "unknown";
- sourceIP = "unknown";
- }
-
- this.timeStamp = System.currentTimeMillis();
- this.version = "1.0";
- this.msgId = PortalApiConstants.ECOMP_DEFAULT_MSG_ID;
- this.payload = "empty payload content";
- this.sourceTopicName = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME);
- if (this.sourceTopicName == null)
- logger.error("Failed to get property " + PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME);
- }
-
- public void putMsgId(String msgId) {
- this.msgId = msgId;
- }
-
- public String getMsgId() {
- return msgId;
- }
-
- public void putPayload(String payload) {
- this.payload = payload;
- }
-
- public String getPayload() {
- return payload;
- }
-
- public void putMsgType(String msgType) {
- this.msgType = msgType;
- }
-
- public String getMsgType() {
- return this.msgType;
- }
-
- public void putUserId(String userId) {
- this.userId = userId;
- }
-
- public String getUserId() {
- return this.userId;
- }
-
- public void putSourceTopicName(String topic) {
- this.sourceTopicName = topic;
- }
-
- public String getSourceTopicName() {
- return this.sourceTopicName;
- }
-
- @Override
- public String toString() {
- return "UebMsg [version=" + version + ", msgId=" + msgId + ", timeStamp=" + timeStamp + ", msgType=" + msgType
- + ", userId=" + userId + ", sourceTopicName=" + sourceTopicName + ", sourceIP=" + sourceIP
- + ", sourceHostName=" + sourceHostName + "]" + System.lineSeparator() + "payload=" + payload;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.ueb;
-
-/**
- * Publishes constants used in the UEB package.
- */
-public interface UebMsgTypes {
- public static final String UEB_MSG_TYPE_GET_FUNC_MENU = "uebMsgTypeGetFuncMenu";
- public static final String UEB_MSG_TYPE_WIDGET_NOTIFICATION = "uebMsgTypeWidgetNotification";
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.ueb;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.LinkedBlockingQueue;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * A thin wrapper around ConcurrentHashMap that stores a queue for each
- * Requester that is waiting for a Reply. When a reply is received that has a
- * matching msgId, that requesters queue is populated with the reply message.
- *
- * Primarily for the UebManager to track requests while it waits for responses.
- */
-public class WaitingRequestersQueueList {
- private final Log logger = LogFactory.getLog(getClass());
-
- private final Map<String, LinkedBlockingQueue<UebMsg>> map;
-
- public WaitingRequestersQueueList() {
- map = new ConcurrentHashMap<>();
- }
-
- public void addQueueToMap(String msgId, LinkedBlockingQueue<UebMsg> queue) {
- this.map.put(msgId, queue);
- }
-
- public void addMsg(String msgId, UebMsg message) {
- LinkedBlockingQueue<UebMsg> queue = this.map.get(msgId);
- if (queue != null) {
- queue.add(message);
- } else {
- logger.warn("Did not find entry in WaitingRequestersQueueList for msgId " + msgId);
- }
- }
-
- public void removeQueueFromMap(String msgId) {
- this.map.remove(msgId);
- }
-
- public String toString() {
- StringBuffer sb = new StringBuffer();
- sb.append("Map contains " + this.map.size() + " Publishers.");
- for (Map.Entry<String, LinkedBlockingQueue<UebMsg>> entry : this.map.entrySet()) {
- String key = entry.getKey().toString();
- LinkedBlockingQueue<UebMsg> queue = entry.getValue();
- sb.append("Entry msgId, " + key + " queue " + queue);
- }
- return sb.toString();
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.restful.client;
-
-/**
- * Holds the status code and body that result from accessing an HTTP URL.
- */
-public class HttpStatusAndResponse {
-
- private int statusCode;
- private String response;
-
- public HttpStatusAndResponse(int status, String resp) {
- this.statusCode = status;
- this.response = resp;
- }
-
- public int getStatusCode() {
- return statusCode;
- }
-
- public String getResponse() {
- return response;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.restful.client;
-
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.http.Consts;
-import org.apache.http.HttpEntity;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.entity.ContentType;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.util.EntityUtils;
-import org.openecomp.portalsdk.core.domain.App;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-import org.openecomp.portalsdk.core.service.AppService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-/**
- * Provides a basic client to access a REST endpoint at the Portal via get or
- * post. Usage caveats:
- * <OL>
- * <LI>Must be auto-wired by Spring, because this in turn auto-wires a
- * data-access service to read application credentials from the FN_APP table.
- * <LI>If HTTP access is used and the server uses a self-signed certificate, the
- * local trust store must be extended appropriately. The HTTP client throws
- * exceptions if the JVM cannot validate the server certificate.
- * </OL>
- */
-@Component
-public class PortalRestClientBase {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalRestClientBase.class);
-
- @Autowired
- AppService appService;
-
- /**
- * Constructs and sends a GET request for the URI, with REST application
- * credentials in the header as the Portal expects.
- *
- * @param uri
- * URI of the service
- * @return Result of the get; null if an error happens
- * @throws URISyntaxException
- * @throws IOException
- * @throws ClientProtocolException
- */
- public HttpStatusAndResponse getRestWithCredentials(final URI uri) throws Exception {
-
- String uebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
- App app = appService.getDefaultApp();
- if (uebKey == null || app == null || app.getUsername() == null || app.getAppPassword() == null)
- throw new Exception("Missing one or more required properties and/or database entries");
- String decryptedPassword = CipherUtil.decrypt(app.getAppPassword());
- CloseableHttpClient httpClient = HttpClients.createDefault();
- HttpGet httpGet = new HttpGet(uri);
- httpGet.setHeader("uebkey", uebKey);
- httpGet.setHeader("username", app.getUsername());
- httpGet.setHeader("password", decryptedPassword);
-
- String responseJson = null;
- CloseableHttpResponse response = null;
- try {
- logger.info(EELFLoggerDelegate.debugLogger, "GET from " + uri);
- response = httpClient.execute(httpGet);
- logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine());
- if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
- logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine().toString());
- HttpEntity entity = response.getEntity();
- if (entity == null) {
- logger.info(EELFLoggerDelegate.debugLogger, "Entity is null!");
- } else {
- // entity content length is never set.
- // this naively tries to read everything.
- responseJson = EntityUtils.toString(entity);
- logger.info(EELFLoggerDelegate.debugLogger, responseJson);
- EntityUtils.consume(entity);
- }
- } finally {
- if (response != null)
- response.close();
- }
- if (response == null)
- return null;
- return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson);
- }
-
- /**
- * Constructs and sends a POST request using the specified body, with REST
- * application credentials in the header as the Portal expects.
- *
- * @param uri
- * REST endpoint
- * @param json
- * Content to post
- * @return Result of the post; null if an error happens
- * @throws Exception
- */
- public HttpStatusAndResponse postRestWithCredentials(final URI uri, final String json) throws Exception {
-
- String uebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
- App app = appService.getDefaultApp();
- if (uebKey == null || app == null || app.getUsername() == null || app.getAppPassword() == null)
- throw new Exception("Missing one or more required properties and/or database entries");
-
- CloseableHttpClient httpClient = HttpClients.createDefault();
- HttpPost httpPost = new HttpPost(uri);
- httpPost.setHeader("uebkey", uebKey);
- httpPost.setHeader("username", app.getUsername());
- httpPost.setHeader("password", app.getAppPassword());
-
- StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8));
- httpPost.setEntity(postEntity);
-
- String responseJson = null;
- CloseableHttpResponse response = null;
- try {
- logger.info(EELFLoggerDelegate.debugLogger, "POST to " + uri);
- response = httpClient.execute(httpPost);
- logger.info(EELFLoggerDelegate.debugLogger, "Status is " + response.getStatusLine());
- if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK)
- throw new Exception("Status is " + response.getStatusLine().toString());
-
- HttpEntity entity = response.getEntity();
- if (entity == null) {
- logger.info(EELFLoggerDelegate.debugLogger, "Entity is null!");
- } else {
- // entity content length is never set.
- // this naively tries to read everything.
- responseJson = EntityUtils.toString(entity);
- logger.info(EELFLoggerDelegate.debugLogger, responseJson);
- EntityUtils.consume(entity);
- }
- } finally {
- if (response != null)
- response.close();
- }
- return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.restful.client;
-
-import java.net.URI;
-import java.util.HashMap;
-import java.util.List;
-
-import org.apache.http.client.utils.URIBuilder;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-import org.openecomp.portalsdk.core.restful.domain.SharedContext;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-/**
- * Provides convenience methods to use the shared-context service at Portal.
- * This hides all JSON; instead it accepts and returns Java objects. Usage
- * caveats (repeated from superclass):
- * <OL>
- * <LI>Must be auto-wired by Spring, because this in turn auto-wires a data
- * access service to read application credentials from the FN_APP table.
- * <LI>If HTTP access is used and the server uses a self-signed certificate, the
- * local trust store must be extended appropriately. The HTTP client throws
- * exceptions if the JVM cannot validate the server certificate.
- * </OL>
- */
-@Component
-public class SharedContextRestClient extends PortalRestClientBase {
-
- @Autowired
- SystemProperties systemProperties;
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestClient.class);
-
- /**
- * Reusable JSON (de)serializer
- */
- private final ObjectMapper mapper = new ObjectMapper();
-
- /**
- * Builds the URl for the shared context service using the portal.properties
- * value for the AUXAPI endpoint.
- *
- * @throws Exception
- * if the ECOMP_REST_URL property is not found
- */
- private String getSharedContextUrl() throws Exception {
- String restUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
- if (restUrl == null || restUrl.length() == 0)
- throw new Exception("getSharedContextUrl: no property " + PortalApiConstants.ECOMP_REST_URL);
- String contextUrl = restUrl + (restUrl.endsWith("/") ? "" : "/") + "context/";
- return contextUrl;
- }
-
- /**
- * Gets the shared-context value for the specified context ID and key.
- *
- * @param contextId
- * An Ecomp Portal session ID
- * @param key
- * Key for the shared-context entry; e.g., "lastName"
- * @return SharedContext object; null if not found.
- * @throws Exception
- */
- public SharedContext getContextValue(String contextId, String key) throws Exception {
- HttpStatusAndResponse hsr = getContext("get", contextId, key);
- logger.info(EELFLoggerDelegate.debugLogger, "getSharedContext: resp is " + hsr);
- if (hsr == null) {
- logger.error(EELFLoggerDelegate.applicationLogger, "getContextValue: unexpected null response");
- return null;
- }
- SharedContext jsonObj = null;
- try {
- jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
- } catch (JsonMappingException ex) {
- logger.error(EELFLoggerDelegate.applicationLogger,
- "getContextValue: failed to map response onto object" + ex.getMessage());
- } catch (JsonParseException ex) {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "getContextValue: failed to parse response" + ex.getMessage());
- }
- if (jsonObj != null && jsonObj.getResponse() != null)
- return null;
- return jsonObj;
- }
-
- /**
- * Gets user information for the specified context ID.
- *
- * @param contextId
- * An Ecomp Portal session ID
- * @return List of SharedContext objects corresponding to the following
- * keys: USER_FIRST_NAME, USER_LAST_NAME, USER_EMAIL and
- * USER_ORGUSERID; empty if none were found; null if an error
- * happens.
- * @throws Exception
- */
- public List<SharedContext> getUserContext(String contextId) throws Exception {
- HttpStatusAndResponse hsr = getContext("get_user", contextId, null);
- logger.info(EELFLoggerDelegate.debugLogger, "getUserContext: resp is " + hsr);
- if (hsr == null) {
- logger.error(EELFLoggerDelegate.applicationLogger, "getUserContext: unexpected null response");
- return null;
- }
- List<SharedContext> jsonList = null;
- try {
- TypeReference<List<SharedContext>> typeRef = new TypeReference<List<SharedContext>>() {
- };
- jsonList = mapper.readValue(hsr.getResponse(), typeRef);
- } catch (JsonMappingException ex) {
- logger.error(EELFLoggerDelegate.applicationLogger,
- "getUserContext: failed to map response onto object" + ex.getMessage());
- } catch (JsonParseException ex) {
- logger.error(EELFLoggerDelegate.applicationLogger,
- "getUserContext: failed to parse response" + ex.getMessage());
- }
- return jsonList;
- }
-
- /**
- * Checks whether a shared-context entry exists for the specified context ID
- * and key.
- *
- * @param contextId
- * An Ecomp Portal session ID
- * @param key
- * Key for the shared-context entry; e.g., "lastName"
- * @return True if the object exists, false otherwise; null on error.
- * @throws Exception
- */
- public Boolean checkSharedContext(String contextId, String key) throws Exception {
- HttpStatusAndResponse hsr = getContext("check", contextId, key);
- logger.info(EELFLoggerDelegate.debugLogger, "checkSharedContext: resp is " + hsr);
- if (hsr == null) {
- logger.error(EELFLoggerDelegate.applicationLogger, "checkSharedContext: unexpected null response");
- return null;
- }
- String response = null;
- try {
- SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
- response = jsonObj.getResponse();
- } catch (JsonMappingException ex) {
- logger.error(EELFLoggerDelegate.applicationLogger,
- "checkSharedContext: failed to map response onto object" + ex.getMessage());
- } catch (JsonParseException ex) {
- logger.error(EELFLoggerDelegate.applicationLogger,
- "checkSharedContext: failed to parse response" + ex.getMessage());
- }
- if (response == null)
- return null;
- return ("exists".equals(response));
- }
-
- /**
- * Removes a shared-context entry with the specified context ID and key.
- *
- * @param contextId
- * An Ecomp Portal session ID
- * @param key
- * Key for the shared-context entry; e.g., "lastName"
- * @return True if the entry was removed, false otherwise; null on error.
- * @throws Exception
- */
- public Boolean removeSharedContext(String contextId, String key) throws Exception {
- HttpStatusAndResponse hsr = getContext("remove", contextId, key);
- logger.info(EELFLoggerDelegate.debugLogger, "removeSharedContext: resp is " + hsr);
- if (hsr == null) {
- logger.error(EELFLoggerDelegate.applicationLogger, "removeSharedContext: unexpected null response");
- return null;
- }
- SharedContext jsonObj = null;
- try {
- jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
- } catch (JsonMappingException ex) {
- logger.error(EELFLoggerDelegate.applicationLogger,
- "removeSharedContext: failed to map response onto object" + ex.getMessage());
- } catch (JsonParseException ex) {
- logger.error(EELFLoggerDelegate.applicationLogger,
- "removeSharedContext: failed to parse response" + ex.getMessage());
- }
- if (jsonObj == null)
- return null;
- String response = jsonObj.getResponse();
- return ("removed".equals(response));
- }
-
- /**
- * Clears the shared context for the specified context ID; i.e., removes all
- * key-value pairs.
- *
- * @param contextId
- * An Ecomp Portal session ID
- * @return Number of key-value pairs removed; -1 if not found or any
- * problems occur.
- * @throws Exception
- */
- public int clearSharedContext(String contextId) throws Exception {
- HttpStatusAndResponse hsr = getContext("remove", contextId, null);
- logger.info(EELFLoggerDelegate.debugLogger, "clearSharedContext: resp is " + hsr);
- if (hsr == null) {
- logger.error(EELFLoggerDelegate.applicationLogger, "clearSharedContext: unexpected null response");
- return -1;
- }
- SharedContext jsonObj = null;
- try {
- jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
- } catch (JsonMappingException ex) {
- logger.error(EELFLoggerDelegate.applicationLogger,
- "clearSharedContext: failed to map response onto object" + ex.getMessage());
- } catch (JsonParseException ex) {
- logger.error(EELFLoggerDelegate.applicationLogger,
- "clearSharedContext: failed to parse response" + ex.getMessage());
- }
- if (jsonObj == null)
- return -1;
- String response = jsonObj.getResponse();
- if (response == null)
- return -1;
- return Integer.parseInt(response);
- }
-
- /**
- * Creates a shared-context entry.
- *
- * @param contextId
- * An Ecomp Portal session ID
- * @param key
- * Key for the shared-context entry; e.g., "lastName"
- * @param value
- * Value for the entry
- * @throws Exception
- * @return True if the object previously existed, false otherwise; null if
- * any problem happened.
- */
- public Boolean setSharedContext(String contextId, String key, String value) throws Exception {
- String body = buildContext(contextId, key, value);
- HttpStatusAndResponse hsr = postContext("set", body);
- logger.info(EELFLoggerDelegate.debugLogger, "setSharedContext: resp is " + hsr);
- if (hsr == null) {
- logger.error(EELFLoggerDelegate.applicationLogger, "setSharedContext: unexpected null response");
- return null;
- }
- SharedContext jsonObj = null;
- try {
- jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
- } catch (JsonMappingException ex) {
- logger.error(EELFLoggerDelegate.applicationLogger,
- "setSharedContext: failed to map response onto object" + ex.getMessage());
- } catch (JsonParseException ex) {
- logger.error(EELFLoggerDelegate.applicationLogger,
- "setSharedContext: failed to parse response" + ex.getMessage());
- }
- if (jsonObj == null)
- return null;
- String response = jsonObj.getResponse();
- return ("replaced".equals(response));
- }
-
- /**
- * Builds the full URL with the specified parameters, then calls the method
- * that adds credentials and GETs.
- *
- * @param requestPath
- * @param contextId
- * @param contextKey
- * @return HttpStatusAndResponse object; may be null.
- * @throws Exception
- */
- private HttpStatusAndResponse getContext(String requestPath, String contextId, String contextKey) throws Exception {
- URIBuilder uriBuilder = new URIBuilder(getSharedContextUrl() + requestPath);
- uriBuilder.addParameter("context_id", contextId);
- if (contextKey != null)
- uriBuilder.addParameter("ckey", contextKey);
- final URI uri = uriBuilder.build();
- return getRestWithCredentials(uri);
- }
-
- /**
- * Builds the full URL, then calls the method that adds credentials and
- * POSTs.
- *
- * @param requestPath
- * @param contextId
- * @param contextKey
- * @return HttpStatusAndResponse object; may be null.
- * @throws Exception
- */
- private HttpStatusAndResponse postContext(String requestPath, String json) throws Exception {
- URIBuilder uriBuilder = new URIBuilder(getSharedContextUrl() + requestPath);
- URI uri = uriBuilder.build();
- return postRestWithCredentials(uri, json);
- }
-
- /**
- * Builds a JSON block with a single shared-context entry.
- *
- * @param cxid
- * Context ID
- * @param ckey
- * Context Key
- * @param cvalue
- * Context value
- * @return JSON block
- */
- private String buildContext(String cxid, String ckey, String cvalue) throws JsonProcessingException {
- ObjectMapper mapper = new ObjectMapper();
- HashMap<String, String> stringMap = new HashMap<String, String>();
- stringMap.put("context_id", cxid);
- stringMap.put("ckey", ckey);
- stringMap.put("cvalue", cvalue);
- String json = mapper.writeValueAsString(stringMap);
- return json;
- }
-
- // Simple test scaffold
- public static void main(String[] args) throws Exception {
- // ObjectMapper mapper = new ObjectMapper();
- // SharedContext cxt = mapper.readValue("{ \"response\":\"foo\" }",
- // SharedContext.class);
- SharedContextRestClient client = new SharedContextRestClient();
- SharedContext get = client.getContextValue("abc", "123");
- System.out.println("Get yields " + get.toString());
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.scheduler;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.quartz.CronTrigger;
-import org.quartz.Trigger;
-import org.springframework.context.annotation.DependsOn;
-import org.springframework.stereotype.Component;
-
-@Component
-@DependsOn({"systemProperties"})
-public class CoreRegister {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CoreRegister.class);
- Trigger trigger[] = new Trigger[1];
-
-
-
- //@Autowired
- //private SessionMgtRegistry sessionMgtRegistry;
-
- protected List<Trigger> scheduleTriggers = new ArrayList<Trigger>();
-
-
- public void registerTriggers() {
- // we can use this method to add any schedules to the core
-
- /*
- try {
- if(SystemProperties.getProperty(SystemProperties.SESSIONTIMEOUT_FEED_CRON) != null)
- getScheduleTriggers().add(sessionMgtRegistry.getTrigger());
-
- } catch(IllegalStateException ies) {
- logger.info("Session Timout Cron not available");
- }
- */
-
- }
-
- protected void addTrigger(final String cron, final CronTrigger cronRegistryTrigger) {
- // if the property value is not available; the cron will not be added and can be ignored. its safe to ignore the exceptions
-
- try {
-
- if(SystemProperties.getProperty(cron) != null) {
- getScheduleTriggers().add(cronRegistryTrigger);
- }
-
- } catch(IllegalStateException ies) {
- logger.error(EELFLoggerDelegate.errorLogger, "Log Cron not available", AlarmSeverityEnum.MAJOR);
- }
- }
-
-
-
-
- public List<Trigger> getScheduleTriggers() {
- return scheduleTriggers;
- }
-
-
-
- public void setScheduleTriggers(List<Trigger> scheduleTriggers) {
- this.scheduleTriggers = scheduleTriggers;
- }
-
-
-
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.scheduler;
-
-import java.text.ParseException;
-import java.util.Map;
-
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.quartz.CronTrigger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
-import org.springframework.scheduling.quartz.JobDetailFactoryBean;
-import org.springframework.scheduling.quartz.QuartzJobBean;
-
-import com.mchange.v2.c3p0.ComboPooledDataSource;
-
-public abstract class CronRegistry {
-
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CronRegistry.class);
- protected JobDetailFactoryBean jobDetailFactory;
- protected CronTriggerFactoryBean cronTriggerFactory;
-
- private ComboPooledDataSource dataSource;
-
- public CronRegistry() {
- try {
- jobDetailFactoryBean();
- cronTriggerFactoryBean();
- }
- catch(Exception e) {
- logger.error(EELFLoggerDelegate.debugLogger, e.getMessage());
- }
- }
-
- //@Autowired
- public CronRegistry(ComboPooledDataSource dataSource) {
- try {
- this.dataSource = dataSource;
- jobDetailFactoryBean();
- cronTriggerFactoryBean();
- }
- catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AlarmSeverityEnum.MAJOR);
- }
- }
-
- //@Autowired
- public CronRegistry(Object... initializeObjects) {
- try {
- initializeObjects(initializeObjects);
- jobDetailFactoryBean();
- cronTriggerFactoryBean();
- }
- catch(Exception e) {
- logger.info(EELFLoggerDelegate.errorLogger, e.getMessage());
- }
- }
-
- protected void initializeObjects(Object... initializeObjects) {
- }
-
- public abstract JobDetailFactoryBean jobDetailFactoryBean() throws ParseException;
-
- protected JobDetailFactoryBean jobDetailFactoryBean(String groupName, String jobName,
- Class<? extends QuartzJobBean> jobClass, Map<String, Object> map) {
-
- jobDetailFactory = new JobDetailFactoryBean();
- jobDetailFactory.setJobClass(jobClass);
- jobDetailFactory.setJobDataAsMap(map);
- jobDetailFactory.setGroup(groupName);
- jobDetailFactory.setName(jobName);
- jobDetailFactory.afterPropertiesSet();
-
- return jobDetailFactory;
- }
-
- public abstract CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException;
-
- protected CronTriggerFactoryBean cronTriggerFactoryBean(String groupName, String triggerName, String cronExpression) throws ParseException {
- cronTriggerFactory = new CronTriggerFactoryBean();
- cronTriggerFactory.setJobDetail(jobDetailFactory.getObject());
- cronTriggerFactory.setStartDelay(3000);
- cronTriggerFactory.setName(triggerName);
- cronTriggerFactory.setGroup(groupName);
- logger.info(EELFLoggerDelegate.applicationLogger, triggerName + " Scheduled: " + cronExpression);
- cronTriggerFactory.setCronExpression( cronExpression); //"0 * * * * ? *"
- cronTriggerFactory.afterPropertiesSet();
- return cronTriggerFactory;
- }
-
- public CronTrigger getTrigger() {
- return cronTriggerFactory.getObject();
- }
-
-
- public void setDataSource(ComboPooledDataSource dataSource) {
- this.dataSource = dataSource;
- }
-
-
- public ComboPooledDataSource getDataSource() {
- return dataSource;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.scheduler;
-
-import org.quartz.Trigger;
-
-public interface Registerable {
-
- public void registerTriggers();
-
- public Trigger[] getTriggers();
-
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Conditional;
-import org.springframework.context.annotation.Configuration;
-
-@Configuration
-public class AccessConfiguration {
-
- /**
- *
- * @return RoleServiceImpl bean if LocalAccessCondition is true
- */
- @Bean
- @Conditional(LocalAccessCondition.class)
- public RoleService roleServiceImpl() {
- return new RoleServiceImpl();
- }
-
- /**
- *
- * @return RoleServiceCentralizedAccess bean if CentralAccessCondition is true
- */
- @Bean
- @Conditional(CentralAccessCondition.class)
- public RoleService roleServiceCentralizedAccess() {
- return new RoleServiceCentralizedAccess();
- }
-
- /**
- *
- * @return LoginServiceImpl bean if LocalAccessCondition is true
- */
- @Bean
- @Conditional(LocalAccessCondition.class)
- public LoginService loginServiceImpl() {
- return new LoginServiceImpl();
- }
-
- /**
- *
- * @return LoginServiceCentralizedImpl bean if CentralAccessCondition is true
- */
- @Bean
- @Conditional(CentralAccessCondition.class)
- public LoginService loginServiceCEntralizedImpl() {
- return new LoginServiceCentralizedImpl();
- }
-
- /**
- *
- * @return UserProfileServiceImpl bean if LocalAccessCondition is true
- */
- @Bean
- @Conditional(LocalAccessCondition.class)
- public UserService userServiceImpl() {
- return new UserServiceImpl();
- }
-
- /**
- *
- * @return returns UserProfileServiceCentalizedImpl bean if
- * CentralAccessCondition is true
- */
- @Bean
- @Conditional(CentralAccessCondition.class)
- public UserService userServiceCentalizedImpl() {
- return new UserServiceCentalizedImpl();
- }
-
- /**
- *
- * @return returns ProfileServiceImpl bean if LocalAccessCondition is true
- */
- @Bean
- @Conditional(LocalAccessCondition.class)
- public ProfileService profileServiceImpl() {
- return new ProfileServiceImpl();
- }
-
- /**
- *
- * @return returns ProfileServiceCentralizedImpl bean if CentralAccessCondition
- * is true
- */
-
- @Bean
- @Conditional(CentralAccessCondition.class)
- public ProfileService profileServiceCentralizedImpl() {
- return new ProfileServiceCentralizedImpl();
- }
-
- /**
- *
- * @return returns RestApiRequestBuilder bean if CentralAccessCondition is true
- */
- @Bean
- @Conditional(CentralAccessCondition.class)
- public RestApiRequestBuilder restApiRequestBuilder() {
- return new RestApiRequestBuilder();
- }
-
- /**
- *
- * @return returns FunctionalMenuListServiceImpl bean if LocalAccessCondition is
- * true
- */
- @Bean
- @Conditional(LocalAccessCondition.class)
- public FunctionalMenuListService functionalMenuListService() {
- return new FunctionalMenuListServiceImpl();
- }
-
- /**
- *
- * @return returns FunctionalMenuListServiceCentralizedImpl bean if
- * CentralAccessCondition is true
- */
-
- @Bean
- @Conditional(CentralAccessCondition.class)
- public FunctionalMenuListService functionalMenuListServiceCentralizedImpl() {
- return new FunctionalMenuListServiceCentralizedImpl();
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.domain.App;
-
-/**
- * Defines methods to fetch App domain objects.
- *
- * Very thin interface; Portal defines a much richer interface.
- */
-public interface AppService {
-
- /**
- * Gets all apps defined in the table.
- *
- * @return List of apps.
- */
- List<App> getApps();
-
- /**
- * Gets the app with the specified ID.
- *
- * @param appId
- * @return App with the specified ID.
- */
- App getApp(Long appId);
-
- /**
- * Gets the singleton entry - applications should have exactly 1 row in the
- * FN_APP table.
- */
- App getDefaultApp();
-
- /**
- * Fetches the application name once from database
- * and keep refers to the same name later on as required.
- * @return Default Application Name
- */
- String getDefaultAppName();
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.domain.App;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-@Service("appService")
-@Transactional
-public class AppServiceImpl implements AppService{
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppServiceImpl.class);
-
- @Autowired
- private DataAccessService dataAccessService;
-
- /**
- * Loads the appName once from database and
- * keep refers to it as required.
- */
- private static String defaultAppName = "";
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalsdk.core.service.AppService#getApps()
- */
- @SuppressWarnings("unchecked")
- @Override
- public List<App> getApps() {
- return getDataAccessService().getList(App.class, null);
- }
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalsdk.service.AppService#getApp(long)
- */
- @Override
- public App getApp(Long appId) {
- return (App)getDataAccessService().getDomainObject(App.class, appId, null);
- }
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalsdk.service.AppService#getApp()
- */
- @Override
- public App getDefaultApp() {
- return getApp(1L);
- }
-
- /**
- * Gets the data access service.
- * @return DataAccessService
- */
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- /**
- * Sets the data access service.
- * @param dataAccessService
- */
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- /**
- * Fetches the application name once from database
- * and keep refers to the same name later on as required.
- * @return Default Application Name
- */
- @Override
- public String getDefaultAppName() {
- if (AppServiceImpl.defaultAppName==null || AppServiceImpl.defaultAppName=="") {
- App app = getApp(1L);
- if (app!=null) {
- AppServiceImpl.defaultAppName = app.getName();
- } else {
- logger.warn(EELFLoggerDelegate.errorLogger, ("Unable to locate the app information from the database."));
- }
- }
- return AppServiceImpl.defaultAppName;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.HashMap;
-
-import org.openecomp.portalsdk.core.domain.AuditLog;
-
-public interface AuditService {
- /**
- *
- * Update log data in database
- *
- * @param auditLog
- * @param additionalParams
- */
-
- @SuppressWarnings("rawtypes")
- void logActivity(AuditLog auditLog, HashMap additionalParams);
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.HashMap;
-
-import org.openecomp.portalsdk.core.domain.AuditLog;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-@Service("auditService")
-@Transactional
-public class AuditServiceImpl implements AuditService {
- public AuditServiceImpl() {}
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @SuppressWarnings("rawtypes")
- public void logActivity(AuditLog auditLog, HashMap additionalParams) {
- getDataAccessService().saveDomainObject(auditLog, additionalParams);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.*;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.domain.BroadcastMessage;
-
-@SuppressWarnings("rawtypes")
-public interface BroadcastService {
- HashMap getBcModel(HttpServletRequest request);
- Hashtable getBroadcastMessages();
- void loadMessages();
- BroadcastMessage getBroadcastMessage(HttpServletRequest request);
- void saveBroadcastMessage(BroadcastMessage broadcastMessage);
- void removeBroadcastMessage(BroadcastMessage broadcastMessage);
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Set;
-import java.util.TreeSet;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.domain.BroadcastMessage;
-import org.openecomp.portalsdk.core.domain.Lookup;
-import org.openecomp.portalsdk.core.service.support.FusionService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-import org.springframework.web.bind.ServletRequestBindingException;
-import org.springframework.web.bind.ServletRequestUtils;
-
-@SuppressWarnings("rawtypes")
-@Service("broadcastService")
-@Transactional
-public class BroadcastServiceImpl extends FusionService implements BroadcastService {
-
- public BroadcastServiceImpl() {
- }
-
- @Autowired
- private DataAccessService dataAccessService;
- private static Hashtable broadcastMessages = new Hashtable();
-
- @SuppressWarnings("unchecked")
- public void loadMessages() {
- List messageLocations = AppUtils.getLookupListNoCache("fn_lu_message_location", "message_location_id", "message_location_descr", "", "message_location_id");
-
- for (int i=0; i < messageLocations.size(); i++) {
- Lookup location = (Lookup)messageLocations.get(i);
- String locationId = location.getValue();
-
- broadcastMessages.put(locationId, getPersistedBroadcastMessages(locationId));
- }
- }
-
- public HashMap getBcModel(HttpServletRequest request){
- HashMap bcModel = new HashMap();
-
- List items = null;
- int messageId = ServletRequestUtils.getIntParameter(request, "message_id", 0);
- String task = ServletRequestUtils.getStringParameter(request, "task", "get");
-
- // delete or toggle activation on the selected record (if applicable)
- if (messageId != 0 && (task.equals("delete") || task.equals("toggleActive"))) {
- BroadcastMessage message = (BroadcastMessage)getDataAccessService().getDomainObject(BroadcastMessage.class, new Long(messageId), null);
-
- if (task.equals("delete")) {
- getDataAccessService().deleteDomainObject(message, null);
- }
- else if (task.equals("toggleActive")) {
- HashMap additionalParams = new HashMap();
- additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request);
-
- message.setActive(new Boolean(!message.getActive().booleanValue()));
- getDataAccessService().saveDomainObject(message, additionalParams);
- }
- loadMessages();
- }
-
- items = getDataAccessService().getList(BroadcastMessage.class, null);
- Collections.sort(items);
- bcModel.put("messagesList", packageMessages(items));
-
- List locations = AppUtils.getLookupList("fn_lu_message_location", "message_location_id", "message_location_descr", "", "message_location_id");
- bcModel.put("messageLocations", locations);
-
- if ("true".equals(SystemProperties.getProperty(SystemProperties.CLUSTERED))) {
- List sites = AppUtils.getLookupList("fn_lu_broadcast_site", "broadcast_site_cd", "broadcast_site_descr", "", "broadcast_site_descr");
- bcModel.put("broadcastSites", sites);
- }
-
- return bcModel;
- }
-
- @SuppressWarnings("unchecked")
- private HashMap packageMessages(List messages) {
- HashMap messagesList = new HashMap();
- Set locationMessages = null;
-
- Integer previousLocationId = null;
-
- for (int i=0; i < messages.size(); i++) {
- BroadcastMessage message = (BroadcastMessage)messages.get(i);
-
- if (!message.getLocationId().equals(previousLocationId)) {
- if (previousLocationId != null) {
- messagesList.put(previousLocationId.toString(), locationMessages);
- }
-
- locationMessages = new TreeSet();
- previousLocationId = message.getLocationId();
- }
-
- locationMessages.add(message);
- }
-
- if (previousLocationId != null) {
- messagesList.put(previousLocationId.toString(), locationMessages);
- }
-
- return messagesList;
- }
-
-
- @SuppressWarnings("unchecked")
- private List getPersistedBroadcastMessages(String locationId) {
- HashMap params = new HashMap();
-
-
-
- params.put("location_id", new Integer(locationId));
-
- Calendar calInstanceToday = Calendar.getInstance();
- calInstanceToday.set(Calendar.HOUR, 0);
- calInstanceToday.set(Calendar.MINUTE, 0);
- calInstanceToday.set(Calendar.SECOND, 0);
- params.put("today_date", calInstanceToday.getTime());
-
- return getDataAccessService().executeNamedQuery("broadcastMessages", params, null);
- }
-
- public Hashtable getBroadcastMessages() {
- return broadcastMessages;
- }
-
- public static List getBroadcastMessages(String locationId) {
- return (List)broadcastMessages.get(locationId);
- }
-
- public static String displayMessages(String locationId) {
- return displayServerMessages(locationId, null);
- }
-
- public static String displayServerMessages(String locationId, String siteCd) {
- StringBuffer html = new StringBuffer();
-
- List messages = getBroadcastMessages(locationId);
-
- for (int i=0; i < messages.size(); i++) {
- BroadcastMessage message = (BroadcastMessage)messages.get(i);
-
- if ((message.getSiteCd() == null) || ((message.getSiteCd() != null) && message.getSiteCd().equals(siteCd))) {
- html.append("<li class=\"broadcastMessage\">")
- .append(message.getMessageText());
- }
- }
-
- if (html.length() > 0) {
- html.insert(0, "<ul class=\"broadcastMessageList\">");
- html.append("</ul>");
- }
-
- return html.toString();
- }
-
- public static boolean hasMessages(String locationId) {
- return hasServerMessages(locationId, null);
- }
-
- public static boolean hasServerMessages(String locationId, String siteCd) {
- List messages = getBroadcastMessages(locationId);
-
- boolean messagesExist = !((messages == null) || messages.size() == 0);
-
- if (siteCd == null) {
- return messagesExist;
- }
- else {
- for (int i=0; i < messages.size(); i++) {
- BroadcastMessage message = (BroadcastMessage)messages.get(i);
-
- if ((message.getSiteCd() == null) || message.getSiteCd().equals(siteCd)) {
- return true;
- }
- }
- return false;
- }
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- dataAccessService = dataAccessService;
- }
-
- public BroadcastMessage getBroadcastMessage(HttpServletRequest request) {
- long messageId = ServletRequestUtils.getLongParameter(request, "message_id", 0);
-
- BroadcastMessage message = new BroadcastMessage();
- if(messageId!=0)
- message = (BroadcastMessage)getDataAccessService().getDomainObject(BroadcastMessage.class, new Long(messageId), null);
-
- if (message.getLocationId() == null) {
- try {
- message.setLocationId(new Integer(ServletRequestUtils.getStringParameter(request, "message_location_id")));
- } catch (NumberFormatException e) {
- e.printStackTrace();
- } catch (ServletRequestBindingException e) {
- e.printStackTrace();
- }
- message.setActive(Boolean.TRUE);
- }
-
- return message;
- }
-
- @Override
- public void saveBroadcastMessage(BroadcastMessage broadcastMessage) {
- dataAccessService.saveDomainObject(broadcastMessage, null);
- }
-
- @Override
- public void removeBroadcastMessage(BroadcastMessage broadcastMessage) {
- dataAccessService.deleteDomainObject(broadcastMessage, null);
- }
-
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-import org.springframework.context.annotation.Condition;
-import org.springframework.context.annotation.ConditionContext;
-import org.springframework.core.type.AnnotatedTypeMetadata;
-
-
-public class CentralAccessCondition implements Condition {
-
- /**
- * returns true if the application is centralized
- */
-
- @Override
- public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
- boolean isRemote = false;
-
- if(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) == null)
- {
- isRemote = false;
- }
- else if(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) != null && PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED).equals("remote")){
- isRemote = true;
- }
-
- return isRemote;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-
-import java.io.Serializable;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.hibernate.FetchMode;
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Order;
-import org.hibernate.criterion.ProjectionList;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-@SuppressWarnings("rawtypes")
-public interface DataAccessService {
-
- // generic view, save, delete methods
- DomainVo getDomainObject(Class domainClass, Serializable id, HashMap additionalParams);
- void deleteDomainObject(DomainVo domainObject, HashMap additionalParams);
- void deleteDomainObjects(Class domainClass, String whereClause, HashMap additionalParams);
- void saveDomainObject(DomainVo domainObject, HashMap additionalParams);
-
- // generic get list method(s)
- List getList(Class domainClass, HashMap additionalParams);
- List getList(Class domainClass, String filter, String orderBy, HashMap additionalParams);
- List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy, HashMap additionalParams);
- List<?> getList(Class<?> domainClass, ProjectionList projectionsList , List<Criterion> restrictionsList , List<Order> orderByList);
- public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList, List<Order> orderByList,HashMap<String,FetchMode> fetchModeMap);
-
- List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, HashMap additionalParams);
-
- // generic native-SQL execution methods
- List executeSQLQuery(String sql, Class domainClass, HashMap additionalParams);
- List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex,HashMap additionalParams);
-
- // generic HQL execution methods
- List executeQuery(String hql, HashMap additionalParams);
- List executeQuery(String hql, Integer fromIndex, Integer toIndex, HashMap additionalParams);
-
- // generic named query execution methods
- List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, HashMap additionalParams);
- List executeNamedQuery(String queryName, Map params, HashMap additionalParams);
- List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex, HashMap additionalParams);
-
- //with Where Clause for RAPTOR ZK
- List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams);
- List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params);
- List executeNamedQuery(Class entity, String queryName, String whereClause, Map params, Integer fromIndex, Integer toIndex, HashMap additionalParams);
- List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams);
-
- // generic update query execution method
- int executeUpdateQuery(String sql, HashMap additionalParams) throws RuntimeException;
-
- // generic named update query execution method
- int executeNamedUpdateQuery(String queryName, Map params, HashMap additionalParams) throws RuntimeException;
-
- // synchronizes the local updates with the database (and vice versa)
- void synchronize(HashMap additionalParams);
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.hibernate.Criteria;
-import org.hibernate.FetchMode;
-import org.hibernate.Query;
-import org.hibernate.SQLQuery;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Order;
-import org.hibernate.criterion.ProjectionList;
-import org.openecomp.portalsdk.core.domain.Lookup;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.support.FusionService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.transaction.annotation.Transactional;
-
-/**
- * Provides implementations of methods in {@link DataAccessService}.
- */
-@Transactional
-public class DataAccessServiceImpl extends FusionService implements DataAccessService {
-
- @Autowired
- private SessionFactory sessionFactory;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DataAccessServiceImpl.class);
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#getDomainObject(java.lang.
- * Class, java.io.Serializable, java.util.HashMap)
- */
- @Override
- public DomainVo getDomainObject(Class domainClass, Serializable id, HashMap additionalParams) {
- DomainVo vo = null;
- Session session = sessionFactory.getCurrentSession();
- logger.info(EELFLoggerDelegate.debugLogger, "Getting " + domainClass.getName() + " record for id - " + id.toString());
- vo = (DomainVo) session.get(domainClass, id);
-
- if (vo == null) {
- try {
- vo = (DomainVo) domainClass.newInstance();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "An error occured while instantiating a class of " + domainClass.getName() + e.getMessage());
- }
- }
- return vo;
- }
-
- /*
- * (non-Javadoc)
- *
- */
- @Override
- public void deleteDomainObject(DomainVo domainObject, HashMap additionalParams) {
- Session session = sessionFactory.getCurrentSession();
- session.delete(domainObject);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#deleteDomainObjects(java.
- * lang.Class, java.lang.String, java.util.HashMap)
- */
- @Override
- public void deleteDomainObjects(Class domainClass, String whereClause, HashMap additionalParams) {
- int rowsAffected = 0;
- Session session = sessionFactory.getCurrentSession();
-
- StringBuffer sql = new StringBuffer("delete from ");
-
- sql.append(domainClass.getName()).append(" where ").append(whereClause);
-
- rowsAffected = session.createQuery(sql.toString()).executeUpdate();
- /* return rowsAffected; */
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#saveDomainObject
- */
- @Override
- public void saveDomainObject(DomainVo vo, HashMap additionalParams) {
- Integer userId = 1;
- if (additionalParams != null) {
- // look for a passed user id
- // userId = (Integer)additionalParams.get(Parameters.PARAM_USERID);
- Object uid = additionalParams.get(Parameters.PARAM_USERID);
- if (uid instanceof Integer) {
- userId = (Integer) uid;
- } else if (uid instanceof Long) {
- userId = ((Long) uid).intValue();
- }
- // if (userId == null) {
- // look for a passed request to get the user id from
- // userId = new
- // Integer(UserUtils.getUserId((HttpServletRequest)additionalParams.get(Parameters.PARAM_HTTP_REQUEST)));
- // }
- }
- _update(vo, userId);
- }
-
- /**
- * Creates or updates the specified virtual object. Uses the specified user
- * ID as the creator and modifier if a new object is created; uses ID only
- * as modifier if an object already exists.
- *
- * @param vo
- * @param userId
- * Ignored if value is zero.
- */
- protected final void _update(DomainVo vo, int userId) {
- Date timestamp = new Date();
-
- Session session = sessionFactory.getCurrentSession();
-
- if (vo.getId() == null || vo.getId().intValue() == 0) { // add new
- vo.setCreated(timestamp);
- vo.setModified(timestamp);
-
- if (userId != 0
- && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
- vo.setCreatedId(new Long(userId));
- vo.setModifiedId(new Long(userId));
- }
- } else { // update existing
- vo.setModified(timestamp);
-
- if (userId != 0
- && userId != Integer.parseInt(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID))) {
- vo.setModifiedId(new Long(userId));
- }
- }
-
- session.saveOrUpdate(vo);
- }
-
- /**
- * generic get list method
- *
- * @param domainClass
- * @param filterClause
- * @param fromIndex
- * @param toIndex
- * @param orderBy
- * @return
- */
- private List getListCommon(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex,
- String orderBy) {
- List list = null;
- String className = domainClass.getName();
- Session session = sessionFactory.getCurrentSession();
-
- if (logger.isInfoEnabled()) {
- logger.info(EELFLoggerDelegate.debugLogger, "Getting " + className.toLowerCase() + " records"
- + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "")
- + "...");
- if (filterClause != null && filterClause.length() > 0)
- logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause);
- }
-
- list = session.createQuery("from " + className + Utilities.nvl(filterClause, "")
- + ((orderBy != null) ? " order by " + orderBy : "")).list();
- list = (fromIndex != null) ? list.subList(fromIndex.intValue() - 1, toIndex.intValue()) : list;
-
- if (orderBy == null && list != null)
- Collections.sort(list);
-
- return list;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class,
- * java.util.HashMap)
- */
- @Override
- public List getList(Class domainClass, HashMap additionalParams) {
- return getListCommon(domainClass, null, null, null, null);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class,
- * java.lang.String, java.lang.String, java.util.HashMap)
- */
- @Override
- public List getList(Class domainClass, String filter, String orderBy, HashMap additionalParams) {
- return getListCommon(domainClass, filter, null, null, orderBy);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class,
- * java.lang.String, int, int, java.lang.String, java.util.HashMap)
- */
- @Override
- public List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy,
- HashMap additionalParams) {
- return getListCommon(domainClass, filter, new Integer(fromIndex), new Integer(toIndex), orderBy);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class,
- * org.hibernate.criterion.ProjectionList, java.util.List, java.util.List)
- */
- @Override
- public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
- List<Order> orderByList) {
-
- Session session = sessionFactory.getCurrentSession();
-
- Criteria criteria = session.createCriteria(domainClass);
-
- if (projectionsList != null) {
- criteria.setProjection(projectionsList);
- }
-
- if (restrictionsList != null && !restrictionsList.isEmpty()) {
- for (Criterion criterion : restrictionsList)
- criteria.add(criterion);
- }
-
- if (orderByList != null && !orderByList.isEmpty()) {
- for (Order order : orderByList)
- criteria.addOrder(order);
- }
- /*
- * if(fetchModeMap!=null){ Iterator<String> itr =
- * fetchModeMap.keySet().iterator(); String key=null;
- * while(itr.hasNext()){ key = itr.next();
- * criteria.setFetchMode(key,fetchModeMap.get(key)); } }
- */
- return criteria.list();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#getLookupList(java.lang.
- * String, java.lang.String, java.lang.String, java.lang.String,
- * java.lang.String, java.util.HashMap)
- */
- @Override
- public List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy,
- HashMap additionalParams) {
- if (logger.isInfoEnabled())
- logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list...");
- String dbOrderByCol = dbOrderBy;
-
- Session session = sessionFactory.getCurrentSession();
-
- // default the orderBy if null;
- if (Utilities.nvl(dbOrderBy).length() == 0) {
- dbOrderByCol = dbLabelCol;
- dbOrderBy = dbLabelCol;
- } else {
- if (dbOrderBy.lastIndexOf(" ") > -1) {
- dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" "));
- }
- }
-
- StringBuffer sql = new StringBuffer();
-
- sql.append("select distinct ").append(dbLabelCol).append(" as lab, ").append(dbValueCol).append(" as val, ")
- .append(dbOrderByCol).append(" as sortOrder ").append("from ").append(dbTable).append(" ")
- .append((Utilities.nvl(dbFilter).length() == 0) ? "" : (" where " + dbFilter)).append(" order by ")
- .append(dbOrderBy);
-
- List list = null;
- try {
- list = session.createSQLQuery(sql.toString()).addEntity(Lookup.class).list();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.debugLogger, "Failed to create SQL lookup query for [" + sql + "]" + e.getMessage());
- }
- return list;
- }
-
- /*
- * methods accepting a Map of additional params to passed to the DAO (for
- * extensibility, just in case)
- */
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#executeSQLQuery(java.lang.
- * String, java.lang.Class, java.util.HashMap)
- */
- @Override
- public List executeSQLQuery(String sql, Class domainClass, HashMap additionalParams) {
- return executeSQLQuery(sql, domainClass, null, null, additionalParams);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#executeSQLQuery(java.lang.
- * String, java.lang.Class, java.lang.Integer, java.lang.Integer,
- * java.util.HashMap)
- */
- @Override
- public List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex,
- HashMap additionalParams) {
- Session session = sessionFactory.getCurrentSession();
-
- SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass);
-
- if (fromIndex != null && toIndex != null) {
- query.setFirstResult(fromIndex.intValue());
- int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
- query.setMaxResults(pageSize);
- }
-
- return query.list();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#executeQuery(java.lang.
- * String, java.util.HashMap)
- */
- @Override
- public List executeQuery(String sql, HashMap additionalParams) {
- return executeQuery(sql, null, null, additionalParams);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#executeQuery(java.lang.
- * String, java.lang.Integer, java.lang.Integer, java.util.HashMap)
- */
- @Override
- public List executeQuery(String sql, Integer fromIndex, Integer toIndex, HashMap additionalParams) {
- Session session = sessionFactory.getCurrentSession();
-
- Query query = session.createQuery(sql);
-
- if (fromIndex != null && toIndex != null) {
- query.setFirstResult(fromIndex.intValue());
- int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
- query.setMaxResults(pageSize);
- }
-
- return query.list();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedQuery(java.lang
- * .String, java.lang.Integer, java.lang.Integer, java.util.HashMap)
- */
- @Override
- public List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, HashMap additionalParams) {
- return executeNamedQuery(queryName, null, fromIndex, toIndex, additionalParams);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedQuery(java.lang
- * .String, java.util.Map, java.util.HashMap)
- */
- @Override
- public List executeNamedQuery(String queryName, Map params, HashMap additionalParams) {
- return executeNamedQuery(queryName, params, null, null, additionalParams);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedQuery(java.lang
- * .String, java.util.Map, java.lang.Integer, java.lang.Integer,
- * java.util.HashMap)
- */
- @Override
- public List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex,
- HashMap additionalParams) {
- Session session = sessionFactory.getCurrentSession();
- Query query = session.getNamedQuery(queryName);
- bindQueryParameters(query, params);
- if (fromIndex != null && toIndex != null) {
- query.setFirstResult(fromIndex.intValue());
- int pageSize = (toIndex.intValue() - fromIndex.intValue()) + 1;
- query.setMaxResults(pageSize);
- }
- return query.list();
- }
-
- /**
- * Stores parameters into the query using String keys from the map. Gives
- * special treatment to map values of Collection and array type.
- *
- * @param query
- * Query with parameters
- * @param params
- * Map of String to Object.
- */
- private void bindQueryParameters(Query query, Map params) {
- if (params != null) {
- for (Iterator i = params.entrySet().iterator(); i.hasNext();) {
- Map.Entry entry = (Map.Entry) i.next();
-
- Object parameterValue = entry.getValue();
-
- if (!(parameterValue instanceof Collection) && !(parameterValue instanceof Object[])) {
- query.setParameter((String) entry.getKey(), parameterValue);
- } else if (parameterValue instanceof Collection) {
- query.setParameterList((String) entry.getKey(), (Collection) parameterValue);
- } else if (parameterValue instanceof Object[]) {
- query.setParameterList((String) entry.getKey(), (Object[]) parameterValue);
- }
- }
- }
- }
-
- // With Where Clause & RAPTOR's ZK
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalsdk.core.service.DataAccessService#
- * executeNamedQueryWithOrderBy(java.lang.Class, java.lang.String,
- * java.util.Map, java.lang.String, boolean, java.lang.Integer,
- * java.lang.Integer, java.util.HashMap)
- */
- @Override
- public List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy, boolean asc,
- Integer fromIndex, Integer toIndex, HashMap additionalParams) {
- // TODO Auto-generated method stub
- logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedCountQuery(java
- * .lang.Class, java.lang.String, java.lang.String, java.util.Map)
- */
- @Override
- public List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params) {
- // TODO Auto-generated method stub
- logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedQuery(java.lang
- * .Class, java.lang.String, java.lang.String, java.util.Map,
- * java.lang.Integer, java.lang.Integer, java.util.HashMap)
- */
- @Override
- public List executeNamedQuery(Class entity, String queryName, String whereClause, Map params, Integer fromIndex,
- Integer toIndex, HashMap additionalParams) {
- // TODO Auto-generated method stub
- logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalsdk.core.service.DataAccessService#
- * executeNamedQueryWithOrderBy(java.lang.Class, java.lang.String,
- * java.lang.String, java.util.Map, java.lang.String, boolean,
- * java.lang.Integer, java.lang.Integer, java.util.HashMap)
- */
- @Override
- public List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params,
- String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams) {
- // TODO Auto-generated method stub
- logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#getList(java.lang.Class,
- * org.hibernate.criterion.ProjectionList, java.util.List, java.util.List,
- * java.util.HashMap)
- */
- @Override
- public List<?> getList(Class<?> domainClass, ProjectionList projectionsList, List<Criterion> restrictionsList,
- List<Order> orderByList, HashMap<String, FetchMode> fetchModeMap) {
- // TODO Auto-generated method stub
- logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#executeUpdateQuery(java.
- * lang.String, java.util.HashMap)
- */
- @Override
- public int executeUpdateQuery(String sql, HashMap additionalParams) throws RuntimeException {
- // TODO Auto-generated method stub
- logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
- return 0;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalsdk.core.service.DataAccessService#executeNamedUpdateQuery(
- * java.lang.String, java.util.Map, java.util.HashMap)
- */
- @Override
- public int executeNamedUpdateQuery(String queryName, Map params, HashMap additionalParams) throws RuntimeException {
- // TODO Auto-generated method stub
- logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
- return 0;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalsdk.core.service.DataAccessService#synchronize(java.util.
- * HashMap)
- */
- @Override
- public void synchronize(HashMap additionalParams) {
- // TODO Auto-generated method stub
- logger.info(EELFLoggerDelegate.debugLogger, "Not implemented");
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.util.YamlUtils;
-
-public class ElementLinkService {
-
- /**
- * Builds renderable model of element links in the network map. Parses YAML
- * files with metadata and builds input for JoinJS to render in the browser
- * as SVG.
- *
- * @param args
- * arg 0 - realPath; arg 1 - callFlowName; arg 2 - callFlowStep.
- * @return Renderable model of element links
- * @throws Exception
- */
- public String buildElementLinkYaml(String[] args) throws Exception {
- String relFilePath;
- if (args[1].startsWith("custom"))
- relFilePath = SystemProperties.getProperty("customCallFlow_path");
- else
- relFilePath = SystemProperties.getProperty("element_map_file_path");
- final String yamlDirPath = new File(args[0], relFilePath).getPath();
-
- String callFlowBusinessYml = "";
- String callFlowStep = "";
-
- if (args != null && args.length > 0) {
- if (args[1] != null)
- callFlowBusinessYml = args[1] + ".yml";
- if (args[2] != null)
- callFlowStep = args[2];
- }
-
- ElementLinkService mapper = new ElementLinkService();
- String linkYaml = mapper.createLinkFile(yamlDirPath, callFlowBusinessYml, callFlowStep);
- return linkYaml;
- }
-
- /*
- * public String main2(String[] args) throws Exception {
- *
- * String filePath = SystemProperties.getProperty("element_map_file_path") +
- * File.separator; String callFlowBusinessYml = ""; String callFlowStep =
- * "";
- *
- * if (args != null && args.length > 0) {
- *
- * if (args[0] != null) { callFlowBusinessYml = args[0] + "-Override.yml"; }
- *
- * if (args[1] != null) { callFlowStep = args[1]; } }
- *
- * ElementLinkService mapper = new ElementLinkService();
- *
- * return mapper.createLinkFileAdditional(filePath, callFlowBusinessYml,
- * callFlowStep); }
- */
-
- public static void main(String[] args) throws Exception {
-
- String filePath = "\\D2Platform\\war\\WEB-INF\\resources\\trisim_files";
- String callFlowBusinessYml = "call_flow_hc-origination-termination-to-volteue-3.3.16-Override.yml";
-
- ElementLinkService mapper = new ElementLinkService();
-
- // System.out.print(mapper.createLinkFile(filePath, networkToscaYml,
- // networkToscaUeYml, networkLayoutYml, callFlowBusinessYml,"Step_1"));
- System.out.print(mapper.createLinkFileAdditional(filePath, callFlowBusinessYml, "Step_2"));
- }
-
- @SuppressWarnings("unchecked")
- protected String createLinkFile(String resourceFilePath, String callFLowBsFileName, String callFlowStep)
- throws Exception {
-
- Map<String, Object> callFlowBs = YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName);
-
- List<Map<String, Object>> callSteps = (List<Map<String, Object>>) callFlowBs.get("callSequenceSteps");
- String callFlowName = (String) callFlowBs.get("shortName");
- return addLinks(resourceFilePath, callFlowName, callSteps, callFlowStep);
-
- }
-
- @SuppressWarnings("unchecked")
- protected String createLinkFileAdditional(String resourceFilePath, String callFLowBsFileName, String callFlowStep)
- throws Exception {
-
- // Map<String, Object> callFlowBs =
- // YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName);
-
- // return YamlUtils.returnYaml(callFlowBs);
-
- Map<String, Object> callFlowBs;
-
- try {
- callFlowBs = YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName);
-
- List<Map<String, Object>> callSteps = (List<Map<String, Object>>) callFlowBs.get("callSequenceSteps");
- String callFlowName = (String) callFlowBs.get("shortName");
- return addLinksAdditional(resourceFilePath, callFlowName, callSteps, callFlowStep);
-
- } catch (Exception e) {
-
- return "";
- }
-
- }
-
- @SuppressWarnings("unchecked")
- protected String addLinks(String filePath, String callFlowName, List<Map<String, Object>> callSteps,
- String callFlowStep) throws IOException {
-
- Map<String, List<String>> checkDuplicateMap = new HashMap<String, List<String>>();
-
- for (Map<String, Object> callStep : callSteps) {
-
- if (((String) callStep.get("name")).split(":")[0].trim().replace(" ", "_").equals(callFlowStep)) {
-
- // String callFlowStepName = callFlowName + "_" +
- // ((String)callStep.get("name")).split("-")[0].trim().replace("
- // ", "_")+".yml";
-
- List<Map<String, Object>> links = new ArrayList<Map<String, Object>>();
-
- List<Map<String, Object>> subSteps = (List<Map<String, Object>>) callStep.get("subSteps");
-
- for (Map<String, Object> subStep : subSteps) {
- Map<String, Object> link = new HashMap<String, Object>();
-
- String source = (String) subStep.get("source_tosca_id");
- String destination = (String) subStep.get("destination_tosca_id");
-
- if ((checkDuplicateMap.get(source) == null || checkDuplicateMap.get(source).isEmpty()
- || !checkDuplicateMap.get(source).contains(destination)) && !source.equals(destination)) {
- if (checkDuplicateMap.get(destination) == null) {
- List<String> toscaList = new ArrayList<String>();
- checkDuplicateMap.put(destination, toscaList);
- }
-
- if (checkDuplicateMap.get(source) == null) {
- List<String> toscaList = new ArrayList<String>();
- checkDuplicateMap.put(source, toscaList);
- }
-
- List<String> toscaSourceList = checkDuplicateMap.get(destination);
- toscaSourceList.add(source);
-
- List<String> toscaDestinationList = checkDuplicateMap.get(source);
- toscaDestinationList.add(destination);
-
- link.put("s", source);
- link.put("d", destination);
- links.add(link);
-
- /*
- * may be needed in future but nnot currently
- *
- * if((String) subStep.get("link_visibility")!=null){
- * if(((String)
- * subStep.get("link_visibility")).equals("No")){
- *
- * } }else{
- *
- * links.add(link); }
- */
-
- }
-
- }
-
- Map<String, Object> callFlowUI = new HashMap<String, Object>();
- callFlowUI.put("linkList", links);
-
- return YamlUtils.returnYaml(callFlowUI);
-
- // YamlUtils.writeYamlFile(filePath, callFlowStepName,
- // callFlowUI);
- }
-
- }
- return "";
- }
-
- protected String addLinksAdditional(String filePath, String callFlowName, List<Map<String, Object>> callSteps,
- String callFlowStep) throws IOException {
-
- for (Map<String, Object> callStep : callSteps) {
-
- if (((String) callStep.get("name")).split(":")[0].trim().replace(" ", "_").equals(callFlowStep)) {
-
- // String callFlowStepName = callFlowName + "_" +
- // ((String)callStep.get("name")).split("-")[0].trim().replace("
- // ", "_")+".yml";
-
- Map<String, Object> callFlowUI = new HashMap<String, Object>();
- try {
- List<Map<String, Object>> links = addLinkVertices(callStep);
- callFlowUI.put("linkList", links);
- } catch (Exception e) {
- }
- try {
- List<String> activeIds = addActiveNodes(callStep);
- callFlowUI.put("activeIds", activeIds);
- } catch (Exception e) {
- }
- try {
- List<Map<String, Object>> disconnectLinks = addDisconnectLinks(callStep);
- callFlowUI.put("disconnectLinks", disconnectLinks);
- } catch (Exception e) {
- }
-
- return YamlUtils.returnYaml(callFlowUI);
- }
- }
-
- return "";
- }
-
- @SuppressWarnings("unchecked")
- List<String> addActiveNodes(Map<String, Object> callStep) {
- List<String> activeIds = (List<String>) callStep.get("activeIds");
- return activeIds;
- }
-
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> addDisconnectLinks(Map<String, Object> callStep) {
- List<Map<String, Object>> disconnectLinks = (List<Map<String, Object>>) callStep.get("disconnectLinks");
- return disconnectLinks;
- }
-
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> addLinkVertices(Map<String, Object> callStep) {
- List<Map<String, Object>> links = new ArrayList<Map<String, Object>>();
-
- List<Map<String, Object>> vertices = (List<Map<String, Object>>) callStep.get("vertices");
-
- for (int i = 0; i < vertices.size() - 1; i++) {
- Map<String, Object> vertex = (Map<String, Object>) vertices.get(i);
- Map<String, Object> vertexNext = (Map<String, Object>) vertices.get(i + 1);
-
- Integer sourceX = (Integer) vertex.get("x");
- Integer sourceY = (Integer) vertex.get("y");
- String sourceD = (String) vertex.get("D");
- String sourceL = (vertex.get("L") != null) ? (String) vertex.get("L") : "-";
-
- if (sourceX == -999) // there is a break in the linkage
- continue;
-
- Integer destinationX = (Integer) vertexNext.get("x");
- Integer destinationY = (Integer) vertexNext.get("y");
- String destinationD = (String) vertexNext.get("D");
-
- if (destinationX == -999) // there is a break in the linkage
- continue;
-
- Map<String, Object> link = new HashMap<String, Object>();
-
- link.put("s", sourceX + "," + sourceY + "," + sourceD + "," + sourceL);
- link.put("d", destinationX + "," + destinationY + "," + destinationD);
- links.add(link);
- }
- return links;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.apache.commons.lang.StringUtils;
-import org.openecomp.portalsdk.core.domain.support.Container;
-import org.openecomp.portalsdk.core.domain.support.Domain;
-import org.openecomp.portalsdk.core.domain.support.Element;
-import org.openecomp.portalsdk.core.domain.support.ElementDetails;
-import org.openecomp.portalsdk.core.domain.support.Layout;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.util.YamlUtils;
-import org.yaml.snakeyaml.Yaml;
-import org.yaml.snakeyaml.nodes.Tag;
-import org.yaml.snakeyaml.representer.Representer;
-
-public class ElementMapService {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ElementMapService.class);
-
- /**
- *
- * @param contextRealPath
- * @param layout
- * @return
- * @throws Exception
- */
- private String convertToYAML(String contextRealPath, Layout layout) throws Exception {
-
- // Used to build image file relative URLs
- final String iconRelPath = SystemProperties.getProperty("element_map_icon_path"); // "static/img/map/icons/";
-
- Map<String, Domain> resultAICDomain = layout.domainRowCol;
- Map<String, List<Domain>> domainMap = new HashMap<String, List<Domain>>();
- List<Domain> domainList = new ArrayList<Domain>();
- for (Domain d : resultAICDomain.values()) {
- d.setWidth(10 * d.computeSize().getWidth());
- d.setHeight(10 * d.computeSize().getHeight());
- d.setLeft(10 * d.getP().getX());
- d.setTop(10 * d.getP().getY());
-
- List<Container> containerList = new ArrayList<Container>();
- for (Container c : d.getContainerRowCol().values()) {
- c.setWidth(10 * c.computeSize().getWidth());
- c.setHeight(10 * c.computeSize().getHeight());
- c.setLeft(10 * c.getP().getX());
- c.setTop(10 * c.getP().getY());
- Element ue = (Element) c.getElementRowCol().values().toArray()[0];
- if (ue.getName().equals("ue1") || ue.getName().equals("ue2") || ue.getName().equals("ue3")
- || ue.getName().equals("ue4") || ue.getName().equals("ue5") || ue.getName().equals("ue6")) {
- c.setVisibilityType("invisible");
- }
-
- if (c.getContainerRowCol() != null) {
- List<Container> innerContainerList = new ArrayList<Container>();
- for (Container innerC : c.getContainerRowCol().values()) {
- innerC.setName(innerC.getName());
- innerC.setWidth(10 * innerC.computeSize().getWidth());
- innerC.setHeight(10 * innerC.computeSize().getHeight());
- innerC.setLeft(10 * innerC.getP().getX());
- innerC.setTop(10 * innerC.getP().getY());
-
- if (innerC.getElementRowCol() != null) {
- List<Element> innerContainerEList = new ArrayList<Element>();
- for (Element ele : innerC.getElementRowCol().values()) {
- // ele.setName(ele.getName());
- ele.setWidth(10 * ele.computeSize().getWidth());
- ele.setHeight(10 * ele.computeSize().getHeight());
- ele.setLeft(10 * ele.getP().getX());
- ele.setTop(10 * ele.getP().getY() - 10);
- ele.setImgFileName(iconRelPath + "/" + ele.getImgFileName());
- if (ele.getBorderType().equals("V"))
- ele.setBorderType("dashed");
- else
- ele.setBorderType("solid");
- innerContainerEList.add(ele);
- }
- innerC.setElementList(innerContainerEList);
- }
- innerContainerList.add(innerC);
- }
- c.setInnerCList(innerContainerList);
- }
-
- if (c.getElementRowCol() != null) {
- List<Element> elementList = new ArrayList<Element>();
- for (Element e : c.getElementRowCol().values()) {
- // e.setName(e.getName());
- e.setWidth(10 * e.computeSize().getWidth());
- e.setHeight(10 * e.computeSize().getHeight());
- e.setLeft(10 * e.getP().getX());
- e.setTop(10 * e.getP().getY() - 10);
- e.setImgFileName(iconRelPath + "/" + e.getImgFileName());
-
- if (e.getBorderType().equals("V"))
- e.setBorderType("dashed");
- else
- e.setBorderType("solid");
-
- if (e.getName().equals("ue1") || e.getName().equals("ue2") || e.getName().equals("ue3")
- || e.getName().equals("ue4") || e.getName().equals("ue5") || e.getName().equals("ue6"))
- e.setBgColor("white");
- elementList.add(e);
- }
- c.setElementList(elementList);
- }
- containerList.add(c);
- }
- d.setContainerList(containerList);
- domainList.add(d);
-
- }
- domainMap.put("domainList", domainList);
-
- List<Domain> collapsedDomains = new ArrayList<Domain>();
-
- // nline
- for (Domain collapsed : layout.getCollapsedDomainsNewList()) {
- collapsed.setWidth(10 * collapsed.computeSize().getWidth());
- collapsed.setHeight(10 * collapsed.computeSize().getHeight());
- collapsed.setLeft(10 * collapsed.getP().getX());
- collapsed.setTop(10 * collapsed.getP().getY());
- // nline
- collapsed.setNewXafterColl(10 * collapsed.getNewXafterColl());
- collapsed.setYafterColl(10 * collapsed.getYafterColl());
- collapsedDomains.add(collapsed);
- }
-
- domainMap.put("collapsedDomainList", collapsedDomains);
-
- Representer representer = new Representer();
- representer.addClassTag(Domain.class, Tag.MAP);
-
- Yaml yaml = new Yaml(representer);
- String output = yaml.dump(domainMap);
-
- return output;
-
- }
-
- private static HashMap<String, Object> toscaElementsMap = new HashMap<String, Object>();
- private static HashMap<String, Element> elementMap = new HashMap<String, Element>();
- private static HashMap<String, Element> miscElementMap = new HashMap<String, Element>();
- private static HashMap<String, Container> outercontainers = new HashMap<String, Container>();
- private static HashMap<String, Container> innercontainers = new HashMap<String, Container>();
- private static HashMap<String, Domain> domainMap = new HashMap<String, Domain>();
-
- private static String filePath = SystemProperties.getProperty("element_map_file_path");
- private static String networkToscaYml = null;// "NetworkMap_topology_composition.yml";
- private static String networkLayoutYml = null;// "network_map_layout.yml";
-
- /**
- * Builds renderable model of elements in the network map. Parses YAML files
- * with metadata and builds input for JoinJS to render in the browser as
- * SVG.
- *
- * @param args
- * arg 0 - collapsedDomains; arg 1 - expandedDomains; arg 2 -
- * context real path; arg 3 - contentFileName; arg 4 -
- * layoutFileName
- * @return Renderable model of elements
- * @throws Exception
- */
- public String buildElementMapYaml(String args[]) throws Exception {
-
- final String yamlDirPath = new File(args[2], filePath).getPath();
- if (args != null && args.length > 4) {
- if (args[3] != null)
- networkToscaYml = args[3] + ".yml";
- if (args[4] != null)
- networkLayoutYml = args[4] + ".yml";
- }
-
- Map<String, Object> toscaYaml = YamlUtils.readYamlFile(yamlDirPath, networkToscaYml);
- Map<String, Object> networkMapLayoutYaml = YamlUtils.readYamlFile(yamlDirPath, networkLayoutYml);
-
- toscaElementsMap = new HashMap<String, Object>();
- elementMap = new HashMap<String, Element>();
- domainMap = new HashMap<String, Domain>();
- outercontainers = new HashMap<String, Container>();
- innercontainers = new HashMap<String, Container>();
- miscElementMap = new HashMap<String, Element>();
-
- if (toscaYaml != null) {
- for (String key : toscaYaml.keySet()) {
- if ("topology_template".equalsIgnoreCase(key) && toscaYaml.get(key) instanceof HashMap) {
- HashMap<String, Object> toscaTopologyDetails = (HashMap<String, Object>) toscaYaml.get(key);
-
- for (String detailsKey : toscaTopologyDetails.keySet()) {
-
- if ("node_templates".equalsIgnoreCase(detailsKey)
- && toscaTopologyDetails.get(detailsKey) instanceof HashMap) {
-
- toscaElementsMap = (HashMap<String, Object>) toscaTopologyDetails.get(detailsKey);
-
- // for (String toscaElementKey :
- // toscaElementsMap.keySet()) {
- //// System.out.println("Element - "+ "key :" +
- //// toscaElementKey);
- // }
-
- }
- }
- }
-
- }
- }
-
- if (networkMapLayoutYaml != null) {
- if (networkMapLayoutYaml.containsKey("toscaNetworkMapElementStyleList")
- && networkMapLayoutYaml.get("toscaNetworkMapElementStyleList") instanceof ArrayList) {
-
- ArrayList<Object> elementlist = (ArrayList<Object>) networkMapLayoutYaml
- .get("toscaNetworkMapElementStyleList");
- String elementName;
- String elementID;
- String imgPath;
- String row;
- String column;
- String mapKey;
- int i = 0;
-
- if (elementlist != null) {
- for (Object eachElement : elementlist) {
- // System.out.println("toscaNetworkMapElementStyleList
- // Container : " +eachElement);
- if (eachElement != null && eachElement instanceof HashMap) {
- HashMap<String, String> elementDetails = (HashMap<String, String>) eachElement;
- if (elementDetails != null) {
- elementName = "NA" + i;
- elementID = "NA" + i;
- imgPath = "NA" + i;
- row = "0";
- column = "0";
- for (String detailsKey : elementDetails.keySet()) {
- if ("tosca_id".equalsIgnoreCase(detailsKey))
- elementName = elementDetails.get(detailsKey).toString();
- if ("id".equalsIgnoreCase(detailsKey)) {
- elementID = String.valueOf(elementDetails.get(detailsKey));
- }
- if ("row".equalsIgnoreCase(detailsKey)) {
- row = String.valueOf(elementDetails.get(detailsKey));
- }
- if ("column".equalsIgnoreCase(detailsKey)) {
- column = String.valueOf(elementDetails.get(detailsKey));
- }
- if ("icon".equalsIgnoreCase(detailsKey))
- imgPath = elementDetails.get(detailsKey).toString();
- }
-
- if (elementMap.containsKey(elementName.concat("/").concat(row).concat(column))) {
- if (elementMap.containsKey(elementName.concat("/").concat(String.valueOf(i))
- .concat(String.valueOf(i)))) {
- mapKey = elementName;
- } else
- mapKey = elementName.concat("/").concat(String.valueOf(i))
- .concat(String.valueOf(i));
-
- } else
- mapKey = elementName.concat("/").concat(row).concat(column);
-
- elementMap.put(mapKey, fetchElementObject(elementID, elementName, imgPath));
- }
- }
- i++;
- }
- }
-
- for (String elementkey : elementMap.keySet()) {
- Element c = (Element) elementMap.get(elementkey);
- // System.out.println("Element - "+ "key :" +elementkey +" -
- // " + "value :" + c.getName());
- }
-
- if (!elementMap.isEmpty()) {
- miscElementMap = new HashMap<String, Element>(elementMap);
- }
- }
-
- if (networkMapLayoutYaml.containsKey("containerStyleList")
- && networkMapLayoutYaml.get("containerStyleList") instanceof ArrayList) {
-
- ArrayList<Object> containerstylelist = (ArrayList<Object>) networkMapLayoutYaml
- .get("containerStyleList");
- String containerName;
- String containerID;
- String domain;
- String row;
- String column;
- String mapKey;
- int i = 0;
-
- if (containerstylelist != null) {
- // Inner Containers
- for (Object eachContainer : containerstylelist) {
- if (eachContainer != null && eachContainer instanceof HashMap) {
- HashMap<String, String> containerDetails = (HashMap<String, String>) eachContainer;
- if (containerDetails != null) {
- containerName = "NA" + i;
- containerID = "NA" + i;
- domain = "NA" + i;
- row = "0";
- column = "0";
-
- for (String detailsKey : containerDetails.keySet()) {
- if ("logical_group_name".equalsIgnoreCase(detailsKey))
- containerName = containerDetails.get(detailsKey).toString();
- if ("id".equalsIgnoreCase(detailsKey)) {
- containerID = String.valueOf(containerDetails.get(detailsKey));
- }
- if ("domain".equalsIgnoreCase(detailsKey)) {
- domain = containerDetails.get(detailsKey).toString();
- }
- if ("row".equalsIgnoreCase(detailsKey)) {
- row = String.valueOf(containerDetails.get(detailsKey));
- }
- if ("column".equalsIgnoreCase(detailsKey)) {
- column = String.valueOf(containerDetails.get(detailsKey));
- }
- }
- if (containerName.contains("/")) {
-
- if (innercontainers.containsKey(
- (domain + ":" + containerName).concat("/").concat(row).concat(column))) {
- if (elementMap.containsKey((domain + ":" + containerName).concat("/")
- .concat(String.valueOf(i)).concat(String.valueOf(i)))) {
- mapKey = (domain + ":" + containerName);
- } else
- mapKey = (domain + ":" + containerName).concat("/")
- .concat(String.valueOf(i)).concat(String.valueOf(i));
-
- } else
- mapKey = (domain + ":" + containerName).concat("/").concat(row).concat(column);
-
- innercontainers.put(mapKey,
- fetchContainerObject(containerID,
- containerName.substring(containerName.indexOf("/") + 1), true,
- containerName, domain));
- }
- }
- }
- i++;
- }
-
- // OuterContainers
- i = 0;
- for (Object eachContainer : containerstylelist) {
- if (eachContainer != null && eachContainer instanceof HashMap) {
- HashMap<String, String> containerDetails = (HashMap<String, String>) eachContainer;
- if (containerDetails != null) {
- containerName = "NA" + i;
- containerID = "NA" + i;
- domain = "NA" + i;
- row = "0";
- column = "0";
-
- for (String detailsKey : containerDetails.keySet()) {
- if ("logical_group_name".equalsIgnoreCase(detailsKey))
- containerName = containerDetails.get(detailsKey).toString();
- if ("id".equalsIgnoreCase(detailsKey)) {
- containerID = String.valueOf(containerDetails.get(detailsKey));
- }
- if ("domain".equalsIgnoreCase(detailsKey)) {
- domain = containerDetails.get(detailsKey).toString();
- }
- if ("row".equalsIgnoreCase(detailsKey)) {
- row = String.valueOf(containerDetails.get(detailsKey));
- }
- if ("column".equalsIgnoreCase(detailsKey)) {
- column = String.valueOf(containerDetails.get(detailsKey));
- }
- }
- if (!containerName.contains("/")) {
- if (outercontainers.containsKey(
- (domain + ":" + containerName).concat("/").concat(row).concat(column))) {
- if (outercontainers.containsKey((domain + ":" + containerName).concat("/")
- .concat(String.valueOf(i)).concat(String.valueOf(i)))) {
- mapKey = (domain + ":" + containerName);
- } else
- mapKey = (domain + ":" + containerName).concat("/")
- .concat(String.valueOf(i)).concat(String.valueOf(i));
-
- } else
- mapKey = (domain + ":" + containerName).concat("/").concat(row).concat(column);
- outercontainers.put(mapKey, fetchContainerObject(containerID, containerName, false,
- containerName, domain));
- }
- // else innercontainers.put(domain +":"+
- // containerName,
- // fetchContainerObject(containerID,containerName.substring(containerName.indexOf("/")+1),false,containerName,domain));
-
- }
- }
- i++;
- }
- }
-
- for (String innerContainerkey : innercontainers.keySet()) {
- Container c = (Container) innercontainers.get(innerContainerkey);
- }
-
- for (String outerContainerkey : outercontainers.keySet()) {
- Container c = (Container) outercontainers.get(outerContainerkey);
- }
-
- }
-
- if (networkMapLayoutYaml.containsKey("domainList")
- && networkMapLayoutYaml.get("domainList") instanceof ArrayList) {
-
- ArrayList<Object> domainlist = (ArrayList<Object>) networkMapLayoutYaml.get("domainList");
- String domainName;
- String domainID;
- String row;
- String column;
- String mapKey;
- int i = 0;
-
- if (domainlist != null) {
-
- HashMap<String, String> domainStagingMap = new HashMap<String, String>();
- for (Object eachDomain : domainlist) {
- // System.out.println("domainlist Container : "
- // +eachDomain);
- if (eachDomain != null && eachDomain instanceof HashMap) {
- HashMap<String, String> domainDetails = (HashMap<String, String>) eachDomain;
- if (domainDetails != null) {
- domainName = "NA" + i;
- domainID = "NA" + i;
- row = "0";
- column = "0";
- for (String detailsKey : domainDetails.keySet()) {
- if ("name".equalsIgnoreCase(detailsKey))
- domainName = domainDetails.get(detailsKey).toString();
- if ("id".equalsIgnoreCase(detailsKey)) {
- domainID = String.valueOf(domainDetails.get(detailsKey));
- }
- if ("row".equalsIgnoreCase(detailsKey)) {
- row = String.valueOf(domainDetails.get(detailsKey));
- }
- if ("column".equalsIgnoreCase(detailsKey)) {
- column = String.valueOf(domainDetails.get(detailsKey));
- }
- }
-
- if (domainStagingMap.containsKey(row.concat(column))) {
- mapKey = domainName;
- } else
- mapKey = row.concat(column);
-
- domainStagingMap.put(mapKey, domainID + "%" + domainName);
- }
- }
- i++;
- }
-
- if (domainStagingMap != null && !domainStagingMap.isEmpty()) {
- for (String domainsKey : new TreeSet<String>(domainStagingMap.keySet())) {
- String value = domainStagingMap.get(domainsKey);
- if (value.contains("%")) {
- domainMap.put(domainsKey, fetchDomainObject(value.substring(0, value.indexOf("%")),
- value.substring(value.indexOf("%") + 1)));
- }
- }
- }
- }
-
- // for (String domainkey : domainMap.keySet()) {
- // Domain c = (Domain) domainMap.get(domainkey);
- // System.out.println("Domain - "+ "key :" +domainkey +" - "
- // + "value :" + c.getName());
- // }
- }
-
- }
-
- Layout dynamicLayout = new Layout(domainMap, 2, 10, 1, 5);
- dynamicLayout.computeDomainPositionsModified();
-
- /*
- * Map<String, Domain> resultAICDomain2 = dynamicLayout.domainRowCol;
- * for (String key : resultAICDomain2.keySet()) { if
- * (resultAICDomain2.get(key).getP() != null) {
- * System.out.println(resultAICDomain2.get(key).name+" "+"x:"+
- * resultAICDomain2.get(key).getP().getX()+","+"y:"+
- * resultAICDomain2.get(key).getP().getY()+","+"width:"+
- * resultAICDomain2.get(key).computeSize().getWidth()
- * +","+"height:"+resultAICDomain2.get(key).computeSize(). getHeight());
- *
- * } }
- */
-
- ElementMapService cm2 = new ElementMapService();
- try {
-
- if (args != null && args.length > 0) {
-
- if (args[0] != null) {
- String collapsedDomains[] = args[0].split(",");
- for (String collapsedDomain : collapsedDomains)
- // dynamicLayout.collapseDomainModified(collapsedDomain);
- dynamicLayout.collapseDomainNew(collapsedDomain);
- }
-
- if (args[1] != null) {
- String expandedDomains[] = args[1].split(",");
- for (String expandedDomain : expandedDomains)
- // dynamicLayout.uncollapseDomainNew(expandedDomain);
- dynamicLayout.uncollapseDomainNew1(expandedDomain);
- }
-
- return cm2.convertToYAML(args[2], dynamicLayout);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "buildElementMapYaml failed", e);
- }
-
- return "";
- }
-
- private static int computeRows(Set<String> keys) {
- int i = 0;
- if (keys != null && !keys.isEmpty()) {
- for (String s : keys) {
- String r = s.substring(0, 1);
- if (StringUtils.isNumeric(r)) {
- int j = Integer.parseInt(r);
- if (i <= j) {
- i = j;
- }
-
- }
- }
-
- return i + 1;
- }
-
- return 1;
- }
-
- private static int computeColumns(Set<String> keys) {
- int i = 0;
- if (keys != null && !keys.isEmpty()) {
- for (String s : keys) {
- String r = s.substring(1, 2);
- if (StringUtils.isNumeric(r)) {
- int j = Integer.parseInt(r);
- if (i <= j) {
- i = j;
- }
-
- }
- }
-
- return i + 1;
- }
-
- return 1;
- }
-
- private static Container fetchContainerObject(String id, String name, boolean isInner, String logicalGroupName,
- String domain) {
- Map<String, Element> containerElementsMap = new HashMap<String, Element>();
-
- containerElementsMap = fetchElementsMapForContainer(name, isInner, logicalGroupName, domain);
- int rows = 1;
- int columns = 1;
-
- if (isInner) {
-
- if (containerElementsMap != null && !containerElementsMap.isEmpty()) {
- rows = computeRows(containerElementsMap.keySet());
- columns = computeColumns(containerElementsMap.keySet());
- }
-
- Container thisContainer = new Container(id, name, rows, columns, 1, 4, 8, 12, 1, 2);
- thisContainer.setElements(containerElementsMap);
- // thisContainer.setVisibilityType("");
-
- return thisContainer;
- } else {
- Map<String, Container> innerContainersMap = fetchInnerContainersMapForOuter(name, isInner, logicalGroupName,
- domain);
-
- if (innerContainersMap != null && !innerContainersMap.isEmpty()) {
- if (containerElementsMap != null && !containerElementsMap.isEmpty()) {
- Set<String> keys = new HashSet<String>(innerContainersMap.keySet());
- keys.addAll(containerElementsMap.keySet());
- rows = computeRows(keys);
- columns = computeColumns(keys);
- } else {
- rows = computeRows(innerContainersMap.keySet());
- columns = computeColumns(innerContainersMap.keySet());
- }
- } else if (containerElementsMap != null && !containerElementsMap.isEmpty()) {
- rows = computeRows(containerElementsMap.keySet());
- columns = computeColumns(containerElementsMap.keySet());
- }
-
- Container thisContainer = new Container(id, name, rows, columns, 2, 6, 2, 5, 0, 0);
- thisContainer.setElements(containerElementsMap);
- thisContainer.setInnerContainer(innerContainersMap);
-
- if (containerElementsMap != null && !containerElementsMap.isEmpty()) {
- for (Element thisElement : containerElementsMap.values()) {
- if (thisElement.getId() != null
- ) {
- thisContainer.setVisibilityType("invisible");
- }
- }
- }
- return thisContainer;
- }
-
- }
-
- private static Domain fetchDomainObject(String id, String name) {
- HashMap<String, Container> domainContainersMap = fetchContainersForDomain(name);
-
- int rows = 1;
- int columns = 1;
- if (domainContainersMap != null && !domainContainersMap.isEmpty()) {
- rows = computeRows(domainContainersMap.keySet());
- columns = computeColumns(domainContainersMap.keySet());
- }
-
- double domainWidth = 11;
- Domain thisDomain;
-
- if (domainMap != null && !domainMap.isEmpty()) {
- int domainsCountSoFar = domainMap.size();
- switch (domainsCountSoFar) {
- case 1: {
- domainWidth = 12.1;
- break;
- }
- case 2: {
- domainWidth = 13.3;
- break;
- }
- case 3: {
- domainWidth = 14.5;
- break;
- }
- case 4: {
- domainWidth = 15.6;
- break;
- }
- default: {
- domainWidth = 11;
- break;
- }
- }
-
- for (String domainsKey : new TreeSet<String>(domainMap.keySet())) {
- Domain eachDomain = domainMap.get(domainsKey);
- domainWidth += eachDomain.computeSize().getWidth();
- }
- thisDomain = new Domain(id, name, 2, 2, domainWidth, 10, 3, rows, columns);
- } else {
-
- thisDomain = new Domain(id, name, 2, 1, 11, 10, 3, rows, columns);
- }
-
- // Domain thisDomain = new Domain(id, name, 2, 1, leftPosition, 10, 3,
- // rows, columns);
- thisDomain.setContainers(domainContainersMap);
-
- thisDomain.computeConatinerPositions();
- if (domainContainersMap != null && !domainContainersMap.isEmpty()) {
- for (Container thisContainer : domainContainersMap.values()) {
- thisContainer.computeSize();
- thisContainer.computeElementPositions();
- Map<String, Element> resultElementMap = thisContainer.elementRowCol;
- for (String key : resultElementMap.keySet()) {
- if (resultElementMap.get(key) == null || resultElementMap.get(key).getP() == null) {
- // System.out.println("culprit " +key);
- }
- /*
- * System.out.println(resultElementMap.get(key).name+" "
- * +"x:"+resultElementMap.get(key).getP().getX()+","+"y:"+
- * resultElementMap.get(key).getP().getY()+","+"width:"+
- * resultElementMap.get(key).computeSize().getWidth()
- * +","+"height:"+resultElementMap.get(key).computeSize().
- * getHeight());
- */
-
- }
-
- HashMap<String, Container> innerContainersMap = (HashMap<String, Container>) thisContainer
- .getContainerRowCol();
- if (innerContainersMap != null && !innerContainersMap.isEmpty()) {
- for (Container thisInnerContainer : innerContainersMap.values()) {
- // thisInnerContainer.computeSize();
- thisInnerContainer.computeElementPositions();
- /*
- * Map<String,Element> resultInnerElementMap =
- * thisContainer.elementRowCol; for (String key :
- * resultElementMap.keySet()) { //
- * System.out.println(resultElementMap.get(key).name+" "
- * +"x:"+resultElementMap.get(key).getP().getX()+","+
- * "y:"+
- * resultElementMap.get(key).getP().getY()+","+"width:"+
- * resultElementMap.get(key).computeSize().getWidth()
- * +","+"height:"+resultElementMap.get(key).computeSize(
- * ).getHeight());
- *
- * }
- */
- }
- }
- }
- }
-
- return thisDomain;
- }
-
- private static HashMap<String, Container> fetchContainersForDomain(String domain) {
- HashMap<String, Container> domainContainersMap = new HashMap<String, Container>();
-
- domainContainersMap = fetchFromOuterContainers(domain);
-
- return domainContainersMap;
-
- }
-
- private static Element fetchElementObject(String id, String name, String imgPath) {
- String bgColor = "bgColor";
- String logical_group;
- String display_longname;
- String display_shortname;
- String description;
- String primary_function;
- String key_interfaces;
- String location;
- String vendor;
- String vendor_shortname;
- String enclosingContainer;
- String borderType;
- String network_function;
-
- if (toscaElementsMap.containsKey(name)) {
-
- if (toscaElementsMap.get(name) != null && toscaElementsMap.get(name) instanceof HashMap) {
- HashMap<String, Object> toscaElementDetails = (HashMap<String, Object>) toscaElementsMap.get(name);
-
- for (String detailsKey : toscaElementDetails.keySet()) {
- if ("properties".equalsIgnoreCase(detailsKey)
- && toscaElementDetails.get(detailsKey) instanceof HashMap) {
- HashMap<String, String> elementDetails = (HashMap<String, String>) toscaElementDetails
- .get(detailsKey);
-
- if (elementDetails != null) {
- logical_group = elementDetails.get("logical_group") == null ? ""
- : elementDetails.get("logical_group").toString();
- display_longname = elementDetails.get("display_longname") == null ? ""
- : elementDetails.get("display_longname").toString();
- display_shortname = elementDetails.get("display_shortname") == null ? ""
- : elementDetails.get("display_shortname").toString();
- description = elementDetails.get("description") == null ? ""
- : elementDetails.get("description").toString();
- primary_function = elementDetails.get("primary_function") == null ? ""
- : elementDetails.get("primary_function").toString();
- key_interfaces = elementDetails.get("key_interfaces") == null ? ""
- : elementDetails.get("key_interfaces").toString();
- location = elementDetails.get("location") == null ? ""
- : elementDetails.get("location").toString();
- vendor = elementDetails.get("vendor") == null ? ""
- : elementDetails.get("vendor").toString();
- vendor_shortname = elementDetails.get("vendor_shortname") == null ? ""
- : elementDetails.get("vendor_shortname").toString();
- enclosingContainer = logical_group.replace("/", "-");
- network_function = elementDetails.get("network_function");
- borderType = elementDetails.get("network_function") == null ? "P"
- : elementDetails.get("network_function").toString().toUpperCase();
- bgColor = elementDetails.get("background_color") == null ? "bgColor"
- : elementDetails.get("background_color").toString();
-
- ElementDetails details = new ElementDetails(logical_group, display_longname, description,
- primary_function, network_function, key_interfaces, location, vendor,
- vendor_shortname, enclosingContainer);
-
- return new Element(name, display_shortname, imgPath, bgColor, borderType, details);
- }
-
- }
- }
-
- }
-
- // Element(id, name, imgPath, bgColor, logical_group,
- // display_longname,
- // description, primary_function, key_interfaces, location, vendor,
- // vendor_shortname);
- } else {
- return new Element(id, name);
- }
-
- return new Element(id, name);
- }
-
- private static String fetchDomainNameOfElement(String name) {
- if (toscaElementsMap.containsKey(name)) {
-
- if (toscaElementsMap.get(name) != null && toscaElementsMap.get(name) instanceof HashMap) {
- HashMap<String, Object> toscaElementDetails = (HashMap<String, Object>) toscaElementsMap.get(name);
-
- for (String detailsKey : toscaElementDetails.keySet()) {
- if ("properties".equalsIgnoreCase(detailsKey)
- && toscaElementDetails.get(detailsKey) instanceof HashMap) {
- HashMap<String, String> elementDetails = (HashMap<String, String>) toscaElementDetails
- .get(detailsKey);
-
- if (elementDetails != null) {
- return elementDetails.get("domain") == null ? "" : elementDetails.get("domain").toString();
- }
-
- }
- }
-
- }
-
- } else {
- return "";
- }
-
- return "";
- }
-
- private static HashMap<String, Container> fetchInnerContainersMapForOuter(String name, boolean isInner,
- String logicalGroupName, String domain) {
- return fetchInnerContainersMap(name, logicalGroupName, domain);
- }
-
- private static HashMap<String, Element> fetchElementsMapForContainer(String name, boolean isInner,
- String logicalGroupName, String domain) {
- return fetchElementsMap(logicalGroupName, domain);
- }
-
- private static HashMap<String, Container> fetchInnerContainersMap(String name, String logicalGroupName,
- String domain) {
- HashMap<String, Container> containersMap = new HashMap<String, Container>();
- String rowColumnKey = "";
- int count = 0;
-
- if (innercontainers != null && !innercontainers.isEmpty()) {
- for (String key : innercontainers.keySet()) {
-
- Container eachContainer = innercontainers.get(key);
-
- if (key.toUpperCase().contains((domain + ":" + name).toUpperCase())) {
- if (key.contains("/")) {
- rowColumnKey = key.substring(key.lastIndexOf("/") + 1);
- }
-
- if (rowColumnKey.isEmpty() || containersMap.containsKey(rowColumnKey)) {
- count = 0;
- while (count <= 9) {
- if (containersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) {
- count++;
- } else {
- rowColumnKey = String.valueOf(count).concat(String.valueOf(count));
- break;
- }
- }
-
- }
-
- containersMap.put(rowColumnKey, eachContainer);
- }
-
- }
- }
- return containersMap.isEmpty() ? null : containersMap;
-
- }
-
- private static HashMap<String, Container> fetchFromOuterContainers(String domain) {
- HashMap<String, Container> thisContainersMap = new HashMap<String, Container>();
- String rowColumnKey = "";
- int count = 0;
-
- if (outercontainers != null && !outercontainers.isEmpty()) {
- for (String key : outercontainers.keySet()) {
- Container eachContainer = outercontainers.get(key);
-
- if (key.toUpperCase().contains((domain + ":").toUpperCase())) {
- if (key.contains("/")) {
- rowColumnKey = key.substring(key.lastIndexOf("/") + 1);
- }
-
- if (rowColumnKey.isEmpty() || thisContainersMap.containsKey(rowColumnKey)) {
- count = 0;
- while (count <= 9) {
- if (thisContainersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) {
- count++;
- } else {
- rowColumnKey = String.valueOf(count).concat(String.valueOf(count));
- break;
- }
- }
-
- }
-
- thisContainersMap.put(rowColumnKey, eachContainer);
- }
- }
-
- }
-
- // Misc Elements Containers
-
- if (miscElementMap != null && !miscElementMap.isEmpty()) {
- for (String key : miscElementMap.keySet()) {
- Element eachElement = miscElementMap.get(key);
- String elementName = eachElement.getName();
- String domainName = fetchDomainNameOfElement(elementName);
-
- if (domain.equalsIgnoreCase(domainName)) {
- Container eachContainer = new Container(domainName + ":" + elementName, elementName, 1, 1, 3, 6, 2,
- 5, 0, 0);
- count = 0;
- while (count <= 9) {
- if (thisContainersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) {
- count++;
- } else {
- rowColumnKey = String.valueOf(count).concat(String.valueOf(count));
- break;
- }
- }
-
- thisContainersMap.put(rowColumnKey, eachContainer);
- }
-
- }
-
- }
-
- return thisContainersMap.isEmpty() ? null : thisContainersMap;
- }
-
- private static HashMap<String, Container> addOuterContainersForMiscElements(String domain) {
- HashMap<String, Container> containerElementsMap = new HashMap<String, Container>();
- if (miscElementMap != null && !miscElementMap.isEmpty()) {
- for (String key : miscElementMap.keySet()) {
- Element eachElement = miscElementMap.get(key);
- String elementName = eachElement.getName();
- String domainName = fetchDomainNameOfElement(elementName);
-
- if (domain.equalsIgnoreCase(domainName)) {
- Container newContainer = new Container(domainName + ":" + elementName, elementName, 1, 1, 3, 6, 2,
- 5, 0, 0);
- containerElementsMap.put(domainName + ":" + elementName, newContainer);
- }
-
- }
-
- }
- return containerElementsMap.isEmpty() ? null : containerElementsMap;
- }
-
- private static HashMap<String, Element> fetchElementsMap(String logicalGroupName, String domain) {
- HashMap<String, Element> innerElementMap = new HashMap<String, Element>();
- String rowColumnKey = "";
- int count = 0;
-
- if (elementMap != null && !elementMap.isEmpty()) {
- for (String key : elementMap.keySet()) {
- Element eachElement = elementMap.get(key);
-
- String elementName = eachElement.getId();
- String elementLogicalGroup = eachElement.details == null ? "" : eachElement.details.logical_group;
- if (elementLogicalGroup.equalsIgnoreCase(logicalGroupName)
- && domain.equalsIgnoreCase(fetchDomainNameOfElement(elementName))) {
- if (key.contains("/")) {
- rowColumnKey = key.substring(key.indexOf("/") + 1);
- }
-
- if (rowColumnKey.isEmpty() || innerElementMap.containsKey(rowColumnKey)) {
- count = 0;
- while (count <= 9) {
- if (innerElementMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) {
- count++;
- } else {
- rowColumnKey = String.valueOf(count).concat(String.valueOf(count));
- break;
- }
- }
-
- }
-
- innerElementMap.put(rowColumnKey, eachElement);
- miscElementMap.remove(key);
- }
-
- }
- }
-
- return innerElementMap.isEmpty() ? null : innerElementMap;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.openecomp.portalsdk.core.domain.Menu;
-import org.openecomp.portalsdk.core.domain.MenuData;
-
-/**
- * Services for Admin to add/edit/delete menu items from FN_MENU
- */
-public interface FnMenuService {
- List<MenuData> getFnMenuItems();
-
- void saveFnMenuData(MenuData domainFnMenu);
-
- void saveFnMenu(Menu domainFnMenu);
-
- void removeMenuItem(MenuData domainFnMenu);
-
- MenuData getMenuItemRow(Long id);
-
- Menu getMenuItem(Long id);
-
- List<Long> getParentId(String label);
-
- @SuppressWarnings("rawtypes")
- List<List> getParentList();
-
- void removeMenuItem(Menu domainFnMenu);
-
- Map<String, List<MenuData>> setMenuDataStructure(List<List<MenuData>> childItemList, List<MenuData> parentList,
- Set<MenuData> menuResult) throws Exception;
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.openecomp.portalsdk.core.domain.Menu;
-import org.openecomp.portalsdk.core.domain.MenuData;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-/**
- * Description: this java class is an implementation of services for Admin to
- * add/edit/delete menu items from FN_MENU
- */
-
-@Service("fnMenuService")
-@Transactional
-public class FnMenuServiceImpl implements FnMenuService {
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @SuppressWarnings("unchecked")
- public List<MenuData> getFnMenuItems() {
- return getDataAccessService().getList(MenuData.class, null, "1", null);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- @Override
- public void saveFnMenuData(MenuData domainFnMenu) {
- getDataAccessService().saveDomainObject(domainFnMenu, null);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<Long> getParentId(String label) {
- Map<String, String> params = new HashMap<String, String>();
- params.put("paramLabel", label);
- return getDataAccessService().executeNamedQuery("IdForLabelList", params, null);
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- public List<List> getParentList() {
- return getDataAccessService().executeNamedQuery("parentList", null, null);
- }
-
- @Override
- public void removeMenuItem(MenuData domainFnMenu) {
- getDataAccessService().deleteDomainObject(domainFnMenu, null);
- }
-
- @Override
- public void removeMenuItem(Menu domainFnMenu) {
- getDataAccessService().deleteDomainObject(domainFnMenu, null);
- }
-
- public MenuData getMenuItemRow(Long id) {
- return (MenuData) getDataAccessService().getDomainObject(MenuData.class, id, null);
- }
-
- @Override
- public Menu getMenuItem(Long id) {
- return (Menu) getDataAccessService().getDomainObject(Menu.class, id, null);
- }
-
- @Override
- public void saveFnMenu(Menu domainFnMenu) {
- getDataAccessService().saveDomainObject(domainFnMenu, null);
- }
-
- @Override
- public Map<String, List<MenuData>> setMenuDataStructure(List<List<MenuData>> childItemList,
- List<MenuData> parentList, Set<MenuData> menuResult) throws Exception {
- for (MenuData menu : menuResult) {
- MenuData parentData = new MenuData();
- parentData.setLabel(menu.getLabel());
- parentData.setAction(menu.getAction());
- parentData.setImageSrc(menu.getImageSrc());
- parentList.add(parentData);
- List<MenuData> tempList = new ArrayList<MenuData>();
- for (Object o : menu.getChildMenus()) {
- MenuData m = (MenuData) o;
- MenuData data = new MenuData();
- data.setLabel(m.getLabel());
- data.setAction(m.getAction());
- data.setImageSrc(m.getImageSrc());
- tempList.add(data);
- }
- childItemList.add(tempList);
- }
- return null;
- }
-
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-
-public interface FunctionalMenuListService {
-
- List<RoleFunction> getFunctionCDList(HttpServletRequest request) throws Exception;
-
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.type.TypeFactory;
-
-public class FunctionalMenuListServiceCentralizedImpl implements FunctionalMenuListService{
-
-private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuListServiceCentralizedImpl.class);
-
- @Autowired
- private RestApiRequestBuilder restApiRequestBuilder;
-
- @SuppressWarnings("unchecked")
- @Override
- public List<RoleFunction> getFunctionCDList(HttpServletRequest request) throws Exception {
- User user = UserUtils.getUserSession(request);
- ObjectMapper mapper = new ObjectMapper();
- List roleFunctionFinalList = new ArrayList<>();
- try {
- String menuList = restApiRequestBuilder.getViaREST("/menuFunctions", true, user.getOrgUserId());
- roleFunctionFinalList = mapper.readValue(menuList,
- TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getFunctionCDList Failed", e);
- throw new Exception(e.getMessage());
- }
- return roleFunctionFinalList;
- }
-
-
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-
-public class FunctionalMenuListServiceImpl implements FunctionalMenuListService{
-
-private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuListServiceImpl.class);
-
- @Autowired
- private DataAccessService dataAccessService;
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<RoleFunction> getFunctionCDList(HttpServletRequest request) throws Exception {
- return getDataAccessService().executeNamedQuery("functionCDlist", null, null);
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import org.openecomp.portalsdk.core.command.support.SearchResult;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-
-public interface LdapService {
-
- // search POST for users based on the criteria selected in the Request
- SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, int pageNo, int dataSize, int userId) throws Exception;
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-import javax.naming.directory.Attribute;
-import javax.naming.directory.Attributes;
-import javax.naming.directory.DirContext;
-import javax.naming.directory.SearchControls;
-
-import org.openecomp.portalsdk.core.command.support.SearchResult;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.support.FusionService;
-import org.openecomp.portalsdk.core.service.support.ServiceLocator;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-@Service("ldapService")
-@Transactional
-public class LdapServiceImpl extends FusionService implements LdapService {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LdapServiceImpl.class);
- @Autowired
- private ServiceLocator serviceLocator;
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3,
- int pageNo, int dataSize, int userId) throws Exception {
-
- // initialize the directory context to access POST
- DirContext dirContext = serviceLocator.getDirContext(SystemProperties.getProperty(SystemProperties.POST_INITIAL_CONTEXT_FACTORY),
- SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL),
- SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL));
-
- SearchResult searchResult = new SearchResult();
-
- try {
-
- String[] postAttributes = {"nickname","givenName","initials","sn","employeeNumber","mail","telephoneNumber",
- "departmentNumber","a1","street","roomNumber","l","st","postalCode","zip4","physicalDeliveryOfficeName","bc",
- "friendlyCountryName","bd","bdname","bu","buname","jtname","mgrid","a2","compcode","compdesc",
- "costcenter","silo","b2"};
-
- SearchControls searchControls = new SearchControls();
- searchControls.setTimeLimit(5000);
- searchControls.setReturningAttributes(postAttributes);
-
- StringBuffer filterClause = new StringBuffer("(&(objectClass=*)");
-
- User user = (User)searchCriteria;
-
- if(Utilities.nvl(user.getFirstName()).length() > 0) {
- filterClause.append("(givenName=").append(user.getFirstName()).append("*)");
- }
- if(Utilities.nvl(user.getLastName()).length() > 0) {
- filterClause.append("(sn=").append(user.getLastName()).append("*)");
- }
- if(Utilities.nvl(user.getHrid()).length() > 0) {
- filterClause.append("(employeeNumber=").append(user.getHrid()).append("*)");
- }
- if(Utilities.nvl(user.getOrgManagerUserId()).length() > 0) {
- filterClause.append("(mgrid=").append(user.getOrgManagerUserId()).append("*)");
- }
- if(Utilities.nvl(user.getOrgCode()).length() > 0) {
- filterClause.append("(departmentNumber=").append(user.getOrgCode()).append("*)");
- }
- if(Utilities.nvl(user.getEmail()).length() > 0) {
- filterClause.append("(mail=").append(user.getEmail()).append("*)");
- }
- if(Utilities.nvl(user.getOrgUserId()).length() > 0) {
- filterClause.append("(a1=").append(user.getOrgUserId()).append("*)");
- }
- filterClause.append("(c3=N)"); // this has been added to filter CP09 entries on the LDAP server that are duplicates of existing individuals
- filterClause.append(")");
-
- List list = new ArrayList();
- if (!filterClause.toString().equals("(&(objectClass=*))")) {
- NamingEnumeration e = dirContext.search(SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL) + "/" +
- SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL),
- filterClause.toString(),
- searchControls);
-
- list = processResults(e);
- }
-
- Collections.sort(list);
-
- searchResult = new SearchResult(list);
- searchResult.setPageNo(pageNo);
- if(dataSize >= 0) {
- searchResult.setDataSize(dataSize);
- }
- else {
- searchResult.setDataSize(list.size());
- } // else
-
- }
- catch(NamingException ne) {
- logger.error(EELFLoggerDelegate.errorLogger,ne.getMessage());
- }
- finally {
- dirContext.close();
- }
-
- return searchResult;
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private ArrayList processResults(NamingEnumeration e) throws NamingException {
- ArrayList results = new ArrayList();
- int count = 0;
-
- while (e.hasMore()) {
- javax.naming.directory.SearchResult searchResult = (javax.naming.directory.SearchResult)e.next();
- results.add(processAttributes(searchResult.getAttributes()));
- count++;
-
- if(count > Integer.parseInt(SystemProperties.getProperty(SystemProperties.POST_MAX_RESULT_SIZE))) {
- break;
- }
-
- }
-
- return results;
- }
-
- @SuppressWarnings("rawtypes")
- private DomainVo processAttributes(Attributes resultAttributes) throws NamingException {
- User user = new User();
-
- try {
- if (resultAttributes == null) {
- // System.out.println("This result has no attributes");
- } else {
- for (NamingEnumeration e = resultAttributes.getAll(); e.hasMore();) { //why the nested loop?
- Attribute attribute = (Attribute)e.next();
- for (NamingEnumeration ie = attribute.getAll(); ie.hasMore();) {
- if (attribute.getID().equalsIgnoreCase("nickname")) {
- user.setFirstName((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("initials")) {
- user.setMiddleInitial((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("sn")) {
- user.setLastName((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("employeeNumber")) {
- user.setHrid((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("mail")) {
- user.setEmail((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("telephoneNumber")) {
- user.setPhone((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("departmentNumber")) {
- user.setOrgCode((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("a1")) {
- user.setOrgUserId((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("street")) {
- user.setAddress1((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("roomNumber")) {
- user.setAddress2((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("l")) {
- user.setCity((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("st")) {
- user.setState((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("postalCode")) {
- user.setZipCode((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("zip4")) {
- user.setZipCodeSuffix((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("physicalDeliveryOfficeName")) {
- user.setLocationClli((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("bc")) {
- user.setBusinessCountryCode((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("friendlyCountryName")) {
- user.setBusinessCountryName((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("bd")) {
- user.setDepartment((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("bdname")) {
- user.setDepartmentName((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("jtname")) {
- user.setJobTitle((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("mgrid")) {
- user.setOrgManagerUserId((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("a2")) {
- user.setCommandChain((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("compcode")) {
- user.setCompanyCode((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("compdesc")) {
- user.setCompany((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("bu")) {
- user.setBusinessUnit((String)ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("buname")) {
- user.setBusinessUnitName((String)ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("silo")) {
- user.setSiloStatus((String)ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("costcenter")) {
- user.setCostCenter((String)ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("b2")) {
- user.setFinancialLocCode((String)ie.next());
- }
- else { //we don't care about returned attribute, let's move on
- ie.next();
- }
-
- }
- }
- }
- } catch (NamingException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "An error occurred while processing the following user from POST with an ORGUSERID of " + user.getOrgUserId() + e.getMessage());
- } finally {
- return user;
- }
-
- }
-
-
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-import org.springframework.context.annotation.Condition;
-import org.springframework.context.annotation.ConditionContext;
-import org.springframework.core.type.AnnotatedTypeMetadata;
-
-public class LocalAccessCondition implements Condition{
-
- /**
- * returns true if the application is not centralized
- */
- @Override
- public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
- return PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) == null || (PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) != null && ! PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED).equals("remote"));
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-
-import java.util.*;
-
-import org.openecomp.portalsdk.core.command.*;
-
-
-public interface LoginService {
-
- /**
- *
- * @param bean
- * @param menuPropertiesFilename
- * @param additionalParams
- * @return returns login user bean
- * @throws Exception
- */
- // validate user exists in the system
- @SuppressWarnings("rawtypes")
- LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams) throws Exception;
-
-
- /**
- *
- * @param bean
- * @param menuPropertiesFilename
- * @param additionalParams
- * @param matchPassword
- * @return returns login user bean
- * @throws Exception
- */
- @SuppressWarnings("rawtypes")
- LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception;
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.openecomp.portalsdk.core.command.LoginBean;
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.menu.MenuBuilder;
-import org.openecomp.portalsdk.core.service.support.FusionService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.transaction.annotation.Transactional;
-
-
-@Transactional
-public class LoginServiceCentralizedImpl extends FusionService implements LoginService {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginServiceCentralizedImpl.class);
-
- @Autowired
- AppService appService;
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @Autowired
- RestApiRequestBuilder restApiRequestBuilder;
-
- @Autowired
- UserService userService;
-
- @SuppressWarnings("unused")
- private MenuBuilder menuBuilder;
-
- @Override
- public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams)
- throws Exception {
- return findUser(bean, menuPropertiesFilename, additionalParams, true);
- }
-
- @SuppressWarnings("rawtypes")
- public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams,
- boolean matchPassword) throws Exception {
- User user = null;
- User userCopy = null;
-
- if (bean.getUserid() != null && bean.getUserid() != null) {
- user = (User) findUser(bean);
- } else {
- if (matchPassword)
- user = (User) findUser(bean.getLoginId(), bean.getLoginPwd());
- else
- user = (User) findUserWithoutPwd(bean.getLoginId());
- }
-
- if (user != null) {
-
- if (AppUtils.isApplicationLocked()
- && !UserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) {
- bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED);
- }
-
- // raise an error if the user is inactive
- if (!user.getActive()) {
- bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
- }
-
- if (!userHasActiveRoles(user)) {
- bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
- }
- // only login the user if no errors have occurred
- if (bean.getLoginErrorMessage() == null) {
-
- // this will be a snapshot of the user's information as
- // retrieved from the database
- userCopy = (User) user.clone();
-
- User appuser = getUser(userCopy);
-
- appuser.setLastLoginDate(new Date());
-
- // update the last logged in date for the user
- // user.setLastLoginDate(new Date());
- getDataAccessService().saveDomainObject(appuser, additionalParams);
-
- // update the audit log of the user
- // Check for the client device type and set log attributes
- // appropriately
-
- // save the above changes to the User and their audit trail
-
- // create the application menu based on the user's privileges
-
- Set appMenu = getMenuBuilder().getMenu(
- SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME), dataAccessService);
- bean.setMenu(appMenu != null ? appMenu : new HashSet());
- Set businessDirectMenu = getMenuBuilder().getMenu(
- SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_SET_NAME),
- dataAccessService);
- bean.setBusinessDirectMenu(businessDirectMenu != null ? businessDirectMenu : new HashSet());
-
- bean.setUser(userCopy);
- }
- }
-
- return bean;
- }
-
- private boolean userHasActiveRoles(User user) {
- boolean hasActiveRole = false;
- Iterator roles = user.getRoles().iterator();
- while (roles.hasNext()) {
- Role role = (Role) roles.next();
- if (role.getActive()) {
- hasActiveRole = true;
- break;
- }
- }
- return hasActiveRole;
- }
-
- @SuppressWarnings("null")
- public User findUser(LoginBean bean) throws Exception {
- User user = null;
- String repsonse = restApiRequestBuilder.getViaREST("/user/" + bean.getUserid(), true, bean.getUserid());
- user = userService.userMapper(repsonse);
- user.setId(getUserIdByOrgUserId(user.getOrgUserId()));
- return user;
- }
-
- public Long getUserIdByOrgUserId(String orgUserId) {
- Map<String, String> params = new HashMap<String, String>();
- params.put("orgUserId", orgUserId);
- @SuppressWarnings("rawtypes")
- List list = getDataAccessService().executeNamedQuery("getUserIdByorgUserId", params, null);
- Long userId = null;
- if (list != null && !list.isEmpty())
- userId = (Long) list.get(0);
- return userId;
- }
-
-
- public User findUser(String loginId, String password) {
-
- List list = null;
-
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where login_id = '").append(loginId).append("'").append(" and login_pwd = '").append(password)
- .append("'");
-
- list = getDataAccessService().getList(User.class, criteria.toString(), null, null);
- return (list == null || list.size() == 0) ? null : (User) list.get(0);
- }
-
- private User findUserWithoutPwd(String loginId) {
- List list = null;
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where login_id = '").append(loginId).append("'");
- list = getDataAccessService().getList(User.class, criteria.toString(), null, null);
- return (list == null || list.size() == 0) ? null : (User) list.get(0);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- public MenuBuilder getMenuBuilder() {
- return new MenuBuilder();
- }
-
- public void setMenuBuilder(MenuBuilder menuBuilder) {
- this.menuBuilder = menuBuilder;
- }
-
- public User getUser(User user) {
- List list = null;
-
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where login_id = '").append(user.getLoginId()).append("'");
-
- list = getDataAccessService().getList(User.class, criteria.toString(), null, null);
- return (list == null || list.size() == 0) ? null : (User) list.get(0);
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.openecomp.portalsdk.core.command.LoginBean;
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.menu.MenuBuilder;
-import org.openecomp.portalsdk.core.service.support.FusionService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.transaction.annotation.Transactional;
-
-@Transactional
-public class LoginServiceImpl extends FusionService implements LoginService {
-
- @SuppressWarnings("unused")
- private MenuBuilder menuBuilder;
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @SuppressWarnings("rawtypes")
- public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams ) throws Exception {
- return findUser(bean, menuPropertiesFilename, additionalParams, true);
- }
-
- @SuppressWarnings("rawtypes")
- public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception {
- User user = null;
- User userCopy = null;
-
- if (bean.getUserid() != null && bean.getUserid() != null) {
- user = (User)findUser(bean);
- }
- else {
- if (matchPassword)
- user = (User)findUser(bean.getLoginId(), bean.getLoginPwd());
- else
- user = (User)findUserWithoutPwd(bean.getLoginId());
- }
-
- if (user != null) {
-
- // raise an error if the application is locked and the user does not have system administrator privileges
- if (AppUtils.isApplicationLocked() && !UserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) {
- bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED);
- }
-
- // raise an error if the user is inactive
- if (!user.getActive()) {
- bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
- }
-
- // raise an error if no active roles exist for the user
-// boolean hasActiveRole = false;
-// Iterator roles = user.getRoles().iterator();
-// while (roles.hasNext()) {
-// Role role = (Role)roles.next();
-// if (role.getActive()) {
-// hasActiveRole = true;
-// break;
-// }
-// }
-
-// if (!hasActiveRole) {
-// bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
-// }
- if (!userHasActiveRoles(user)) {
- bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
- }
- // only login the user if no errors have occurred
- if (bean.getLoginErrorMessage() == null) {
-
- // this will be a snapshot of the user's information as retrieved from the database
- userCopy = (User)user.clone();
-
- // update the last logged in date for the user
- user.setLastLoginDate(new Date());
- getDataAccessService().saveDomainObject(user, additionalParams);
-
- // update the audit log of the user
- //Check for the client device type and set log attributes appropriately
-
-
- // save the above changes to the User and their audit trail
-
- // create the application menu based on the user's privileges
- Set appMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME),dataAccessService);
- bean.setMenu(appMenu != null?appMenu:new HashSet());
- Set businessDirectMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_SET_NAME),dataAccessService);
- bean.setBusinessDirectMenu(businessDirectMenu != null?businessDirectMenu:new HashSet());
-
- bean.setUser(userCopy);
- }
-
- }
-
- return bean;
- }
-
- private boolean userHasActiveRoles(User user) {
- boolean hasActiveRole = false;
- @SuppressWarnings("rawtypes")
- Iterator roles = user.getRoles().iterator();
- while (roles.hasNext()) {
- Role role = (Role)roles.next();
- if (role.getActive()) {
- hasActiveRole = true;
- break;
- }
- }
- return hasActiveRole;
- }
-
- @SuppressWarnings("rawtypes")
- public User findUser(String loginId, String password) {
- List list = null;
-
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where login_id = '").append(loginId).append("'")
- .append(" and login_pwd = '").append(password).append("'");
-
- list = getDataAccessService().getList(User.class, criteria.toString(), null, null);
-
- return (list == null || list.size() == 0) ? null : (User)list.get(0);
- }
-
- @SuppressWarnings("rawtypes")
- private User findUserWithoutPwd(String loginId) {
- List list = null;
-
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where login_id = '").append(loginId).append("'");
-
- list = getDataAccessService().getList(User.class, criteria.toString(), null, null);
-
- return (list == null || list.size() == 0) ? null : (User)list.get(0);
- }
-
- @SuppressWarnings("rawtypes")
- public User findUser(LoginBean bean) {
- List list = null;
-
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where org_user_id = '").append(bean.getUserid()).append("'");
-
- list = getDataAccessService().getList(User.class, criteria.toString(), null, null);
-
- return (list == null || list.size() == 0) ? null : (User)list.get(0);
- }
-
-
- public MenuBuilder getMenuBuilder() {
- return new MenuBuilder();
- }
-
-
- public void setMenuBuilder(MenuBuilder menuBuilder) {
- this.menuBuilder = menuBuilder;
- }
-
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.command.PostDroolsBean;
-
-public interface PostDroolsService {
-
- String execute(String droolsFile, String className, String selectedRules);
-
- List<PostDroolsBean> fetchDroolBeans();
-
- String retrieveClass(String droolsFile);
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.DirectoryIteratorException;
-import java.nio.file.DirectoryStream;
-import java.nio.file.FileSystems;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.kie.api.io.ResourceType;
-import org.kie.internal.KnowledgeBase;
-import org.kie.internal.KnowledgeBaseFactory;
-import org.kie.internal.builder.KnowledgeBuilder;
-import org.kie.internal.builder.KnowledgeBuilderFactory;
-import org.kie.internal.definition.KnowledgePackage;
-import org.kie.internal.io.ResourceFactory;
-import org.kie.internal.runtime.StatefulKnowledgeSession;
-import org.openecomp.portalsdk.core.command.PostDroolsBean;
-import org.openecomp.portalsdk.core.drools.DroolsRuleService;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-/**
- * TODO REFACTOR
- *
- */
-@Service("postDroolsService")
-@Transactional
-public class PostDroolsServiceImpl implements PostDroolsService{
-
- static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostDroolsServiceImpl.class);
-
- @Override
- public String execute(String droolsFile, String className, String selectedRules) {
- logger.info(EELFLoggerDelegate.applicationLogger, "Executing Drools...");
- String resultsString = executeDemoRules(droolsFile, className, selectedRules);
- return resultsString;
- }
-
-
- public List<PostDroolsBean> fetchDroolBeans() {
-
- List<PostDroolsBean> beanList = new ArrayList<PostDroolsBean>();
- Path path = FileSystems.getDefault().getPath(SystemProperties.getProperty(SystemProperties.FILES_PATH));
- try (DirectoryStream<Path> stream = Files.newDirectoryStream(path,"*.{drl}")) {
- for (Path entry: stream) {
-
- PostDroolsBean postDroolsBean = new PostDroolsBean();
- String fileName = entry.getName(entry.getNameCount()-1).toString();
- postDroolsBean.setDroolsFile(fileName);//sample populated
- postDroolsBean.setClassName(retrieveClass(fileName));
- //postDroolsBean.setSelectedRules("[\"NJ\",\"NY\",\"KY\"]");
- beanList.add(postDroolsBean);
- }
- } catch (DirectoryIteratorException ex) {
- logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage());
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- }
- return beanList;
- }
-
- @Override
- public String retrieveClass(String fileName) {
- String resultsString = "";
- try {
- // load up the knowledge base
- final KnowledgeBuilder kbuilder = loadKBuilder(fileName);
- final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
- return pkgs.iterator().next().getFactTypes().iterator().next().getFactClass().getName();
-
- } catch (Throwable t) {
- logger.error(EELFLoggerDelegate.errorLogger, t.getMessage());
- }
-
- return resultsString;
- }
-
- protected static KnowledgeBuilder loadKBuilder(String fileName) {
- final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
-
- // this will parse and compile in one step
- kbuilder.add(ResourceFactory.newFileResource(SystemProperties.getProperty(SystemProperties.FILES_PATH) + File.separator + fileName),
- //kbuilder.add(ResourceFactory.newClassPathResource(SystemProperties.getProperty(SystemProperties.FILES_PATH) + File.separator + drl_file_path, DroolsRuleService.class),
- ResourceType.DRL);
- // kbuilder.add(ResourceFactory.newClassPathResource("rules.drl",DroolsRuleService.class),
- // ResourceType.DRL);
-
- // Check the builder for errors
- if (kbuilder.hasErrors()) {
-
- logger.error(EELFLoggerDelegate.errorLogger, kbuilder.getErrors().toString());
-
- throw new RuntimeException("Unable to compile \".drl\".");
-
- }
- return kbuilder;
- }
-
-
- @SuppressWarnings({ "deprecation", "unchecked" })
- public static String executeDemoRules(String fileName, String className, String ruleValue) {
- String resultsString = "";
- try {
- // load up the knowledge base
- // KieServices ks = KieServices.Factory.get();
- // KieContainer kContainer = ks.getKieClasspathContainer();
- // KieSession kSession = kContainer.newKieSession("ksession-rules");
-
- final KnowledgeBuilder kbuilder = loadKBuilder(fileName);
-
- // get the compiled packages (which are serializable)
-
- final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
-
- // add the packages to a knowledgebase (deploy the knowledge
- // packages).
-
- final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
-
- kbase.addKnowledgePackages(pkgs);
-
- final StatefulKnowledgeSession kSession = kbase.newStatefulKnowledgeSession();
-
- ObjectMapper mapper = new ObjectMapper();
- if(ruleValue == null || ruleValue.equals("")) {
- resultsString = "Please enter valid rule";
- return resultsString;
- }
- List<String> selectedRules = mapper.readValue(ruleValue, List.class);
- List<String> ruleResponse = new ArrayList<String>();
-
- for(String rule : selectedRules){
- Class<DroolsRuleService> clazz = (Class<DroolsRuleService>) Class.forName(className);
- DroolsRuleService droolsIntroduction =clazz.newInstance();
- droolsIntroduction.init(rule);
- kSession.insert(droolsIntroduction);
- kSession.fireAllRules();
- ruleResponse.add(droolsIntroduction.getResultsString());
- }
-
- resultsString = mapper.writeValueAsString(ruleResponse);
-
-// kSession.insert(new DroolsRuleService("KY"));
-// kSession.fireAllRules();
-//
-// kSession.setGlobal("age", "25");
-// kSession.insert(new DroolsRuleService("NY"));
-// kSession.fireAllRules();
- } catch (Throwable t) {
- logger.error(EELFLoggerDelegate.errorLogger, t.getMessage());
- }
-
- return resultsString;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.command.PostSearchBean;
-
-public interface PostSearchService {
-
- /**
- * Imports the selected users in the search results as new users.
- *
- * @param request
- * @param postSearch
- * @return the number of users successfully imported
- */
- int process(HttpServletRequest request, PostSearchBean postSearch);
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.FusionObject.Parameters;
-import org.openecomp.portalsdk.core.command.PostSearchBean;
-import org.openecomp.portalsdk.core.domain.Lookup;
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-@Service("postSearchService")
-@Transactional
-public class PostSearchServiceImpl implements PostSearchService {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostSearchServiceImpl.class);
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- public int process(HttpServletRequest request, PostSearchBean postSearch) {
- HashMap additionalParams = new HashMap();
- additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request);
- int numUsersImported = 0;
-
- if (postSearch.getSelected() != null) {
- // sort the selected users for quick validation
-
- Arrays.sort(postSearch.getSelected());
- // import the users that have been selected
- for (int i = 0; i < postSearch.getPostOrgUserId().length; i++) {
- if (Arrays.binarySearch(postSearch.getSelected(), postSearch.getPostOrgUserId()[i]) >= 0) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "Adding ORGUSERID - " + postSearch.getPostOrgUserId()[i]);
- logger.debug(EELFLoggerDelegate.auditLogger,
- "Import new user from webphone " + postSearch.getPostOrgUserId()[i]);
-
- User user = new User();
- user.setLastName(postSearch.getPostLastName()[i]);
- user.setFirstName(postSearch.getPostFirstName()[i]);
-
- if (postSearch.getPostHrid() != null && postSearch.getPostHrid().length > 0) {
- user.setHrid(postSearch.getPostHrid()[i]);
- }
-
- if (postSearch.getPostPhone() != null && postSearch.getPostPhone().length > 0) {
- user.setPhone(postSearch.getPostPhone()[i]);
- }
-
- if (postSearch.getPostEmail() != null && postSearch.getPostEmail().length > 0) {
- user.setEmail(postSearch.getPostEmail()[i]);
- }
-
- if (postSearch.getPostOrgUserId() != null && postSearch.getPostOrgUserId().length > 0) {
- user.setOrgUserId(postSearch.getPostOrgUserId()[i]);
- user.setLoginId(postSearch.getPostOrgUserId()[i]);
- }
-
- if (postSearch.getPostAddress1() != null && postSearch.getPostAddress1().length > 0) {
- user.setAddress1(postSearch.getPostAddress1()[i]);
- }
-
- if (postSearch.getPostAddress2() != null && postSearch.getPostAddress2().length > 0) {
- user.setAddress2(postSearch.getPostAddress2()[i]);
- }
-
- if (postSearch.getPostCity() != null && postSearch.getPostCity().length > 0) {
- user.setCity(postSearch.getPostCity()[i]);
- }
-
- if (postSearch.getPostState() != null && postSearch.getPostState().length > 0) {
- user.setState(postSearch.getPostState()[i]);
- }
-
- if (postSearch.getPostZipCode() != null && postSearch.getPostZipCode().length > 0) {
- user.setZipCode(postSearch.getPostZipCode()[i]);
- }
-
- if (postSearch.getPostLocationClli() != null && postSearch.getPostLocationClli().length > 0) {
- user.setLocationClli(postSearch.getPostLocationClli()[i]);
- }
-
- if (postSearch.getPostBusinessCountryCode() != null
- && postSearch.getPostBusinessCountryCode().length > 0) {
- user.setBusinessCountryCode(postSearch.getPostBusinessCountryCode()[i]);
- }
-
- if (postSearch.getPostBusinessCountryName() != null
- && postSearch.getPostBusinessCountryName().length > 0) {
-
- // find the country cd for the indicated country
- List countries = dataAccessService.getLookupList("fn_lu_country", "country_cd", "country",
- "country = '" + postSearch.getPostBusinessCountryName()[i] + "'", null, null);
-
- if (countries != null && countries.size() == 1) {
- Lookup country = (Lookup) countries.get(0);
- user.setCountry(country.getValue());
- } else {
- logger.info(EELFLoggerDelegate.debugLogger,
- "No countries or more than one country was found matching the country returned from WEBPHONE. "
- + "Therefore, no country was set for this user.");
- }
-
- }
-
- if (postSearch.getPostDepartment() != null && postSearch.getPostDepartment().length > 0) {
- user.setDepartment(postSearch.getPostDepartment()[i]);
- }
-
- if (postSearch.getPostDepartmentName() != null && postSearch.getPostDepartmentName().length > 0) {
- user.setDepartmentName(postSearch.getPostDepartmentName()[i]);
- }
-
- if (postSearch.getPostBusinessUnit() != null && postSearch.getPostBusinessUnit().length > 0) {
- user.setBusinessUnit(postSearch.getPostBusinessUnit()[i]);
- }
-
- if (postSearch.getPostBusinessUnitName() != null
- && postSearch.getPostBusinessUnitName().length > 0) {
- user.setBusinessUnitName(postSearch.getPostBusinessUnitName()[i]);
- }
-
- if (postSearch.getPostJobTitle() != null && postSearch.getPostJobTitle().length > 0) {
- user.setJobTitle(postSearch.getPostJobTitle()[i]);
- }
-
- if (postSearch.getPostOrgManagerUserId() != null
- && postSearch.getPostOrgManagerUserId().length > 0) {
- user.setOrgManagerUserId(postSearch.getPostOrgManagerUserId()[i]);
- }
-
- if (postSearch.getPostCommandChain() != null && postSearch.getPostCommandChain().length > 0) {
- user.setCommandChain(postSearch.getPostCommandChain()[i]);
- }
-
- if (postSearch.getPostCompanyCode() != null && postSearch.getPostCompanyCode().length > 0) {
- user.setCompanyCode(postSearch.getPostCompanyCode()[i]);
- }
-
- if (postSearch.getPostCompany() != null && postSearch.getPostCompany().length > 0) {
- user.setCompany(postSearch.getPostCompany()[i]);
- }
-
- if (postSearch.getPostCostCenter() != null && postSearch.getPostCostCenter().length > 0) {
- user.setCostCenter(postSearch.getPostCostCenter()[i]);
- }
-
- if (postSearch.getPostSiloStatus() != null && postSearch.getPostSiloStatus().length > 0) {
- user.setSiloStatus(postSearch.getPostSiloStatus()[i]);
- }
-
- if (postSearch.getPostFinancialLocCode() != null
- && postSearch.getPostFinancialLocCode().length > 0) {
- user.setFinancialLocCode(postSearch.getPostFinancialLocCode()[i]);
- }
-
- user.setActive(true);
-
- try {
- dataAccessService.saveDomainObject(user, additionalParams);
- Role role = (Role) dataAccessService.getDomainObject(Role.class,
- Long.valueOf(SystemProperties.getProperty(SystemProperties.POST_DEFAULT_ROLE_ID)),
- null);
- user.addRole(role);
- numUsersImported++;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "process: saveDomainObject failed on user " + user.getLoginId(), e);
- }
- }
- }
-
- }
-
- return numUsersImported;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.domain.Profile;
-import org.openecomp.portalsdk.core.domain.User;
-
-
-public interface ProfileService {
-
- /**
- *
- * @return returns list of profiles
- * @throws Exception
- */
- List<Profile> findAll() throws Exception;
-
- /**
- *
- * @param id
- * @return returns profile of requested ID
- * @throws Exception
- */
- Profile getProfile(int id) throws Exception;
-
-
- /**
- *
- * @param id loginId
- * @return returns User info of requested ID
- * @throws Exception
- */
- User getUser(String id) throws Exception;
-
- /**
- *
- * @param user
- *saveUser method saves the user object
- */
- void saveUser(User user);
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.domain.Profile;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.transaction.annotation.Transactional;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Transactional
-public class ProfileServiceCentralizedImpl implements ProfileService{
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProfileServiceCentralizedImpl.class);
-
- @Autowired
- AppService appService;
-
- @Autowired
- private DataAccessService dataAccessService;
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- @Autowired
- RestApiRequestBuilder restApiRequestBuilder ;
-
- @SuppressWarnings("unchecked")
- @Override
- public List<Profile> findAll() throws Exception{
- return getDataAccessService().getList(Profile.class, null);
- }
-
- @Override
- public Profile getProfile(int id) throws Exception{
- ObjectMapper mapper = new ObjectMapper();
- Profile user = null;
- String responseString = restApiRequestBuilder.getViaREST("/getProfile/" + id, true,Integer.toString(id));
- user = mapper.readValue(responseString, Profile.class);
- return user;
- }
-
- @Override
- public User getUser(String id) throws Exception{
- ObjectMapper mapper = new ObjectMapper();
- User user = new User();
- String responseString =restApiRequestBuilder.getViaREST("/user/" + id, true,id);
- user = mapper.readValue(responseString, User.class);
-
- return user;
- }
-
- @Override
- public void saveUser(User user) {
- try {
- getDataAccessService().saveDomainObject(user, null);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "saveUser failed", e);
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.dao.ProfileDao;
-import org.openecomp.portalsdk.core.domain.Profile;
-import org.openecomp.portalsdk.core.domain.User;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.transaction.annotation.Transactional;
-
-@Transactional
-public class ProfileServiceImpl implements ProfileService{
-
- @Autowired
- private ProfileDao profileDao;
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @SuppressWarnings("unchecked")
- public List<Profile> findAll() {
- //List msgDB = getDataAccessService().getList(Profile.class, null);
- return getDataAccessService().getList(Profile.class, null);
- }
-
- public User getUser(String userId){
- return (User) getDataAccessService().getDomainObject(User.class, Long.parseLong(userId), null);
- }
-
- public void saveUser(User user){
-
- getDataAccessService().saveDomainObject(user, null);
- }
-
-
- public Profile getProfile(int id) {
- return profileDao.getProfile(id);
- }
-
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
-
-
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
-
-import org.openecomp.portalsdk.core.domain.App;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.rest.RestWebServiceClient;
-import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-
-public class RestApiRequestBuilder {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestApiRequestBuilder.class);
-
- @Autowired
- AppService appService;
-
- public static String content_type = "application/json";
-
- public String getViaREST(String restEndPoint, boolean isBasicAuth,String userId) throws Exception {
- String appName = "";
- String requestId = "";
- String appUserName = "";
- String decryptedPwd = "";
-
- logger.info(EELFLoggerDelegate.debugLogger, "Making use of REST API communication for GET" + restEndPoint);
-
- App app = appService.getDefaultApp();
-
- if (app != null) {
- appName = app.getName();
- appUserName = app.getUsername();
- try {
- decryptedPwd = CipherUtil.decrypt(app.getAppPassword(),
- SystemProperties.getProperty(SystemProperties.Decryption_Key));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: "
- + e.toString());
- }
- } else {
- logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database.");
- appName = SystemProperties.SDK_NAME;
- }
- requestId = MDC.get(MDC_KEY_REQUEST_ID);
-
- String response = null;
- try {
- response = RestWebServiceClient.getInstance().getPortalContent(restEndPoint, userId,appName, requestId, appUserName,
- decryptedPwd, isBasicAuth);
- } catch (Exception ex) {
- response = "Failed to perform GET " + ex.toString();
- throw new Exception("get Failed"+ ex);
- }
- logger.debug(EELFLoggerDelegate.errorLogger, "getRoles response: {}", response);
- return response;
- }
-
- public void postViaREST(String restEndPoint, boolean isBasicAuth, String content,String userId) throws Exception {
- String appName = "";
- String requestId = "";
- String appUserName = "";
- String decryptedPwd = "";
-
- logger.info(EELFLoggerDelegate.debugLogger, "Making use of REST API communication for POST" + restEndPoint);
-
- App app = appService.getDefaultApp();
-
- if (app != null) {
- appName = app.getName();
- appUserName = app.getUsername();
- try {
- decryptedPwd = CipherUtil.decrypt(app.getAppPassword(),
- SystemProperties.getProperty(SystemProperties.Decryption_Key));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: "
- + e.toString());
- }
- } else {
- logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database.");
- appName = SystemProperties.SDK_NAME;
- }
- requestId = MDC.get(MDC_KEY_REQUEST_ID);
-
-
- try {
- RestWebServiceClient.getInstance().postPortalContent(restEndPoint, userId, appName, requestId, appUserName,
- decryptedPwd, content_type, content, isBasicAuth);
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "POST response: {}", ex);
-
- throw new Exception("Save Failed");
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "POST response: {}");
-
- }
-
- public void deleteViaRest(String restEndPoint, boolean isBasicAuth, String content, String userId) throws Exception {
- String appName = "";
- String requestId = "";
- String appUserName = "";
- String decryptedPwd = "";
-
- logger.info(EELFLoggerDelegate.debugLogger, "Making use of REST API communication for DELETE" + restEndPoint);
-
- App app = appService.getDefaultApp();
-
- if (app != null) {
- appName = app.getName();
- appUserName = app.getUsername();
- try {
- decryptedPwd = CipherUtil.decrypt(app.getAppPassword(),
- SystemProperties.getProperty(SystemProperties.Decryption_Key));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: "
- + e.toString());
- }
- } else {
- logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database.");
- appName = SystemProperties.SDK_NAME;
- }
- requestId = MDC.get(MDC_KEY_REQUEST_ID);
-
-
- try {
- RestWebServiceClient.getInstance().deletePortalContent(restEndPoint, userId, appName, requestId, appUserName,
- decryptedPwd, content_type, content, isBasicAuth);
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "DELETE response: {}", ex);
- throw new Exception("Delete Failed");
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "DELETE response: {}");
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-
-
-public interface RoleService {
- /**
- *
- * @param requestedLoginId loginId
- * @return returns List of RoleFunction
- * @throws Exception
- * Method getRoleFunctions returns list of Role Functions
- */
- List<RoleFunction> getRoleFunctions(String requestedLoginId) throws Exception;
-
-
- /**
- *
- * @param requestedLoginId
- * @param roleId
- * @return returns List of Role
- * @throws Exception
- * Method getAvailableChildRoles returns list of avialable child roles
- */
- List<Role> getAvailableChildRoles(String requestedLoginId,Long roleId) throws Exception;
-
-
- /**
- *
- * @param requestedLoginId
- * @param id roleId
- * @return returns role
- * @throws Exception
- * Method getRole returns Role object if requested roleID
- */
- Role getRole(String requestedLoginId,Long id) throws Exception;
-
- /**
- *
- * @param requestedLoginId
- * @param domainRole Object to be saved
- * Method saveRole saves the Role Object
- */
- void saveRole(String requestedLoginId,Role domainRole) throws Exception;
-
- /**
- *
- * @param requestedLoginId
- * @param domainRole Object to be removed
- * Method deleteRole deletes the requested Role Object
- */
- void deleteRole(String requestedLoginId,Role domainRole) throws Exception;
-
- /**
- *
- * @param requestedLoginId
- * @return returns list of available roles
- * @throws Exception
- * Method getAvailableRoles gets the list of available roles
- */
-
- List<Role> getAvailableRoles(String requestedLoginId) throws Exception;
-
- /**
- *
- * @param requestedLoginId
- * @return List of active roles
- * @throws Exception
- * Method getActiveRoles gets the list of active roles of application
- *
- */
- List<Role> getActiveRoles(String requestedLoginId) throws Exception;
-
- /**
- *
- * @param requestedLoginId
- * @param code function code
- * @return RoleFunction of requested function code
- * @throws Exception
- * Method getRoleFunction returns RoleFunction of requested function code
- */
- RoleFunction getRoleFunction(String requestedLoginId,String code) throws Exception;
-
- /**
- *
- * @param requestedLoginId
- * @param domainRoleFunction
- * Method saveRoleFunction saves the requested RoleFunction object
- */
- void saveRoleFunction(String requestedLoginId,RoleFunction domainRoleFunction) throws Exception;
-
- /**
- *
- * @param requestedLoginId
- * @param domainRoleFunction
- * Method deleteRoleFunction deletes the requested RoleFunction object
- */
- void deleteRoleFunction(String requestedLoginId,RoleFunction domainRoleFunction) throws Exception;
-
- /**
- *
- * @param requestedLoginId
- * @param id
- * Method deleteDependcyRoleRecord deletes the requested object
- */
- void deleteDependcyRoleRecord(String requestedLoginId,Long id);
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.transaction.annotation.Transactional;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.type.TypeFactory;
-
-@Transactional
-public class RoleServiceCentralizedAccess implements RoleService {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleServiceCentralizedAccess.class);
-
- @Autowired
- AppService appService;
-
- @Autowired
- RestApiRequestBuilder restApiRequestBuilder;
-
- @Override
- public List<RoleFunction> getRoleFunctions(String loginId) throws Exception {
-
- List<RoleFunction> roleFunctionList = null;
- String role_function_list = "";
- role_function_list = restApiRequestBuilder.getViaREST("/functions", true, loginId);
- ObjectMapper mapper = new ObjectMapper();
- roleFunctionList = mapper.readValue(role_function_list,
- TypeFactory.defaultInstance().constructCollectionType(List.class, RoleFunction.class));
- return roleFunctionList;
- }
-
- @Override
- public List<Role> getAvailableChildRoles(String loginId, Long roleId) throws Exception {
- List<Role> availableChildRoles = getAvailableRoles(loginId);
- if (roleId == null || roleId == 0) {
- return availableChildRoles;
- }
-
- Role currentRole = getRole(loginId, roleId);
- Set<Role> allParentRoles = new TreeSet<Role>();
- allParentRoles = getAllParentRolesAsList(loginId, currentRole, allParentRoles);
-
- Iterator<Role> availableChildRolesIterator = availableChildRoles.iterator();
- while (availableChildRolesIterator.hasNext()) {
- Role role = availableChildRolesIterator.next();
- if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
- availableChildRolesIterator.remove();
- }
- }
- return availableChildRoles;
- }
-
- @SuppressWarnings("unchecked")
- private Set<Role> getAllParentRolesAsList(String loginId, Role role, Set<Role> allParentRoles) {
- Set<Role> parentRoles = role.getParentRoles();
- allParentRoles.addAll(parentRoles);
- Iterator<Role> parentRolesIterator = parentRoles.iterator();
- while (parentRolesIterator.hasNext()) {
- getAllParentRolesAsList(loginId, parentRolesIterator.next(), allParentRoles);
- }
- return allParentRoles;
- }
-
- @Override
- public Role getRole(String loginId, Long id) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- String roleString = restApiRequestBuilder.getViaREST("/role/" + id, true, loginId);
- Role role = new Role();
- role = mapper.readValue(roleString, Role.class);
- if (role.getRoleFunctions() != null) {
- @SuppressWarnings("unchecked")
- Set<RoleFunction> roleFunctionList = role.getRoleFunctions();
- Set<RoleFunction> roleFunctionListNew = new HashSet<>();
- Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
- while (itetaror.hasNext()) {
- Object nextValue = itetaror.next();
- RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
- roleFunctionListNew.add(roleFun);
- }
-
- role.setRoleFunctions(roleFunctionListNew);
- }
- logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + role.getId());
- return role;
-
- }
-
- @Override
- public void saveRole(String loginId, Role domainRole) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- String role = mapper.writeValueAsString(domainRole);
- try {
- restApiRequestBuilder.postViaREST("/role", true, role, loginId);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "saveRole Failed", e);
- throw new Exception(e.getMessage());
- }
- }
-
- @Override
- public void deleteRole(String loginId, Role domainRole) throws Exception {
- String roleName = domainRole.getName().replaceAll(" ", "%20");
- try {
- restApiRequestBuilder.deleteViaRest("/deleteRole/"+ roleName, true, null, loginId);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteRole Failed", e);
- throw new Exception(e.getMessage());
- }
- }
- @Override
- public List<Role> getAvailableRoles(String requestedLoginId) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- String roleList = restApiRequestBuilder.getViaREST("/roles", true, requestedLoginId);
- List<Role> roles = null;
- roles = mapper.readValue(roleList,
- TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
- return roles;
- }
-
- @Override
- public List<Role> getActiveRoles(String requestedLoginId) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- String roleString = restApiRequestBuilder.getViaREST("/activeRoles", true, requestedLoginId);
- List<Role> roles = null;
- roles = mapper.readValue(roleString,
- TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
- return roles;
-
- }
-
- @Override
- public RoleFunction getRoleFunction(String requestedLoginId, String code) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- String responseString = restApiRequestBuilder.getViaREST("/function/" + code, true, requestedLoginId);
- RoleFunction roleFunction = new RoleFunction();
- if (!responseString.isEmpty()) {
- roleFunction = mapper.readValue(responseString, RoleFunction.class);
- }
- return roleFunction;
- }
-
- @Override
- public void saveRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- String roleFunction = mapper.writeValueAsString(domainRoleFunction);
- try{
- restApiRequestBuilder.postViaREST("/roleFunction", true, roleFunction, requestedLoginId);
- }catch(Exception e){
- logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction Failed", e);
- throw new Exception(e.getMessage());
- }
- }
-
- @Override
- public void deleteRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws Exception {
- String code = domainRoleFunction.getCode();
- try {
- restApiRequestBuilder.deleteViaRest("/roleFunction/"+ code, true, null, requestedLoginId);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction Failed ", e);
- throw new Exception(e.getMessage());
- }
- }
-
- @Override
- public void deleteDependcyRoleRecord(String requestedLoginId, Long id) {
- try {
- restApiRequestBuilder.deleteViaRest("/deleteDependcyRoleRecord/" + id, true, null, requestedLoginId);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord Failed", e);
- }
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.sql.Connection;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.TreeSet;
-
-import javax.sql.DataSource;
-
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.transaction.annotation.Transactional;
-
-@Transactional
-public class RoleServiceImpl implements RoleService {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleServiceImpl.class);
-
- @Autowired
- private DataAccessService dataAccessService;
-
- DataSource dataSource;
-
- public DataSource getDataSource() {
- return dataSource;
- }
-
- @Autowired
- public void setDataSource(DataSource dataSource) {
- this.dataSource = dataSource;
- }
-
- @SuppressWarnings("unchecked")
- public List<RoleFunction> getRoleFunctions(String loginId) {
- // List msgDB = getDataAccessService().getList(Profile.class, null);
- return getDataAccessService().getList(RoleFunction.class, null);
- }
-
- @SuppressWarnings("unchecked")
- public List<Role> getAvailableChildRoles(String loginId,Long roleId) {
- List<Role> availableChildRoles = (List<Role>) getDataAccessService().getList(Role.class, null);
- if (roleId == null || roleId == 0) {
- return availableChildRoles;
- }
-
- Role currentRole = (Role) getDataAccessService().getDomainObject(Role.class, roleId, null);
- Set<Role> allParentRoles = new TreeSet<Role>();
- allParentRoles = getAllParentRolesAsList(loginId,currentRole, allParentRoles);
-
- Iterator<Role> availableChildRolesIterator = availableChildRoles.iterator();
- while (availableChildRolesIterator.hasNext()) {
- Role role = availableChildRolesIterator.next();
- if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
- availableChildRolesIterator.remove();
- }
- }
- return availableChildRoles;
- }
-
- @SuppressWarnings("unchecked")
- private Set<Role> getAllParentRolesAsList(String loginId,Role role, Set<Role> allParentRoles) {
- Set<Role> parentRoles = role.getParentRoles();
- allParentRoles.addAll(parentRoles);
- Iterator<Role> parentRolesIterator = parentRoles.iterator();
- while (parentRolesIterator.hasNext()) {
- getAllParentRolesAsList( loginId,parentRolesIterator.next(), allParentRoles);
- }
- return allParentRoles;
- }
-
- public RoleFunction getRoleFunction(String loginId,String code) {
- return (RoleFunction) getDataAccessService().getDomainObject(RoleFunction.class, code, null);
- }
-
- public void saveRoleFunction(String loginId,RoleFunction domainRoleFunction) {
- getDataAccessService().saveDomainObject(domainRoleFunction, null);
- }
-
- public void deleteRoleFunction(String loginId,RoleFunction domainRoleFunction) {
- getDataAccessService().deleteDomainObject(domainRoleFunction, null);
- }
-
- public Role getRole(String loginId,Long id) {
- return (Role) getDataAccessService().getDomainObject(Role.class, id, null);
- }
-
- public void saveRole(String loginId,Role domainRole) {
- getDataAccessService().saveDomainObject(domainRole, null);
- }
-
- public void deleteRole(String loginId,Role domainRole) {
- getDataAccessService().deleteDomainObject(domainRole, null);
- }
-
- @SuppressWarnings("unchecked")
- public List<Role> getAvailableRoles(String loginId) {
- return getDataAccessService().getList(Role.class, null);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<Role> getActiveRoles(String loginId) {
- String filter = " where active_yn = 'Y' ";
- return getDataAccessService().getList(Role.class, filter, null, null);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- @Override
- public void deleteDependcyRoleRecord(String loginId,Long id) {
- Connection conn = null;
- Statement stmt = null;
- try {
- conn = getDataSource().getConnection();
- stmt = conn.createStatement();
- String sql = "delete from fn_user_role where role_id = '" + id + "'";
- stmt.executeUpdate(sql);
- stmt.close();
- conn.close();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", e);
- } finally {
- try {
- if (stmt != null)
- stmt.close();
- } catch (SQLException se2) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", se2);
- }
- try {
- if (conn != null)
- conn.close();
- } catch (SQLException se) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", se);
- }
- }
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-/*package org.openecomp.portalsdk.core.service;
-
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-
-@Service("roleService")
-@Transactional
-public class RoleServiceNonSpringImpl implements RoleService{
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @SuppressWarnings("unchecked")
- public List<RoleFunction> getRoleFunctions() {
- //List msgDB = getDataAccessService().getList(Profile.class, null);
- return getDataAccessService().getList(RoleFunction.class, null);
- }
-
- @SuppressWarnings("unchecked")
- public List<Role> getAvailableChildRoles(Long roleId) {
- List<Role> availableChildRoles = (List<Role>)getDataAccessService().getList(Role.class,null);
- if(roleId==null || roleId==0){
- return availableChildRoles;
- }
-
- Role currentRole = (Role)getDataAccessService().getDomainObject(Role.class,roleId,null);
- Set<Role> allParentRoles = new TreeSet<Role>();
- allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
-
-
- Iterator<Role> availableChildRolesIterator = availableChildRoles.iterator();
- while (availableChildRolesIterator.hasNext()) {
- Role role = availableChildRolesIterator.next();
- if(!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)){
- availableChildRolesIterator.remove();
- }
- }
- return availableChildRoles;
- }
-
- @SuppressWarnings("unchecked")
- private Set<Role> getAllParentRolesAsList(Role role, Set<Role> allParentRoles) {
- Set<Role> parentRoles = role.getParentRoles();
- allParentRoles.addAll(parentRoles);
- Iterator<Role> parentRolesIterator = parentRoles.iterator();
- while (parentRolesIterator.hasNext()) {
- getAllParentRolesAsList(parentRolesIterator.next(),allParentRoles);
- }
- return allParentRoles;
- }
-
- public RoleFunction getRoleFunction(String code) {
- return (RoleFunction)getDataAccessService().getDomainObject(RoleFunction.class, code, null);
- }
-
- public void saveRoleFunction(RoleFunction domainRoleFunction) {
- getDataAccessService().saveDomainObject(domainRoleFunction, null);
- }
-
- public void deleteRoleFunction(RoleFunction domainRoleFunction) {
- getDataAccessService().deleteDomainObject(domainRoleFunction, null);
- }
-
- public Role getRole(Long id) {
- return (Role)getDataAccessService().getDomainObject(Role.class, id, null);
- }
-
- public void saveRole(Role domainRole) {
- getDataAccessService().saveDomainObject(domainRole, null);
- }
-
- public void deleteRole(Role domainRole) {
- getDataAccessService().deleteDomainObject(domainRole, null);
- }
-
- @SuppressWarnings("unchecked")
- public List<Role> getAvailableRoles() {
- return getDataAccessService().getList(Role.class, null);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
-
-
-}
-*/
\ No newline at end of file
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.domain.UrlsAccessible;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-@Transactional
-@Service("urlAccessService")
-public class UrlAccessImpl implements UrlAccessService{
-
- @Autowired
- DataAccessService dataAccessService;
-
- @Override
- public boolean isUrlAccessible(HttpServletRequest request, String currentUrl) {
- boolean isAccessible = false;
- Map<String, String> params = new HashMap<>();
- params.put("current_url", currentUrl);
- List list = dataAccessService.executeNamedQuery("restrictedUrls", params, null);
-
- // loop through the list of restricted URL's
- if (list != null && list.size() > 0) {
- for (int i = 0; i < list.size(); i++) {
- UrlsAccessible urlFunctions = (UrlsAccessible) list.get(i);
- // String url = (String) urlFunctions.getUrl();
- String functionCd = (String) urlFunctions.getFunctionCd();
- if (UserUtils.isAccessible(request, functionCd)) {
- isAccessible = true;
- }
- }
- return isAccessible;
- }
- return true;
- }
-
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import javax.servlet.http.HttpServletRequest;
-
-public interface UrlAccessService {
-
- /**
- * Answers whether the specified URL is accessible.
- *
- * @param request
- * @param currentUrl
- * @return true if yes, false if no.
- */
- public boolean isUrlAccessible(HttpServletRequest request, String currentUrl);
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.domain.User;
-
-
-public interface UserProfileService {
- List<User> findAll();
- User getUserByLoginId(String loginId);
- void saveUser(User user);
- public List<User> findAllUserWithOnOffline(String originOrgUserId);
- List<User> findAllActive();
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.SortedSet;
-
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Restrictions;
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.domain.support.CollaborateList;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-@Service("userProfile")
-@Transactional
-public class UserProfileServiceImpl implements UserProfileService{
-
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @SuppressWarnings("unchecked")
- public List<User> findAll() {
- return getDataAccessService().getList(User.class, null);
- }
-
- @SuppressWarnings("unchecked")
- public User getUserByLoginId(String loginId){
- User user=null;
- List<Criterion> restrictionsList = new ArrayList<Criterion>();
- Criterion criterion1= Restrictions.eq("loginId",loginId);
- restrictionsList.add(criterion1);
- List<User> users = (List<User>) getDataAccessService().getList(User.class,null, restrictionsList, null);
- if(users!=null && users.size()==1)
- user = users.get(0);
- return user;
- }
-
- public void saveUser(User user){
-
- getDataAccessService().saveDomainObject(user, null);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- @SuppressWarnings("unchecked")
- public List<User> findAllUserWithOnOffline(String originOrgUserId) {
- HashSet<String> onlineUser = CollaborateList.getInstance().getAllUserName();
- List<User> users = getDataAccessService().getList(User.class, null);
- for(User u:users){
- if(onlineUser.contains(u.getOrgUserId()))
- u.setOnline(true);
- if(u.getOrgUserId()!=null){
- if(originOrgUserId.compareTo(u.getOrgUserId()) > 0) {
- u.setChatId(originOrgUserId + "-" + u.getOrgUserId());
- } else u.setChatId(u.getOrgUserId() + "-" + originOrgUserId );
- }
- }
- return users;
-
- }
-
- public List<User> findAllActive() {
- @SuppressWarnings("unchecked")
- List<User> users = getDataAccessService().getList(User.class, null);
- Iterator<User> itr = users.iterator();
- while(itr.hasNext()){
- User u = (User) itr.next();
- if(!u.getActive())
- itr.remove();//if not active remove user from list
- else {
- SortedSet<Role> roles = u.getRoles();
- Iterator<Role> itrRoles = roles.iterator();
- while(itrRoles.hasNext()){
- Role role = (Role) itrRoles.next();
- if(!role.getActive())
- u.removeRole(role.getId());//if not active remove role from list
- }
- }
- }
- return users;
- }
-
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import org.openecomp.portalsdk.core.domain.User;
-
-public interface UserService {
-
- /**
- * Gets the user object for the specified ID.
- *
- * @param id
- * orgUserID
- * @return User object
- * @throws Exception
- */
- User getUser(String id) throws Exception;
-
- /**
- * Builds a User object from a JSON string.
- *
- * @param response
- * @return User object
- * @throws Exception
- */
- User userMapper(String response) throws Exception;
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.domain.UserApp;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.transaction.annotation.Transactional;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Transactional
-public class UserServiceCentalizedImpl implements UserService {
-
- @Autowired
- AppService appService;
-
- @Autowired
- RestApiRequestBuilder restApiRequestBuilder;
-
- @Autowired
- LoginService loginService;
-
- @Autowired
- private DataAccessService dataAccessService;
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
-
- @Override
- public User getUser(String id) throws Exception {
- User user = null;
- String orgUserId = getUserByProfileId(id);
- String responseString = restApiRequestBuilder.getViaREST("/user/" + orgUserId, true, id);
- user = userMapper(responseString);
- return user;
- }
-
- public String getUserByProfileId(String id) {
- Map<String, Long> params = new HashMap<String, Long>();
- params.put("user_id", new Long(id));
- @SuppressWarnings("rawtypes")
- List list = getDataAccessService().executeNamedQuery("getUserByProfileId", params, null);
- String orgUserId = "";
- if (list != null && !list.isEmpty())
- orgUserId = (String) list.get(0);
- return orgUserId;
- }
-
- @Override
- public User userMapper(String res) throws Exception
- {
- User user= new User();
- ObjectMapper mapper = new ObjectMapper();
- HashSet<RoleFunction> rolefun = null;
- user = mapper.readValue(res, User.class);
- Set<RoleFunction> roleFunctionListNew = new HashSet<>();
- Set<RoleFunction> roleFunctionList = new HashSet<>();
- SortedSet<UserApp> UserAppSet = new TreeSet<>();
- @SuppressWarnings("unchecked")
- Set<UserApp> setAppsObj = user.getUserApps();
- Iterator<UserApp> it = setAppsObj.iterator();
- while (it.hasNext()) {
- Object next = it.next();
-
- UserApp nextApp = mapper.convertValue(next, UserApp.class);
- rolefun = new HashSet<>();
- Role role = nextApp.getRole();
- roleFunctionList = role.getRoleFunctions();
- Iterator<RoleFunction> itetaror = roleFunctionList.iterator();
- while (itetaror.hasNext()) {
- Object nextValue = itetaror.next();
- RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class);
- roleFunctionListNew.add(roleFunction);
- }
- role.setRoleFunctions(roleFunctionListNew);
- nextApp.setRole(role);
- nextApp.getRole().getRoleFunctions();
-
- UserAppSet.add(nextApp);
- user.setUserApps(UserAppSet);
- }
- return user;
- }
-
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.service;
-
-import org.openecomp.portalsdk.core.domain.User;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.transaction.annotation.Transactional;
-
-@Transactional
-public class UserServiceImpl implements UserService {
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @Override
- public User getUser(String id) {
- return (User) dataAccessService.getDomainObject(User.class, Long.parseLong(id), null);
- }
-
- @Override
- public User userMapper(String response) throws Exception {
- throw new UnsupportedOperationException("method cannot be used");
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-
-public interface WebServiceCallService {
- public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword)throws Exception;
- /*public String get(String restURL, String restPath);*/
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.domain.App;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-@Service("webServiceCallService")
-@Transactional
-public class WebServiceCallServiceImpl implements WebServiceCallService{
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @Autowired
- AppService appService;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebServiceCallServiceImpl.class);
-
- /**
- * Verify REST Credential
- * @return true if the credential is accepted; else false.
- */
- @Override
- public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword)throws Exception {
- App app = appService.getDefaultApp();
- if (app!=null) {
- String encriptedPwdDB = app.getAppPassword();
- String appUserName = app.getUsername();
- String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB, secretKey==null?SystemProperties.getProperty(SystemProperties.Decryption_Key):secretKey);
- if(decreptedPwd.equals(requestPassword) && appUserName.equals(requestAppName)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Getting App information from FN_APP table
- * @return App domain object, or null if not found.
- */
- public App findApp(){
- List<?> list = null;
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where id = 1");
- list = getDataAccessService().getList(App.class, criteria.toString(), null, null);
- return (list == null || list.size() == 0) ? null : (App) list.get(0);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- /*/
- @Override
- public String get(String restURL, String restPath) {
- String appUserName = "";
- String appUebKey = "";
- String decreptedPwd = "";
- String appName = "";
- String inputLine = "";
- String serviceName = "";
- String loginId = "";
- StringBuffer jsonResponse = new StringBuffer();
-
- StopWatch stopWatch = new StopWatch("WebServiceCallServiceImpl.get");
- stopWatch.start();
- try {
- logger.info(EELFLoggerDelegate.metricsLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started.");
- logger.debug(EELFLoggerDelegate.debugLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started.");
- loginId = MDC.get("LoginId");
- appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
- App app = appService.getDefaultApp();
- if (app!=null) {
- appName = app.getName();
- appUserName = app.getUsername();
- try{
- decreptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key));
- } catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: " + e.getMessage());
- }
- } else {
- logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database.");
- appName = SystemProperties.SERVICE_NAME;
- }
-
- //Create the connection object
- URL obj = new URL(restURL + restPath);
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
- con.setRequestMethod("GET");
- con.setConnectTimeout(3000);
- con.setReadTimeout(8000);
-
- //add request header
- con.setRequestProperty("username", appUserName);
- con.setRequestProperty("password", decreptedPwd);
- con.setRequestProperty("uebkey", appUebKey);
- con.setRequestProperty(SystemProperties.LOGIN_ID, loginId);
- con.setRequestProperty(SystemProperties.USERAGENT_NAME, appName);
- con.setRequestProperty(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID));
-
- //set MDC context for outgoing audit logging
- serviceName = String.format("%s:%s.%s", appName, SystemProperties.ECOMP_PORTAL_BE, restPath);
- MDC.put(Configuration.MDC_SERVICE_NAME, serviceName);
- MDC.put(Configuration.MDC_REMOTE_HOST, restURL);
- MDC.put(SystemProperties.MDC_APPNAME, appName);
- MDC.put(SystemProperties.MDC_REST_PATH, restPath);
- MDC.put(SystemProperties.MDC_REST_METHOD, "GET");
-
- int responseCode = con.getResponseCode();
- logger.info(EELFLoggerDelegate.errorLogger, "Received the response code '" + responseCode + "' while getting the '" + restPath + "' for user: " + loginId);
-
- BufferedReader in = new BufferedReader(
- new InputStreamReader(con.getInputStream()));
-
- while ((inputLine = in.readLine()) != null) {
- jsonResponse.append(inputLine);
- }
- in.close();
-
- logSecurityMessage(RESULT_ENUM.SUCCESS);
- logger.debug(EELFLoggerDelegate.debugLogger, restPath + " response: " + jsonResponse.toString());
- logger.debug(EELFLoggerDelegate.debugLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started.");
- } catch(UrlAccessRestrictedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Authentication exception occurred in WebServiceCallServiceImpl.get (" + restPath + "). Details: " + e.getMessage());
- logSecurityMessage(RESULT_ENUM.FAILURE);
- } catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get (" + restPath + "). Details: " + e.getMessage());
- logSecurityMessage(RESULT_ENUM.FAILURE);
- } finally {
- if (stopWatch.isRunning()) stopWatch.stop();
- MDC.put(SystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms");
- logger.info(EELFLoggerDelegate.metricsLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is completed.");
-
- //clear the temporary MDC context values
- MDC.remove(SystemProperties.MDC_TIMER);
- MDC.remove(SystemProperties.MDC_REST_METHOD);
- MDC.remove(SystemProperties.MDC_REST_PATH);
- MDC.remove(SystemProperties.MDC_APPNAME);
- MDC.remove(Configuration.MDC_REMOTE_HOST);
- MDC.remove(Configuration.MDC_SERVICE_NAME);
- }
-
- return jsonResponse.toString();
- }
-
- //Handles all the outgoing rest/ueb messages.
- public void logSecurityMessage(RESULT_ENUM isSuccess) {
- String additionalInfo = "";
- String protocol = "HTTP";
- String loginId = MDC.get("LoginId");
- additionalInfo = String.format("Rest API=%s, Rest Method=%s, App-Name=%s, Request-URL=%s",
- MDC.get(SystemProperties.MDC_REST_PATH), MDC.get(SystemProperties.MDC_REST_METHOD),
- MDC.get(SystemProperties.MDC_APPNAME), MDC.get(Configuration.MDC_REMOTE_HOST));
-
- logger.info(EELFLoggerDelegate.auditLogger, AuditLogFormatter.getInstance().createMessage(
- protocol, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE.name(), loginId, SystemProperties.SERVICE_NAME,
- isSuccess.name(), additionalInfo));
- }
- /**/
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service.support;
-
-
-import org.openecomp.portalsdk.core.FusionObject;
-
-public class FusionService implements FusionObject {
- /** Logger for this class and subclasses */
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service.support;
-
-import javax.naming.directory.DirContext;
-
-
-public interface ServiceLocator {
- DirContext getDirContext(String initialContextFactory, String providerUrl, String securityPrincipal);
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.service.support;
-
-import java.util.*;
-
-import javax.naming.*;
-import javax.naming.directory.*;
-import javax.naming.ldap.*;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.stereotype.Service;
-
-/**
- * This class implements the J2EE service locator pattern. It provides lookup
- * facilities for various services. Currenttly LDAP (pre-v3) is supported
- */
-@Service("serviceLocator")
-public class ServiceLocatorImpl implements ServiceLocator {
-
- //private static ServiceLocator locator; // The singleton instance
-
- private Context context; // JNDI context (not currently in use)
- private Context rootContext; // Java env root context (not currently in use)
- private DirContext dirContext; // LDAP DIR context
- private InitialLdapContext ldapContext; // LDAP context LDAPv3-style (not currently in use)
-
-
- // cannot directly instantiate
- public ServiceLocatorImpl() {}
-
- /*public static ServiceLocator getLocator() {
- if (locator == null)
- locator = new ServiceLocator();
- return locator;
- }
-
- public Object clone() throws CloneNotSupportedException {
- throw new CloneNotSupportedException();
- }*/
-
-
- // Get an LDAP directory context
- public DirContext getDirContext(String initialContextFactory, String providerUrl, String securityPrincipal) {
-
- if (dirContext == null) {
-
- Properties properties = new Properties();
- properties.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
- properties.put(Context.PROVIDER_URL, providerUrl);
- properties.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
-
- try {
- dirContext = new InitialDirContext(properties);
- }
- catch (NamingException ne) {
- logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while creating an Initial Directory Context: " + ne.getMessage());
- logger.error(EELFLoggerDelegate.errorLogger, "Explanation: " + ne.getExplanation());
- }
- }
-
- return dirContext;
- }
-
- // Get an LDAP directory context - LDAPv3-style
- /*public InitialLdapContext getLdapContext() { //throws NamingException {
- if (ldapContext == null) {
- Properties properties = new Properties();
- // @todo - need to parameterize context factoy class and url
- properties.put(Context.INITIAL_CONTEXT_FACTORY, AttLdap.DIR_INITIAL_CONTEXT_FACTORY);
- properties.put(Context.PROVIDER_URL, AttLdap.DIR_PROVIDER_URL);
- properties.put(Context.SECURITY_PRINCIPAL, AttLdap.DIR_SECURITY_PRINCIPAL);
- Control[] ctrl = null;
- try {
- ldapContext = new InitialLdapContext(properties, ctrl);
- }
- catch (NamingException ne) {
- // MJ FIX log exception?
- }
- }
- return ldapContext;
- }*/
-
-
- /** Logger for this class and subclasses */
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ServiceLocatorImpl.class);
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.util;
-
-import org.openecomp.portalsdk.core.objectcache.jcs.JCSCacheManager;
-import org.springframework.context.annotation.Configuration;
-@Configuration
-public class CacheManager extends JCSCacheManager {
- public CacheManager() {
-
- }
-
- /* The following can be customized for your application to cache the appropriate data upon application startup. The provided
- example retrieves a list of sample lookup data and puts the list in the Cache Manager. To retrieve that data, simply call the
- Cache Manager's getObject(String key) method which will return an Object instance. To put additional data in the Cache Manager
- outside of application startup, call the Cache Manager's putObject(String key, Object objectToCache) method. */
- public void loadLookUpCache() {
- /*
- List<Role> result = (List<Role>)getDataAccessService().getList(Role.class,null);
-
- if (result != null) {
- putObject("lookupRoles", result);
- }*/
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.util;
-import java.security.AlgorithmParameters;
-import java.security.SecureRandom;
-
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactory;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.PBEKeySpec;
-import javax.crypto.spec.SecretKeySpec;
-
-import org.apache.commons.codec.binary.Base64;
-
-public class EncDecUtilTest {
-
- private static final String password = "test";
- private static final String salt = "r n�HN~�\ 6�\1a|\bf��X\1d�" ;
- private static int pswdIterations = 65536 ;
- private static int keySize = 256;
- private byte[] ivBytes;
-
- public String encrypt(String plainText) throws Exception {
-
- //get salt
- //salt = generateSalt();
- byte[] saltBytes = salt.getBytes("UTF-8");
-
- // Derive the key
- SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
- PBEKeySpec spec = new PBEKeySpec(
- password.toCharArray(),
- saltBytes,
- pswdIterations,
- keySize
- );
-
- SecretKey secretKey = factory.generateSecret(spec);
- SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
-
- //encrypt the message
- Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
- cipher.init(Cipher.ENCRYPT_MODE, secret);
- AlgorithmParameters params = cipher.getParameters();
- ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
- byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
- return new Base64().encodeAsString(encryptedTextBytes);
- }
-
- @SuppressWarnings("static-access")
- public String decrypt(String encryptedText) throws Exception {
-
- byte[] saltBytes = salt.getBytes("UTF-8");
- byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText);
-
- // Derive the key
- SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
- PBEKeySpec spec = new PBEKeySpec(
- password.toCharArray(),
- saltBytes,
- pswdIterations,
- keySize
- );
-
- SecretKey secretKey = factory.generateSecret(spec);
- SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
-
- // Decrypt the message
- Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
- cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));
-
-
- byte[] decryptedTextBytes = null;
- try {
- decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
- } catch (IllegalBlockSizeException e) {
- e.printStackTrace();
- } catch (BadPaddingException e) {
- e.printStackTrace();
- }
-
- return new String(decryptedTextBytes);
- }
-
- public String generateSalt() {
- SecureRandom random = new SecureRandom();
- byte bytes[] = new byte[20];
- random.nextBytes(bytes);
- String s = new String(bytes);
- return s;
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.util;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.openecomp.portalsdk.core.domain.User;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-public class JSONUtil {
- public static String convertResponseToJSON(String response) throws JsonProcessingException{
- ObjectMapper mapper = new ObjectMapper();
- Map<String, String> responseMap = new HashMap<String, String>();
- responseMap.put("response", response);
- response = mapper.writeValueAsString(responseMap);
- return response;
- }
-
- public static User mapToDomainUser(User domainUser, User editUser) {
- domainUser.setOrgId(editUser.getOrgId());
- domainUser.setManagerId(editUser.getManagerId());
- domainUser.setFirstName(editUser.getFirstName());
- domainUser.setMiddleInitial(editUser.getMiddleInitial());
- domainUser.setLastName(editUser.getLastName());
- domainUser.setPhone(editUser.getPhone());
- domainUser.setEmail(editUser.getEmail());
- domainUser.setHrid(editUser.getHrid());
- domainUser.setOrgUserId(editUser.getOrgUserId());
- domainUser.setOrgCode(editUser.getOrgCode());
- domainUser.setOrgManagerUserId(editUser.getOrgManagerUserId());
- domainUser.setJobTitle(editUser.getJobTitle());
- domainUser.setLoginId(editUser.getLoginId());
- domainUser.setActive(editUser.getActive());
- return domainUser;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.util;
-
-import javax.servlet.ServletContext;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.PropertySource;
-import org.springframework.core.env.Environment;
-
-/**
- * SystemProperties contains a list of constants used throughout portions of the
- * application. Populated by Spring from multiple configuration files.
- *
- * Should be used like this:
- *
- * <pre>
- *
- * @Autowired
- * SystemProperties systemProperties;
- * </pre>
- */
-@Configuration
-@PropertySource(value = { "${container.classpath:}/WEB-INF/conf/system.properties",
- "${container.classpath:}/WEB-INF/fusion/conf/fusion.properties",
- "${container.classpath:}/WEB-INF/conf/sql.properties" })
-public class SystemProperties {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SystemProperties.class);
-
- private static Environment environment;
-
- private ServletContext servletContext;
-
- public SystemProperties() {
- }
-
- protected Environment getEnvironment() {
- return environment;
- }
-
- @Autowired
- public void setEnvironment(Environment environment) {
- SystemProperties.environment = environment;
- }
-
- public ServletContext getServletContext() {
- return servletContext;
- }
-
- public void setServletContext(ServletContext servletContext) {
- this.servletContext = servletContext;
- }
-
- /**
- * Tests whether a property value is available for the specified key.
- *
- * @param key Property key
- * @return True if the key is known, otherwise false.
- */
- public static boolean containsProperty(String key) {
- return environment.containsProperty(key);
- }
-
- /**
- * Returns the property value associated with the given key (never
- * {@code null}), after trimming any trailing space.
- *
- * @param key
- * Property key
- * @return Property value; the empty string if the environment was not
- * autowired, which should never happen.
- * @throws IllegalStateException
- * if the key cannot be resolved
- */
- public static String getProperty(String key) {
- String value = "";
- if (environment == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "getProperty: environment is null, should never happen!");
- }
- else {
- value = environment.getRequiredProperty(key);
- // java.util.Properties preserves trailing space
- if (value != null)
- value = value.trim();
- }
- return value;
- }
-
- /**
- * Gets the property value for the key {@link #APPLICATION_NAME}.
- *
- * method created to get around JSTL 1.0 limitation of not being able to
- * access a static method of a bean
- *
- * @return Application name
- */
- public String getApplicationName() {
- return getProperty(APPLICATION_NAME);
- }
-
- /**
- * Gets the property value for the key {@link #APP_DISPLAY_NAME}.
- *
- * @return Application display name
- */
- public String getAppDisplayName() {
- return getProperty(APP_DISPLAY_NAME);
- }
-
- // keys used to reference values in the system properties file
- public static final String DOMAIN_CLASS_LOCATION = "domain_class_location";
- public static final String DEFAULT_ERROR_MESSAGE = "default_error_message";
-
- public static final String CSP_COOKIE_NAME = "csp_cookie_name";
- public static final String CSP_GATE_KEEPER_DATA_KEY = "csp_gate_keeper_data_key";
- public static final String CSP_GATE_KEEPER_PROD_KEY = "csp_gate_keeper_prod_key";
- public static final String CSP_LOGIN_URL = "csp_login_url";
- public static final String CSP_LOGOUT_URL = "csp_logout_url";
-
- public static final String WEB_JUNCTION_USER_ID_HEADER_NAME = "web_junction_user_id_header_name";
-
- public static final String AUTHENTICATION_MECHANISM = "authentication_mechanism";
-
- public static final String APPLICATION_NAME = "application_name";
- public static final String HIBERNATE_CONFIG_FILE_PATH = "hibernate_config_file_path";
- public static final String APPLICATION_USER_ID = "application_user_id";
-
- public static final String POST_INITIAL_CONTEXT_FACTORY = "post_initial_context_factory";
- public static final String POST_PROVIDER_URL = "post_provider_url";
- public static final String POST_SECURITY_PRINCIPAL = "post_security_principal";
- public static final String POST_MAX_RESULT_SIZE = "post_max_result_size";
- public static final String POST_DEFAULT_ROLE_ID = "post_default_role_id";
-
- public static final String FILES_PATH = "files_path";
- public static final String TEMP_PATH = "temp_path";
-
- public static final String NUM_UPLOAD_FILES = "num_upload_files";
-
- public static final String SYS_ADMIN_ROLE_ID = "sys_admin_role_id";
-
- public static final String SYS_ADMIN_ROLE_FUNCTION_DELETE_FROM_UI = "sys_admin_role_function_delete_from_ui";
- public static final String USER_NAME = "user_name";
- public static final String FIRST_NAME = "first_name";
- public static final String LAST_NAME = "last_name";
- public static final String APP_DISPLAY_NAME = "app_display_name";
- // Application base URL is a proper prefix of the on-boarding URL
- public static final String APP_BASE_URL = "app_base_url";
-
- public static final String MENU_PROPERTIES_FILE_LOCATION = "menu_properties_file_location";
- public static final String MENU_QUERY_NAME = "menu_query_name";
- public static final String APPLICATION_MENU_SET_NAME = "application_menu_set_name";
- public static final String APPLICATION_MENU_ATTRIBUTE_NAME = "application_menu_attribute_name";
- public static final String APPLICATION_MENU_PROPERTIES_NAME = "application_menu_properties_name";
- public static final String BUSINESS_DIRECT_MENU_SET_NAME = "business_direct_menu_set_name";
- public static final String BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME = "business_direct_menu_attribute_name";
- public static final String BUSINESS_DIRECT_MENU_PROPERTIES_NAME = "business_direct_menu_properties_name";
- public static final String RAPTOR_CONFIG_FILE_PATH = "raptor_config_file_path";
- public static final String HOMEPAGE_DATA_CALLBACK_CLASS = "homepage_data_callback_class";
- public static final String ERROR_EMAIL_DISTRIBUTION = "error_email_distribution";
- public static final String ERROR_EMAIL_SOURCE_ADDRESS = "error_email_source_address";
- public static final String ERROR_EMAIL_SUBJECT_LINE = "error_email_subject_line";
- public static final String PROFILE_SEARCH_REPORT_ID = "profile_search_report_id";
- public static final String CALLABLE_PROFILE_SEARCH_REPORT_ID = "callable_profile_search_report_id";
- public static final String CLUSTERED = "clustered";
-
- public static final String USER_ATTRIBUTE_NAME = "user_attribute_name";
- public static final String ROLES_ATTRIBUTE_NAME = "roles_attribute_name";
- public static final String ROLE_FUNCTIONS_ATTRIBUTE_NAME = "role_functions_attribute_name";
- public static final String CLIENT_DEVICE_ATTRIBUTE_NAME = "client_device_attribute_name";
- public static final String CLIENT_DEVICE_EMULATION = "client_device_emulation";
- public static final String CLIENT_DEVICE_TYPE_TO_EMULATE = "client_device_type_to_emulate";
- // File generation - Document
- public static final String TEMPLATES_PATH = "templates_path";
- public static final String DOCUMENT_XML_ENCODING = "document_xml_encoding";
-
- // Transaction
- public static final String ROUTING_DATASOURCE_KEY = "routing_datasource_key";
-
- // Document Library keys
- public static final String DOCLIB_ADMIN_ROLE_ID = "doclib_admin_role_id";
- public static final String DOCLIB_USER_ROLE_ID = "doclib_user_role_id";
-
- public static final String SYSTEM_PROPERTIES_FILENAME = "system.properties";
- public static final String FUSION_PROPERTIES_FILENAME = "fusion.properties";
- public static final String SUCCESS_TASKS_PROPERTIES_FILENAME = "success_tasks.properties";
-
- // login methods
- public static final String LOGIN_METHOD_CSP = "login_method_csp";
- public static final String LOGIN_METHOD_WEB_JUNCTION = "login_method_web_junction";
- public static final String LOGIN_METHOD_BACKDOOR = "login_method_backdoor";
- public static final String LOGIN_METHOD_ATTRIBUTE_NAME = "login_method_attribute_name";
- public static final String ROLE_FUNCTION_LIST = "role_function_list";
-
-
- // login error message keys
- public static final String MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY = "login.error.hrid.empty";
- public static final String MESSAGE_KEY_LOGIN_ERROR_HEADER_EMPTY = "login.error.header.empty";
- public static final String MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE = "login.error.user.inactive";
- public static final String MESSAGE_KEY_LOGIN_ERROR_USER_NOT_FOUND = "login.error.hrid.not-found";
- public static final String MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED = "login.error.application.locked";
- public static final String MESSAGE_KEY_AUTOLOGIN_NONE = "webphone.autoimport.nouser";
- public static final String MESSAGE_KEY_AUTOLOGIN_MULTIPLE = "webphone.autoimport.multiple";
-
- // Application Mobile capability
- public static final String MOBILE_ENABLE = "mobile_enable";
-
- public static final String DATABASE_TIME_ZONE = "db.time_zone";
-
- public static final String AUTO_USER_IMPORT_ENABLE = "auto_user_import_enable";
- public static final String AUTO_USER_IMPORT_ROLE = "auto_user_import_role";
-
- public static final String ITRACKER_EMAIL_SOURCE_ADDRESS = "itracker_email_source_address";
- public static final String ITRACKER_EMAIL_DISTRIBUTION = "itracker_email_distribution";
- public static final String ITRACKER_SYSTEM_USER = "itracker_system_user_id";
-
- public static final String MAIL_SERVER_HOST = "mail_server_host";
- public static final String MAIL_SERVER_PORT = "mail_server_port";
-
- // Routing Data Source keys
- public static final String ROUTING_DATASOURCE_KEY_NON_XA = "NON-XA";
- public static final String ROUTING_DATASOURCE_KEY_XA = "XA";
- public static final String QUARTZ_JOB_ENABLED = "quartz_job_enable";
- public static final String WORKFLOW_EMAIL_SENDER = "workflow_email_sender";
- public static final String DROOLS_GUVNOR_HOME = "drools.guvnor.home";
-
- // Hibernate Config
- public static final String HB_DIALECT = "hb.dialect";
- public static final String HB_SHOW_SQL = "hb.show_sql";
- public static final String IDLE_CONNECTION_TEST_PERIOD = "hb.idle_connection_test_period";
-
- // DataSource
- public static final String DB_DRIVER = "db.driver";
- public static final String DB_CONNECTIONURL = "db.connectionURL";
- public static final String DB_USERNAME = "db.userName";
- /** @deprecated this variable is used in many places so don't remove */
- public static final String DB_PASSWOR = "db.password";
- public static final String DB_PASSWORD = "db.password";
- public static final String DB_MIN_POOL_SIZE = "db.min_pool_size";
- public static final String DB_MAX_POOL_SIZE = "db.max_pool_size";
- public static final String TEST_CONNECTION_ON_CHECKOUT = "db.test_connection_on_checkout";
- public static final String PREFERRED_TEST_QUERY = "db.preferred_test_query";
-
- public static final String MYLOGINS_FEED_CRON = "mylogins_feed_cron";
- public static final String SESSIONTIMEOUT_FEED_CRON = "sessiontimeout_feed_cron";
- public static final String LOG_CRON = "log_cron";
-
- public static final String DB_ENCRYPT_FLAG = "db.encrypt_flag";
-
- // Decryption Key
- public static final String Decryption_Key = "decryption_key";
-
- // Logging/Audit Fields
- public static final String MDC_APPNAME = "AppName";
- public static final String MDC_REST_PATH = "RestPath";
- public static final String MDC_REST_METHOD = "RestMethod";
- public static final String INSTANCE_UUID = "instance_uuid";
- public static final String MDC_CLASS_NAME = "ClassName";
- public static final String MDC_LOGIN_ID = "LoginId";
- public static final String MDC_TIMER = "Timer";
- public static final String SDK_NAME = "ECOMP_SDK";
- public static final String ECOMP_REQUEST_ID = "X-ECOMP-RequestID";
- public static final String PARTNER_NAME = "PartnerName";
- public static final String FULL_URL = "Full-URL";
- public static final String AUDITLOG_BEGIN_TIMESTAMP = "AuditLogBeginTimestamp";
- public static final String AUDITLOG_END_TIMESTAMP = "AuditLogEndTimestamp";
- public static final String METRICSLOG_BEGIN_TIMESTAMP = "MetricsLogBeginTimestamp";
- public static final String METRICSLOG_END_TIMESTAMP = "MetricsLogEndTimestamp";
- public static final String CLIENT_IP_ADDRESS = "ClientIPAddress";
- public static final String STATUS_CODE = "StatusCode";
- public static final String RESPONSE_CODE = "ResponseCode";
- // Component or sub component name
- public static final String TARGET_ENTITY = "TargetEntity";
- // API or operation name
- public static final String TARGET_SERVICE_NAME = "TargetServiceName";
-
- // Logging Compliance
- public static final String DOUBLE_WHITESPACE_SEPARATOR = " ";
- public static final String SINGLE_WHITESPACE_SEPARATOR = " ";
- public static final String SINGLE_QUOTE = "'";
- public static final String NA = "N/A";
- public static final String UNKNOWN = "Unknown";
- public static final String SECURITY_LOG_TEMPLATE = "Protocol:{0} Security-Event-Type:{1} Login-ID:{2} {3}";
- public static final String ECOMP_PORTAL_BE = "ECOMP_PORTAL_BE";
- public static final String PROTOCOL = "PROTOCOL";
- public static final String SECURIRY_EVENT_TYPE = "SECURIRY_EVENT_TYPE";
- public static final String LOGIN_ID = "LOGIN_ID";
- public static final String ACCESSING_CLIENT = "ACCESSING_CLIENT";
- public static final String RESULT_STR = "RESULT";
- public static final String ECOMP_PORTAL_FE = "ECOMP_PORTAL_FE";
- public static final String ADDITIONAL_INFO = "ADDITIONAL_INFO";
- public static final String INTERFACE_NAME = "INTERFACE_NAME";
- public static final String USERAGENT_NAME = "user-agent";
-
- // Protocols
- public static final String HTTP = "HTTP";
- public static final String HTTPS = "HTTPS";
- public static final String SSO_VALUE = "sso";
-
- public enum RESULT_ENUM {
- SUCCESS, FAILURE
- }
-
- public enum SecurityEventTypeEnum {
- FE_LOGIN_ATTEMPT, FE_LOGOUT, SSO_LOGIN_ATTEMPT_PHASE_1, SSO_LOGIN_ATTEMPT_PHASE_2, SSO_LOGOUT, LDAP_PHONEBOOK_USER_SEARCH, INCOMING_REST_MESSAGE, OUTGOING_REST_MESSAGE, REST_AUTHORIZATION_CREDENTIALS_MODIFIED, ECOMP_PORTAL_USER_MODIFIED, ECOMP_PORTAL_USER_ADDED, ECOMP_PORTAL_USER_REMOVED, ECOMP_PORTAL_WIDGET, INCOMING_UEB_MESSAGE, ECOMP_PORTAL_HEALTHCHECK
- }
-
- // Menu
- public static final String CONTACT_US_LINK = "contact_us_link";
-
- // Left Menu
- public static final String LEFT_MENU_PARENT = "parentList";
- public static final String LEFT_MENU_CHILDREND = "childItemList";
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.util;
-
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-
-import javax.servlet.http.HttpSession;
-
-import org.openecomp.portalsdk.core.command.UserRowBean;
-import org.openecomp.portalsdk.core.domain.User;
-
-public class UsageUtils {
- @SuppressWarnings("rawtypes")
- public static ArrayList<UserRowBean> getActiveUsers(HashMap activeUsers) {
- ArrayList<UserRowBean> rows = new ArrayList<UserRowBean>();
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
-
- for(Iterator i = activeUsers.keySet().iterator(); i.hasNext(); ){
- String sessionId = (String)i.next();
- HttpSession session = (HttpSession)activeUsers.get(sessionId);
- User userBean = (User)session.getAttribute("user");
- //
- // Not all sessions will be valid logins
- // Skip those ones
- //
- if(null == userBean)
- continue;
-
- UserRowBean userRow = new UserRowBean();
- userRow.setFirstName(userBean.getFirstName());
- userRow.setLastName(userBean.getLastName());
- userRow.setEmail(userBean.getEmail());
- userRow.setId(userBean.getId());
- userRow.setSessionId(sessionId);
- userRow.setLoginTime(sdf.format(new Date(session.getCreationTime())));
- userRow.setLastLoginTime(sdf.format(userBean.getLastLoginDate()));
-
- //
- // Calculate the last time and time remaining for these sessions.
- //
- int sessionLength = session.getMaxInactiveInterval();
- long now = new java.util.Date().getTime();
- long lastAccessed = (now - session.getLastAccessedTime()) / 1000;
- long lengthInactive = (now - session.getLastAccessedTime());
- long minutesRemaining = sessionLength - (lengthInactive / 1000);
-
- userRow.setLastAccess((lastAccessed / 60) + ":" + String.format("%02d", (lastAccessed % 60)));
- userRow.setRemaining((minutesRemaining / 60) + ":" + String.format("%02d", (minutesRemaining % 60)));
-
- rows.add(userRow);
- }
-
- return rows;
- }
-
- @SuppressWarnings("rawtypes")
- public static ArrayList<UserRowBean> getActiveUsersAfterDelete(HashMap activeUsers, final java.lang.Object data) {
- return getActiveUsers(deleteSession(activeUsers,data));
-
- }
-
- @SuppressWarnings("rawtypes")
- private static HashMap deleteSession(HashMap activeUsers, Object data) {
- String sessionId = ((UserRowBean)data).getSessionId();
- HttpSession session = (HttpSession)activeUsers.get(sessionId);
- session.invalidate();
- activeUsers.remove(sessionId);
-
- return activeUsers;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.util;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.Map;
-
-import org.yaml.snakeyaml.Yaml;
-import org.yaml.snakeyaml.representer.Representer;
-
-public class YamlUtils {
-
- static Yaml yaml;
-
- static {
-
- Representer representer = new Representer();
- //representer.addClassTag(Domain.class, Tag.MAP);
-
-
- yaml = new Yaml(representer);
-
- }
-
- public static void writeYamlFile(String filePath, String fileName,
- Map<String, Object> model) throws IOException {
- FileWriter writer = new FileWriter(filePath + File.separator + fileName);
- yaml.dump(model, writer);
- writer.close();
- }
-
- public static String returnYaml(
- Map<String, Object> model) throws IOException {
-
- return yaml.dump(model);
-
- }
-
- @SuppressWarnings("unchecked")
- public static Map<String, Object> readYamlFile(
- String filePath, String fileName) throws FileNotFoundException,
- IOException {
- FileReader reader = new FileReader(filePath + File.separator + fileName);
-
- Map<String,Object> callFlowBs = (Map<String,Object>)yaml.load(reader);
- reader.close();
- return callFlowBs;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.web.socket;
-
-import java.io.IOException;
-import java.util.Hashtable;
-import java.util.Map;
-
-import javax.websocket.OnClose;
-import javax.websocket.OnMessage;
-import javax.websocket.OnOpen;
-import javax.websocket.Session;
-import javax.websocket.server.ServerEndpoint;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@ServerEndpoint("/contact")
-public class PeerBroadcastSocket {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PeerBroadcastSocket.class);
-
- public static Map<String, Object> channelMap = new Hashtable<String, Object>();
- public Map<String, String> sessionMap = new Hashtable<String, String>();
- ObjectMapper mapper = new ObjectMapper();
-
- @OnMessage
- public void message(String message, Session session) {
- try {
- // JSONObject jsonObject = new JSONObject(message);
- @SuppressWarnings("unchecked")
- Map<String, Object> jsonObject = mapper.readValue(message, Map.class);
- try {
- Object from = jsonObject.get("from");
- if (from != null) {
- channelMap.put(from.toString(), session);
- sessionMap.put(session.getId(), from.toString());
- }
- } catch (Exception je) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed to read value" + je.getMessage());
- }
-
- try {
- Object to = jsonObject.get("to");
- if (to == null)
- return;
- Object toSessionObj = channelMap.get(to);
- if (toSessionObj != null) {
- Session toSession = null;
- toSession = (Session) toSessionObj;
- toSession.getBasicRemote().sendText(message);
- }
-
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed to send text" + ex.getMessage());
- }
-
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed" + ex.getMessage());
- }
-
- }
-
- @OnOpen
- public void open(Session session) {
- logger.info(EELFLoggerDelegate.debugLogger, "Channel opened");
- }
-
- @OnClose
- public void close(Session session) {
- String channel = sessionMap.get(session.getId());
- if (channel != null) {
- Object sessObj = channelMap.get(channel);
- if (sessObj != null) {
- try {
- ((Session) sessObj).close();
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed to close" + e.getMessage());
- }
- }
- channelMap.remove(channel);
- }
- logger.info(EELFLoggerDelegate.debugLogger, "Channel closed");
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.web.socket;
-
-import java.util.Hashtable;
-import java.util.Map;
-
-import javax.websocket.OnClose;
-import javax.websocket.OnMessage;
-import javax.websocket.OnOpen;
-import javax.websocket.Session;
-import javax.websocket.server.ServerEndpoint;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@ServerEndpoint("/webrtc")
-public class WebRTCSocket {
-
-
- public static Map<String,Hashtable<String,Object[]>> channelMap = new Hashtable<String,Hashtable<String,Object[]>>();
- public Map<String,String> sessionMap = new Hashtable<String,String>();
- ObjectMapper mapper = new ObjectMapper();
-
-
- @OnMessage
- public void message(String message, Session session) {
- try {
- //JSONObject jsonObject = new JSONObject(message);
- @SuppressWarnings("unchecked")
- Map<String,Object> jsonObject = mapper.readValue(message, Map.class);
- try {
- Object isOpen = jsonObject.get("open");
- if(isOpen != null && (Boolean)isOpen == true) {
- String channel = (String) jsonObject.get("channel");
- Object value = channelMap.get(channel);
- Hashtable<String,Object[]> sourceDestMap = null;
- if(value == null)
- sourceDestMap = new Hashtable<String,Object[]>();
- else
- sourceDestMap = (Hashtable<String,Object[]>) value;
-
- sourceDestMap.put(session.getId(), new Object[]{session});
- channelMap.put(channel, sourceDestMap);
- sessionMap.put(session.getId(), channel);
-
-
- }
- }
- catch (Exception je) {
- je.printStackTrace();
- }
-
- try{
-
- Object dataObj = jsonObject.get("data");
- if(dataObj == null)
- return;
- Map<String,Object> dataMapObj = ( Map<String,Object>)dataObj;
- //Object thisUserId = dataMapObj.get("userid");
- String channel = null;
- try{
- Object channelObj = dataMapObj.get("sessionid");
- if(channelObj != null)
- channel = (String) channelObj;
- else
- channel = (String) jsonObject.get("channel");
- }
- catch(Exception json) {
- json.printStackTrace();
- }
-
- /*
- JSONObject dataMapObj = (JSONObject)dataObj;
- Object thisUserId = dataMapObj.get("userid");
- String channel = (String) dataMapObj.get("sessionid");
- Hashtable<String,Object> sourceDestMap = sessionMap.get(channel);
-
- if(thisUserId != null && sourceDestMap.get((String)thisUserId) == null) {
- sourceDestMap.put((String)thisUserId, new Object[] {message, session});
- }
-
- for(String userId : sourceDestMap.keySet()){
- if(!userId.equals(thisUserId)) {
- Session otherSession = (Session) ((Object[])sourceDestMap.get(userId))[1];
- otherSession.getBasicRemote().sendText(message);
- }
- }
- */
-
- Hashtable<String,Object[]> sourceDestMap = channelMap.get(channel);
- if(sourceDestMap != null)
- for(String id : sourceDestMap.keySet()){
- if(!id.equals(session.getId())) {
- Session otherSession = (Session) ((Object[])sourceDestMap.get(id))[0];
- if(otherSession.isOpen())
- otherSession.getBasicRemote().sendText(mapper.writeValueAsString(dataObj));
- }
-
- }
- }
- catch (Exception je) {
- je.printStackTrace();
- }
-
- }
- catch (Exception je) {
- je.printStackTrace();
- }
- //System.out.println("Message received:" + message);
- }
-
- @OnOpen
- public void open(Session session) {
- // System.out.println("Channel opened");
- }
-
- @OnClose
- public void close(Session session) {
- String channel = sessionMap.get(session.getId());
- if (channel != null) {
- channelMap.remove(channel);
- }
- // System.out.println("Channel closed");
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.web.support;
-
-import java.io.File;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-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 javax.sql.DataSource;
-
-import org.hibernate.Session;
-import org.openecomp.portalsdk.core.exception.SessionExpiredException;
-import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.core.io.FileSystemResource;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-import org.springframework.util.StringUtils;
-
-
-public class AppUtils {
-
-
-
- private static DataAccessService dataAccessService;
-
- private static AbstractCacheManager cacheManager;
-
- private static boolean applicationLocked;
-
- private static Hashtable feedback = new Hashtable();
-
- private static DataSource datasource;
-
- public static DataSource getDatasource() {
- return datasource;
- }
-
- @Autowired
- public void setDatasource(DataSource datasource) {
- AppUtils.datasource = datasource;
- }
-
- public AppUtils() {
- }
-
- public static HttpSession getSession(HttpServletRequest request) {
- HttpSession session = null;
- if (request != null) {
- session = request.getSession(false);
- if (session == null) {
- throw new SessionExpiredException();
- }
- } else {
- throw new SessionExpiredException();
- }
- return session;
- }
-
- public static List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy) {
- return getLookupList(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null);
- } // getLookupList
-
- public static List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, Session session) {
- String cacheKey = dbTable + "|" + dbValueCol + "|" + dbLabelCol + "|" + dbFilter + "|" + dbOrderBy;
- List list = getLookupListFromCache(cacheKey);
- if (list == null) {
- list = getDataAccessService().getLookupList(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null);
- if (list != null) {
- addLookupListToCache(cacheKey, list);
- }
- } // if
- return list;
- } // getLookupList
-
- private static List getLookupListFromCache(String key) {
- return (List)getObjectFromCache(key);
- } // getLookupListFromCache
-
- public static Object getObjectFromCache(String key) {
- if (isCacheManagerAvailable()) {
- return getCacheManager().getObject(key);
- } else {
- return null;
- }
- } // getObjectFromCache
-
- private static void addLookupListToCache(String key, List list) {
- addObjectToCache(key, list);
- } // addLookupListToCache
-
- public static void addObjectToCache(String key, Object o) {
- if (isCacheManagerAvailable()) {
- getCacheManager().putObject(key, o);
- }
- } // addObjectToCache
-
- @Autowired
- public void setCacheManager(AbstractCacheManager cacheManager) {
- this.cacheManager = cacheManager;
- }
-
- public static AbstractCacheManager getCacheManager() {
- return cacheManager;
- }
-
- public static boolean isCacheManagerAvailable() {
- return (getCacheManager() != null);
- }
-
- public void setFeedback(Hashtable feedback) {
- this.feedback = feedback;
- }
-
- public static boolean isApplicationLocked() {
- return applicationLocked;
- }
-
- public static DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- @Autowired
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- public static void setApplicationLocked(boolean locked) {
- applicationLocked = locked;
- }
-
- public static String getLookupValueByLabel(String label, String dbTable, String dbValueCol, String dbLabelCol) {
- if (label == null || label.equals("")) {
- return "";
- }
-
- List<org.openecomp.portalsdk.core.domain.Lookup> lstResult = getLookupListNoCache(dbTable, dbValueCol, dbLabelCol, dbLabelCol + "='" + label.replaceAll("'", "''") + "'", "");
- if (lstResult == null) {
- return "";
- }
- if (lstResult.size() > 0) {
- return ((org.openecomp.portalsdk.core.domain.Lookup)lstResult.toArray()[0]).getValue();
- } else {
- return "";
- }
- }
-
- public static String getLookupValueByLabel(String label, List lookupList) {
- Iterator i = null;
-
- if (label == null || label.equalsIgnoreCase("")) {
- return "";
- }
-
- if (lookupList == null || lookupList.size() == 0) {
- return "";
- }
-
- i = lookupList.iterator();
- while (i.hasNext()) {
- org.openecomp.portalsdk.core.domain.Lookup lookup = (org.openecomp.portalsdk.core.domain.Lookup)i.next();
-
- if (lookup.getLabel().equals(label)) {
- return lookup.getValue();
- }
- }
-
- return "";
-}
- public static List getLookupListNoCache(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy) {
- return getLookupListNoCache(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null);
- } // getLookupListNoCache
-
-
- public static List getLookupListNoCache(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, Session session) {
- return getDataAccessService().getLookupList(dbTable, dbValueCol, dbLabelCol, dbFilter, dbOrderBy, null);
- } // getLookupListNoCache
-
-
-
-} // AppUtils
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.web.support;
-
-public interface ControllerProperties {
-
- static final String TASK_GET = "get";
- static final String TASK_DELETE = "delete";
- static final String TASK_SAVE = "save";
- static final String TASK_PROCESS = "process";
- static final String TASK_TOGGLE_ACTIVE = "toggleActive";
- static final String TASK_DOWNLOAD = "download";
- static final String TASK_POPUP = "popup";
- static final String TASK_LOOKUP = "lookup";
- static final String TASK_ADD_ROW = "addRow";
- static final String TASK_APPROVE = "approve";
- static final String TASK_REJECT = "reject";
- static final String TASK_RESET = "reset";
- static final String TASK_ASSIGN = "assign";
- static final String TASK_CUT = "cut";
- static final String TASK_COPY = "copy";
- static final String TASK_PASTE = "paste";
- static final String TASK_SELECT = "select";
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.web.support;
-
-public class FeedbackMessage {
-
- private String message;
- private int messageType;
- private boolean keyed;
-
- public static final int MESSAGE_TYPE_ERROR = 10;
- public static final int MESSAGE_TYPE_WARNING = 20;
- public static final int MESSAGE_TYPE_INFO = 30;
- public static final int MESSAGE_TYPE_SUCCESS = 40;
-
- public static final String DEFAULT_MESSAGE_SUCCESS = "Update successful.";
- public static final String DEFAULT_MESSAGE_ERROR = "An error occurred while processing the request: ";
-
- public static final String DEFAULT_MESSAGE_SYSTEM_ADMINISTRATOR = "If the problem persists, please contact your Administrator.";
-
- public FeedbackMessage() {
- }
-
- public FeedbackMessage(String message) {
- this(message, MESSAGE_TYPE_ERROR);
- }
-
- public FeedbackMessage(String message, int messageType) {
- this(message, messageType, false);
- }
-
- public FeedbackMessage(String message, int messageType, boolean keyed) {
- this.message = message;
- this.messageType = messageType;
- this.keyed = keyed;
- }
-
- public String getMessage() {
- return message;
- }
-
- public int getMessageType() {
- return messageType;
- }
-
- public boolean isKeyed() {
- return keyed;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public void setMessageType(int messageType) {
- this.messageType = messageType;
- }
-
- public void setKeyed(boolean keyed) {
- this.keyed = keyed;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.web.support;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-public class JsonMessage {
-
- private String data;
- private String data2;
- private String data3;
- public JsonMessage(String data) {
- super();
- this.data = data;
- }
- public JsonMessage(String data,String data2) {
- super();
- this.data = data;
- this.data2 = data2;
- }
-
- public JsonMessage(String data,String data2,String data3) {
- super();
- this.data = data;
- this.data2 = data2;
- this.data3 = data3;
- }
-
- public String getData() {
- return data;
- }
-
- public void setData(String data) {
- this.data = data;
- }
- public String getData2() {
- return data2;
- }
- public void setData2(String data2) {
- this.data2 = data2;
- }
- public String getData3() {
- return data3;
- }
- public void setData3(String data3) {
- this.data3 = data3;
- }
-
-
- /**
- * Builds JSON object with status + message response body.
- *
- * @param success
- * True to indicate success, false to signal failure.
- * @param msg
- * Message to include in the response object; ignored if null.
- * @return
- *
- * <pre>
- * { "status" : "ok" (or "error"), "message": "some explanation" }
- * </pre>
- */
- public static String buildJsonResponse(boolean success, String msg) {
- PortalAPIResponse response = new PortalAPIResponse(success, msg);
- String json = null;
- try {
- json = new ObjectMapper().writeValueAsString(response);
- } catch (JsonProcessingException ex) {
- // Truly should never, ever happen
- json = "{ \"status\": \"error\",\"message\":\"" + ex.toString() + "\" }";
- }
- return json;
- }
-
- /**
- * Builds JSON object with status of error and message containing stack
- * trace for the specified throwable.
- *
- * @param t
- * Throwable with stack trace to use as message
- * @return
- *
- * <pre>
- * { "status" : "error", "message": "some-big-stacktrace" }
- * </pre>
- */
- public static String buildJsonResponse(Throwable t) {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- t.printStackTrace(pw);
- return buildJsonResponse(false, sw.toString());
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.web.support;
-
-import java.util.*;
-
-public class MessagesList {
-
- private boolean successMessageDisplayed = true;
- private boolean includeCauseInCustomExceptions = false;
-
- private List successMessages;
- private List exceptionMessages;
-
- public MessagesList() {
- setExceptionMessages(new ArrayList());
- setSuccessMessages(new ArrayList());
- }
-
- public MessagesList(boolean displaySuccess) {
- this();
- setSuccessMessageDisplayed(displaySuccess);
- }
-
- public List getExceptionMessages() {
- return exceptionMessages;
- }
-
- public List getSuccessMessages() {
- return successMessages;
- }
-
- public boolean isSuccessMessageDisplayed() {
- return successMessageDisplayed;
- }
-
- public boolean isIncludeCauseInCustomExceptions() {
- return includeCauseInCustomExceptions;
- }
-
-
- public void setExceptionMessages(List exceptionMessages) {
- this.exceptionMessages = exceptionMessages;
- }
-
- public void setSuccessMessages(List successMessages) {
- this.successMessages = successMessages;
- }
-
- public void setSuccessMessageDisplayed(boolean successMessageDisplayed) {
- this.successMessageDisplayed = successMessageDisplayed;
- }
-
- public void setIncludeCauseInCustomExceptions(boolean includeCauseInCustomExceptions) {
- this.includeCauseInCustomExceptions = includeCauseInCustomExceptions;
- }
-
-
- public void addSuccessMessage(FeedbackMessage message) {
- getSuccessMessages().add(message);
- }
-
- public void addExceptionMessage(FeedbackMessage message) {
- getExceptionMessages().add(message);
- }
-
- public boolean hasExceptionMessages() {
- return!getExceptionMessages().isEmpty();
- }
-
- public boolean hasSuccessMessages() {
- return!getSuccessMessages().isEmpty();
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.web.support;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.UUID;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
-import org.openecomp.portalsdk.core.domain.Role;
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.exception.SessionExpiredException;
-import org.openecomp.portalsdk.core.lm.FusionLicenseManager;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.menu.MenuBuilder;
-import org.openecomp.portalsdk.core.restful.domain.EcompRole;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-
-@SuppressWarnings("rawtypes")
-public class UserUtils {
-
- static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserUtils.class);
-
- public static final String KEY_USER_ROLES_CACHE = "userRoles";
-
- private static DataAccessService dataAccessService;
-
- public static void setUserSession(HttpServletRequest request, User user, Set applicationMenuData,
- Set businessDirectMenuData, String loginMethod , List<RoleFunction> roleFunctionList) {
- HttpSession session = request.getSession(true);
-
- UserUtils.clearUserSession(request); // let's clear the current user
- // session to avoid any
- // conflicts during the set
-
- session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
- session.setAttribute(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME), loginMethod);
-
- getRoleFunctions(request);
-
- session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
- session.setAttribute(SystemProperties.FIRST_NAME, user.getFirstName());
- session.setAttribute(SystemProperties.LAST_NAME, user.getLastName());
- session.setAttribute(SystemProperties.ROLE_FUNCTION_LIST, roleFunctionList);
-
- ServletContext context = session.getServletContext();
- int licenseVarificationFlag = 3;
- try {
- licenseVarificationFlag = (Integer) context.getAttribute("licenseVerification");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.debugLogger, "Error while get license varification " + e.getMessage());
- }
- String displayName = "";
- if (SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) != null)
- displayName = SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME);
- switch (licenseVarificationFlag) {
- case FusionLicenseManager.DEVELOPER_LICENSE:
- session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME),
- displayName + " [Development Version]");
- break;
- case FusionLicenseManager.EXPIRED_LICENSE:
- session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME),
- displayName + " [LICENSE EXPIRED]");
- break;
- case FusionLicenseManager.VALID_LICENSE:
- session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), displayName);
- break;
- default:
- session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME),
- displayName + " [INVALID LICENSE]");
- break;
- }
-
- session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME),
- MenuBuilder.filterMenu(applicationMenuData, request));
- session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME),
- MenuBuilder.filterMenu(businessDirectMenuData, request));
- }
-
- public static void clearUserSession(HttpServletRequest request) {
- HttpSession session = AppUtils.getSession(request);
-
- if (session == null) {
- throw new SessionExpiredException();
- }
-
- // removes all stored attributes from the current user's session
- session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
- session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
- session.removeAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME));
- session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
- session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
- session.removeAttribute(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME));
- session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTION_LIST));
-
- }
-
- @SuppressWarnings("unchecked")
- public static Set getRoleFunctions(HttpServletRequest request) {
- HashSet roleFunctions = null;
-// HashSet<RoleFunction> rolefun = null;
- HttpSession session = request.getSession();
- roleFunctions = (HashSet) session
- .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
-
- if (roleFunctions == null) {
- HashMap roles = getRoles(request);
- roleFunctions = new HashSet();
-
- Iterator i = roles.keySet().iterator();
-
- while (i.hasNext()) {
- Long roleKey = (Long) i.next();
- Role role = (Role) roles.get(roleKey);
-
- Iterator j = role.getRoleFunctions().iterator();
-
- while (j.hasNext()) {
- RoleFunction function = (RoleFunction) j.next();
- roleFunctions.add(function.getCode());
- }
- }
- session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME),
- roleFunctions);
- }
- return roleFunctions;
- }
-
- public static HashMap getRoles(HttpServletRequest request) {
- HashMap roles = null;
-
- // HttpSession session = request.getSession();
- HttpSession session = AppUtils.getSession(request);
- roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
-
- // if roles are not already cached, let's grab them from the user
- // session
- if (roles == null) {
- User user = getUserSession(request);
-
- // get all user roles (including the tree of child roles)
- roles = getAllUserRoles(user);
-
- session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME),
- getAllUserRoles(user));
- }
-
- return roles;
- }
-
- public static User getUserSession(HttpServletRequest request) {
- HttpSession session = AppUtils.getSession(request);
-
- if (session == null) {
- throw new SessionExpiredException();
- }
-
- return (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
- }
-
- @SuppressWarnings("unchecked")
- public static HashMap getAllUserRoles(User user) {
- HashMap roles = new HashMap();
- Iterator i = user.getRoles().iterator();
-
- while (i.hasNext()) {
- Role role = (Role) i.next();
-
- if (role.getActive()) {
- roles.put(role.getId(), role);
-
- // let's take a recursive trip down the tree to add all child
- // roles
- addChildRoles(role, roles);
- }
- }
-
- return roles;
- }
-
- @SuppressWarnings("unchecked")
- private static void addChildRoles(Role role, HashMap roles) {
- Set childRoles = role.getChildRoles();
- if (childRoles != null && childRoles.size() > 0) {
- Iterator j = childRoles.iterator();
- while (j.hasNext()) {
- Role childRole = (Role) j.next();
- if (childRole.getActive()) {
- roles.put(childRole.getId(), childRole);
- addChildRoles(childRole, roles);
- }
- }
- }
-
- }
-
-
-
- public static boolean hasRole(HttpServletRequest request, String roleKey) {
- return getRoles(request).keySet().contains(new Long(roleKey));
- }
-
- public static boolean hasRole(User user, String roleKey) {
- return getAllUserRoles(user).keySet().contains(new Long(roleKey));
- }
-
- public static boolean isAccessible(HttpServletRequest request, String functionKey) {
- return getRoleFunctions(request).contains(functionKey);
- }
-
- public static String getLoginMethod(HttpServletRequest request) {
- HttpSession session = AppUtils.getSession(request);
-
- if (session == null) {
- throw new SessionExpiredException();
- }
-
- return (String) session
- .getAttribute(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME));
- }
-
- public static DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- @Autowired
- public void setDataAccessService(DataAccessService dataAccessService) {
- UserUtils.dataAccessService = dataAccessService;
- }
-
- public static int getUserId(HttpServletRequest request) {
- return getUserIdAsLong(request).intValue();
- }
-
- public static Long getUserIdAsLong(HttpServletRequest request) {
- Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
-
- if (request != null) {
- if (getUserSession(request) != null) {
- userId = getUserSession(request).getId();
- }
- }
- return userId;
- }
-
- private static final Object stackTraceLock = new Object();
-
- /**
- * Serializes a stack trace of the specified throwable and returns it as a
- * string.
- *
- * TODO: why is synchronization required?
- *
- * @param t
- * @return String version of stack trace
- */
- public static String getStackTrace(Throwable t) {
- synchronized (stackTraceLock) {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- t.printStackTrace(pw);
- return sw.toString();
- }
- }
-
- /**
- * Gets the full URL of the request by joining the request and any query
- * string.
- *
- * @param request
- * @return Full URL of the request including query parameters
- */
- public static String getFullURL(HttpServletRequest request) {
- if (request != null) {
- StringBuffer requestURL = request.getRequestURL();
- String queryString = request.getQueryString();
-
- if (queryString == null) {
- return requestURL.toString();
- } else {
- return requestURL.append('?').append(queryString).toString();
- }
- }
- return "";
- }
-
- /**
- * Gets or generates a request ID by searching for header X-ECOMP-RequestID.
- * If not found, generates a new random UUID.
- *
- * @param request
- * @return Request ID for the specified request
- */
- public static String getRequestId(HttpServletRequest request) {
- Enumeration<String> headerNames = request.getHeaderNames();
-
- String requestId = "";
- try {
- while (headerNames.hasMoreElements()) {
- String headerName = (String) headerNames.nextElement();
- if (logger.isTraceEnabled())
- logger.trace(EELFLoggerDelegate.debugLogger, "getRequestId: header {} = {}", headerName,
- request.getHeader(headerName));
- if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
- requestId = request.getHeader(headerName);
- break;
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.debugLogger, "getRequestId: failed to get headder", e);
- }
-
- if (requestId.isEmpty())
- requestId = UUID.randomUUID().toString();
- logger.debug(EELFLoggerDelegate.debugLogger, "getRequestId: result is {}", requestId);
- return requestId;
- }
-
- /**
- * Converts a Hibernate-mapped User object to a JSON-serializable EcompUser
- * object.
- *
- * @param user
- * @return EcompUser with a subset of fields.
- */
- public static EcompUser convertToEcompUser(User user) {
- EcompUser userJson = new EcompUser();
- userJson.setEmail(user.getEmail());
- userJson.setFirstName(user.getFirstName());
- userJson.setHrid(user.getHrid());
- userJson.setJobTitle(user.getJobTitle());
- userJson.setLastName(user.getLastName());
- userJson.setLoginId(user.getLoginId());
- userJson.setOrgManagerUserId(user.getOrgManagerUserId());
- userJson.setMiddleInitial(user.getMiddleInitial());
- userJson.setOrgCode(user.getOrgCode());
- userJson.setOrgId(user.getOrgId());
- userJson.setPhone(user.getPhone());
- userJson.setOrgUserId(user.getOrgUserId());
- Set<EcompRole> ecompRoles = new TreeSet<EcompRole>();
- for (Role role : user.getRoles()) {
- ecompRoles.add(convertToEcompRole(role));
- }
- userJson.setRoles(ecompRoles);
- return userJson;
- }
-
- /**
- * Converts a Hibernate-mapped Role object to a JSON-serializable EcompRole
- * object.
- *
- * @param role
- * @return EcompRole with a subset of fields: ID and name
- */
- public static EcompRole convertToEcompRole(Role role) {
- EcompRole ecompRole = new EcompRole();
- ecompRole.setId(role.getId());
- ecompRole.setName(role.getName());
- return ecompRole;
- }
-
- }
-
-
--- /dev/null
+package org.onap.fusion.core;
+
+import java.io.IOException;
+
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.onap.portalsdk.core.conf.AppConfig;
+import org.onap.portalsdk.core.objectcache.AbstractCacheManager;
+import org.onap.portalsdk.core.util.CacheManager;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
+import org.springframework.test.context.web.WebAppConfiguration;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+
+/**
+ * In order to write a unit test, 1. inherit this class - See SanityTest.java 2.
+ * place the "war" folder on your test class's classpath 3. run the test with
+ * the following VM argument; This is important because when starting the
+ * application from Container, the System Properties file
+ * (SystemProperties.java) can have the direct path but, when running from the
+ * Mock Junit container, the path should be prefixed with "classpath" to enable
+ * the mock container to search for the file in the classpath
+ * -Dcontainer.classpath="classpath:"
+ *
+ */
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@WebAppConfiguration
+@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = { MockAppConfig.class })
+@ActiveProfiles(value = "test")
+public class MockApplicationContextTestSuite {
+
+ @Autowired
+ public WebApplicationContext wac;
+
+ private MockMvc mockMvc;
+
+ @Before
+ public void setup() {
+ if (mockMvc == null) {
+ this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
+
+ }
+ }
+
+ public Object getBean(String name) {
+ return this.wac.getBean(name);
+ }
+
+ public MockMvc getMockMvc() {
+ return mockMvc;
+ }
+
+ public void setMockMvc(MockMvc mockMvc) {
+ this.mockMvc = mockMvc;
+ }
+
+ public WebApplicationContext getWebApplicationContext() {
+ return wac;
+ }
+
+}
+
+@Configuration
+@ComponentScan(basePackages = "org.onap", excludeFilters = {})
+@Profile("test")
+class MockAppConfig extends AppConfig {
+
+ @Bean
+ public SystemProperties systemProperties() {
+ return new MockSystemProperties();
+ }
+
+ @Bean
+ public AbstractCacheManager cacheManager() {
+ return new CacheManager() {
+
+ public void configure() throws IOException {
+
+ }
+ };
+ }
+
+ protected String[] tileDefinitions() {
+ return new String[] { "classpath:/WEB-INF/fusion/defs/definitions.xml",
+ "classpath:/WEB-INF/defs/definitions.xml" };
+ }
+
+ @Override
+ public void addInterceptors(InterceptorRegistry registry) {
+ // registry.addInterceptor(new
+ // SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout());
+ // registry.addInterceptor(resourceInterceptor());
+ }
+
+ public static class MockSystemProperties extends SystemProperties {
+
+ public MockSystemProperties() {
+ }
+
+ }
+
+}
--- /dev/null
+package org.onap.fusion.core;
+
+import org.onap.portalsdk.core.conf.HibernateMappingLocatable;
+import org.springframework.context.annotation.Profile;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+import org.springframework.stereotype.Component;
+
+@Component
+@Profile("test")
+public class MockHibernateMappingLocations implements HibernateMappingLocatable{
+
+ @Override
+ public Resource[] getMappingLocations() {
+ return new Resource[]{new ClassPathResource("WEB-INF/fusion/orm/Fusion.hbm.xml"), new ClassPathResource("WEB-INF/fusion/orm/Workflow.hbm.xml")};
+ }
+
+ @Override
+ public String[] getPackagesToScan() {
+ return new String[] { "org.onap" };
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk;
+
+import java.io.IOException;
+
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.onap.portalsdk.core.conf.AppConfig;
+import org.onap.portalsdk.core.objectcache.AbstractCacheManager;
+import org.onap.portalsdk.core.util.CacheManager;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
+import org.springframework.test.context.web.WebAppConfiguration;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+
+/**
+ *
+ *
+ *
+ * In order to write a unit test,
+ * 1. inherit this class - See SanityTest.java
+ * 2. place the "war" folder on your test class's classpath
+ * 3. run the test with the following VM argument; This is important because when starting the application from Container, the System Properties file (SystemProperties.java) can have the direct path
+ * but, when running from the Mock Junit container, the path should be prefixed with "classpath" to enable the mock container to search for the file in the classpath
+ * -Dcontainer.classpath="classpath:"
+ *
+ */
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@WebAppConfiguration
+@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = {MockAppConfig.class})
+@ActiveProfiles(value="test")
+public class MockApplicationContextTestSuite {
+
+ @Autowired
+ public WebApplicationContext wac;
+
+ private MockMvc mockMvc;
+
+ @Before
+ public void setup() {
+ if(mockMvc == null) {
+ this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
+
+ }
+ }
+
+ public Object getBean(String name) {
+ return this.wac.getBean(name);
+ }
+
+
+ public MockMvc getMockMvc() {
+ return mockMvc;
+ }
+
+ public void setMockMvc(MockMvc mockMvc) {
+ this.mockMvc = mockMvc;
+ }
+
+ public WebApplicationContext getWebApplicationContext() {
+ return wac;
+ }
+
+
+
+
+}
+
+
+ @Configuration
+ @ComponentScan(basePackages = "org.onap",
+ excludeFilters = { }
+ )
+ @Profile("test")
+ class MockAppConfig extends AppConfig {
+
+ @Bean
+ public SystemProperties systemProperties(){
+ return new MockSystemProperties();
+ }
+
+ @Bean
+ public AbstractCacheManager cacheManager() {
+ return new CacheManager() {
+
+ public void configure() throws IOException {
+
+ }
+ };
+ }
+
+ protected String[] tileDefinitions() {
+ return new String[] {"classpath:/WEB-INF/fusion/defs/definitions.xml", "classpath:/WEB-INF/defs/definitions.xml"};
+ }
+
+ @Override
+ public void addInterceptors(InterceptorRegistry registry) {
+ //registry.addInterceptor(new SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout());
+ //registry.addInterceptor(resourceInterceptor());
+ }
+
+ public static class MockSystemProperties extends SystemProperties {
+
+ public MockSystemProperties() {
+ }
+
+ }
+
+ }
+
+
+
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk;
+
+import org.onap.portalsdk.core.conf.HibernateMappingLocatable;
+import org.springframework.context.annotation.Profile;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+import org.springframework.stereotype.Component;
+
+@Component
+@Profile("test")
+public class MockHibernateMappingLocations implements HibernateMappingLocatable {
+
+ public Resource[] getMappingLocations() {
+ return new Resource[] { new ClassPathResource("WEB-INF/fusion/orm/Fusion.hbm.xml"),
+ new ClassPathResource("WEB-INF/fusion/orm/Workflow.hbm.xml") };
+ }
+
+ @Override
+ public String[] getPackagesToScan() {
+ return new String[] { "org.onap" };
+ }
+
+}
+++ /dev/null
-package org.openecomp.fusion.core;
-
-import java.io.IOException;
-
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.openecomp.portalsdk.core.conf.AppConfig;
-import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager;
-import org.openecomp.portalsdk.core.util.CacheManager;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Profile;
-import org.springframework.test.context.ActiveProfiles;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
-import org.springframework.test.context.web.WebAppConfiguration;
-import org.springframework.test.web.servlet.MockMvc;
-import org.springframework.test.web.servlet.setup.MockMvcBuilders;
-import org.springframework.web.context.WebApplicationContext;
-import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
-
-/**
- * In order to write a unit test, 1. inherit this class - See SanityTest.java 2.
- * place the "war" folder on your test class's classpath 3. run the test with
- * the following VM argument; This is important because when starting the
- * application from Container, the System Properties file
- * (SystemProperties.java) can have the direct path but, when running from the
- * Mock Junit container, the path should be prefixed with "classpath" to enable
- * the mock container to search for the file in the classpath
- * -Dcontainer.classpath="classpath:"
- *
- */
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@WebAppConfiguration
-@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = { MockAppConfig.class })
-@ActiveProfiles(value = "test")
-public class MockApplicationContextTestSuite {
-
- @Autowired
- public WebApplicationContext wac;
-
- private MockMvc mockMvc;
-
- @Before
- public void setup() {
- if (mockMvc == null) {
- this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
-
- }
- }
-
- public Object getBean(String name) {
- return this.wac.getBean(name);
- }
-
- public MockMvc getMockMvc() {
- return mockMvc;
- }
-
- public void setMockMvc(MockMvc mockMvc) {
- this.mockMvc = mockMvc;
- }
-
- public WebApplicationContext getWebApplicationContext() {
- return wac;
- }
-
-}
-
-@Configuration
-@ComponentScan(basePackages = "org.openecomp", excludeFilters = {})
-@Profile("test")
-class MockAppConfig extends AppConfig {
-
- @Bean
- public SystemProperties systemProperties() {
- return new MockSystemProperties();
- }
-
- @Bean
- public AbstractCacheManager cacheManager() {
- return new CacheManager() {
-
- public void configure() throws IOException {
-
- }
- };
- }
-
- protected String[] tileDefinitions() {
- return new String[] { "classpath:/WEB-INF/fusion/defs/definitions.xml",
- "classpath:/WEB-INF/defs/definitions.xml" };
- }
-
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- // registry.addInterceptor(new
- // SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout());
- // registry.addInterceptor(resourceInterceptor());
- }
-
- public static class MockSystemProperties extends SystemProperties {
-
- public MockSystemProperties() {
- }
-
- }
-
-}
+++ /dev/null
-package org.openecomp.fusion.core;
-
-import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable;
-import org.springframework.context.annotation.Profile;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.core.io.Resource;
-import org.springframework.stereotype.Component;
-
-@Component
-@Profile("test")
-public class MockHibernateMappingLocations implements HibernateMappingLocatable{
-
- @Override
- public Resource[] getMappingLocations() {
- return new Resource[]{new ClassPathResource("WEB-INF/fusion/orm/Fusion.hbm.xml"), new ClassPathResource("WEB-INF/fusion/orm/Workflow.hbm.xml")};
- }
-
- @Override
- public String[] getPackagesToScan() {
- return new String[] { "org.openecomp" };
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
-
-import java.io.IOException;
-
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.openecomp.portalsdk.core.conf.AppConfig;
-import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager;
-import org.openecomp.portalsdk.core.util.CacheManager;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Profile;
-import org.springframework.test.context.ActiveProfiles;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
-import org.springframework.test.context.web.WebAppConfiguration;
-import org.springframework.test.web.servlet.MockMvc;
-import org.springframework.test.web.servlet.setup.MockMvcBuilders;
-import org.springframework.web.context.WebApplicationContext;
-import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
-
-/**
- *
- *
- *
- * In order to write a unit test,
- * 1. inherit this class - See SanityTest.java
- * 2. place the "war" folder on your test class's classpath
- * 3. run the test with the following VM argument; This is important because when starting the application from Container, the System Properties file (SystemProperties.java) can have the direct path
- * but, when running from the Mock Junit container, the path should be prefixed with "classpath" to enable the mock container to search for the file in the classpath
- * -Dcontainer.classpath="classpath:"
- *
- */
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@WebAppConfiguration
-@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = {MockAppConfig.class})
-@ActiveProfiles(value="test")
-public class MockApplicationContextTestSuite {
-
- @Autowired
- public WebApplicationContext wac;
-
- private MockMvc mockMvc;
-
- @Before
- public void setup() {
- if(mockMvc == null) {
- this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
-
- }
- }
-
- public Object getBean(String name) {
- return this.wac.getBean(name);
- }
-
-
- public MockMvc getMockMvc() {
- return mockMvc;
- }
-
- public void setMockMvc(MockMvc mockMvc) {
- this.mockMvc = mockMvc;
- }
-
- public WebApplicationContext getWebApplicationContext() {
- return wac;
- }
-
-
-
-
-}
-
-
- @Configuration
- @ComponentScan(basePackages = "org.openecomp",
- excludeFilters = { }
- )
- @Profile("test")
- class MockAppConfig extends AppConfig {
-
- @Bean
- public SystemProperties systemProperties(){
- return new MockSystemProperties();
- }
-
- @Bean
- public AbstractCacheManager cacheManager() {
- return new CacheManager() {
-
- public void configure() throws IOException {
-
- }
- };
- }
-
- protected String[] tileDefinitions() {
- return new String[] {"classpath:/WEB-INF/fusion/defs/definitions.xml", "classpath:/WEB-INF/defs/definitions.xml"};
- }
-
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- //registry.addInterceptor(new SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout());
- //registry.addInterceptor(resourceInterceptor());
- }
-
- public static class MockSystemProperties extends SystemProperties {
-
- public MockSystemProperties() {
- }
-
- }
-
- }
-
-
-
-
+++ /dev/null
-/*-
- * ================================================================================
- * 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;
-
-import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable;
-import org.springframework.context.annotation.Profile;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.core.io.Resource;
-import org.springframework.stereotype.Component;
-
-@Component
-@Profile("test")
-public class MockHibernateMappingLocations implements HibernateMappingLocatable {
-
- public Resource[] getMappingLocations() {
- return new Resource[] { new ClassPathResource("WEB-INF/fusion/orm/Fusion.hbm.xml"),
- new ClassPathResource("WEB-INF/fusion/orm/Workflow.hbm.xml") };
- }
-
- @Override
- public String[] getPackagesToScan() {
- return new String[] { "org.openecomp" };
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.controller.sessionmgt;
-/*package org.openecomp.portalsdk.controller.sessionmgt;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.springframework.mock.web.MockHttpSession;
-import org.springframework.test.web.servlet.ResultActions;
-import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
-import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
-
-import org.openecomp.portalsdk.MockApplicationContextTestSuite;
-import org.openecomp.portalsdk.service.sessionmgt.CoreTimeoutHandler;
-
-public class PortalCommunicationTest extends MockApplicationContextTestSuite{
-
-
- @Test
- public void testGetTimeoutSessions() throws Exception {
-
- MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/sessionTimeOuts");
- MockHttpSession httpSession = new MockHttpSession(this.wac.getServletContext(),"1234");
- CoreTimeoutHandler.sessionCreated("12", "1234", httpSession);
-
- ResultActions ra = this.getMockMvc().perform(requestBuilder);
-
- System.out.println(" %%%%%%%%%%%%%%%%%%%%%%%%% " + ra.andReturn().getResponse().getContentAsString());
- System.out.println(" %%%%%%%%%%%%%%%%%%%%%%%%% " + "{\"12\":{\"jSessionId\":\"1234\",\"sessionTimOutMilliSec\":");
-
- Assert.assertTrue(ra.andReturn().getResponse().getContentAsString().startsWith("{\"12\":{\"jSessionId\":\"1234\",\"sessionTimOutMilliSec\":"));
-
- }
-
- @Test
- public void testUpdateTimeoutSessions() throws Exception {
-
- // pre condition
- MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/sessionTimeOuts");
- MockHttpSession httpSession = new MockHttpSession(this.wac.getServletContext(),"1234");
- CoreTimeoutHandler.sessionCreated("12", "1234", httpSession);
- ResultActions ra = this.getMockMvc().perform(requestBuilder);
-
- String responseSessMapStr = ra.andReturn().getResponse().getContentAsString();
-
-
- // test
- requestBuilder = MockMvcRequestBuilders.post("/api/updateSessionTimeOuts");
- requestBuilder.param("sessionMap", responseSessMapStr);
- ra = this.getMockMvc().perform(requestBuilder);
-
-
- }
-
-
-
-}
-*/
-# ECOMP Portal SDK Framework
+# ONAP Portal SDK Framework
## Overview
-This is the Maven project for the ECOMP Portal SDK Framework library,
+This is the Maven project for the ONAP Portal SDK Framework library,
which is distributed as epsdk-fw-N.N.N.jar. This library
(once called third-party onboarding) provides features to
partner applications that use a J2EE Servlet 3.0 container
### ONAP Distributions
-Version 1.3.0
+Version 1.4.0
+- PORTAL-19 Rename Java package base to org.onap
+- PORTAL-42 Use OParent as parent POM
+- PORTAL-72 Address Sonar Scan code issues
+- PORTAL-90 Use approved ONAP license text
+* Put new entries here *
+
+Version 1.3.0, 28 August 2017
- PORTAL-19 Renaming the Group Id in the POM file to org.onap.portal.sdk
- PORTAL-64 Single sign-on from Portal fails for some applications
<parent>
<groupId>org.onap.portal.sdk</groupId>
<artifactId>epsdk-project</artifactId>
- <version>1.3.0-SNAPSHOT</version>
+ <version>1.4.0-SNAPSHOT</version>
</parent>
<!-- GroupId is inherited from parent -->
<artifactId>epsdk-fw</artifactId>
<!-- Version is inherited from parent -->
<packaging>jar</packaging>
- <name>ECOMP Portal SDK Framework</name>
+ <name>ONAP Portal SDK Framework</name>
<!-- properties are inherited from parent -->
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.crossapi;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
+import org.onap.portalsdk.core.restful.domain.EcompRole;
+import org.onap.portalsdk.core.restful.domain.EcompUser;
+
+/**
+ * Defines the REST API Interface that an on-boarding application must implement
+ * to answer queries and accept updates from the ECOMP Portal about the
+ * application's users, roles and user-role assignments.
+ */
+public interface IPortalRestAPIService {
+
+ // EcompUser Interface
+
+ /**
+ * Creates a user with the specified details. If any error occurs, for example
+ * the user exists, the method should throw PortalApiException with an
+ * appropriate message. The FW library will catch the exception and send an
+ * appropriate response to Portal.
+ *
+ * @param user
+ * Model object with attributes of user to be created.
+ * @throws PortalAPIException
+ * If any error occurs while processing the request; for example,
+ * user exists.
+ */
+ public void pushUser(EcompUser user) throws PortalAPIException;
+
+ /**
+ * Updates details about the user with the specified loginId. For example, mark
+ * user as inactive. If any error occurs, the method should throw
+ * PortalApiException with an appropriate message. The FW library will catch the
+ * exception and send an appropriate response to Portal.
+ *
+ * @param loginId
+ * EcompUser ID to be updated.
+ * @param user
+ * Model object with attributes of user to be updated.
+ * @throws PortalAPIException
+ * If any error occurs while processing the request; for example,
+ * unknown user.
+ */
+ public void editUser(String loginId, EcompUser user) throws PortalAPIException;
+
+ /**
+ * Gets and returns the user object with the specified loginId. If any error
+ * occurs, the method should throw PortalApiException with an appropriate
+ * message. The FW library will catch the exception and send an appropriate
+ * response to Portal
+ *
+ * @param loginId
+ * EcompUser ID to be fetched
+ * @return Model object with user attributes.
+ * @throws PortalAPIException
+ * If any error occurs while processing the request; for example,
+ * unknown user.
+ */
+ public EcompUser getUser(String loginId) throws PortalAPIException;
+
+ /**
+ * Gets and returns a list of active users. If any error occurs, the method
+ * should throw PortalApiException with an appropriate message. The FW library
+ * will catch the exception and send an appropriate response to Portal.
+ *
+ * @return List of user attribute model objects; empty list if none are found.
+ * @throws PortalAPIException
+ * If any error occurs while processing the request.
+ */
+ public List<EcompUser> getUsers() throws PortalAPIException;
+
+ // Roles Interface
+
+ /**
+ * Gets and returns a list of active roles. If any error occurs, the method
+ * should throw PortalApiException with an appropriate message. The FW library
+ * will catch the exception and send an appropriate response to Portal.
+ *
+ * @param requestedLoginId
+ * requested userloginId to fetch available roles
+ * @return List of role attribute objects; empty list if none are found.
+ * @throws PortalAPIException
+ * If an unexpected error occurs while processing the request.
+ */
+ public List<EcompRole> getAvailableRoles(String requestedLoginId) throws PortalAPIException;
+
+ /**
+ * Updates roles for the user with the specified loginId to the list of roles
+ * provided as the second argument. After this operation, the should have ONLY
+ * the roles provided in the list above. For example, if user had roles r1, r2
+ * and r3; and a call was made to pushUserRole with a list containing only roles
+ * r3 and r4, this method should leave the user with roles r3 and r4 since those
+ * were the ONLY roles provided in second argument. If any error occurs, the
+ * method should throw PortalApiException with an appropriate message. The FW
+ * library will catch the exception and send an appropriate response to Portal.
+ *
+ * @param loginId
+ * EcompUser ID to be updated.
+ * @param roles
+ * List of role attribute objects
+ * @throws PortalAPIException
+ * If any error occurs while processing the request.
+ */
+ public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException;
+
+ /**
+ * Gets and returns a list of roles for the user with the specified loginId. If
+ * any error occurs, the method should throw PortalApiException with an
+ * appropriate message. The FW library will catch the exception and send an
+ * appropriate response to Portal.
+ *
+ * @param loginId
+ * Organization user ID
+ * @return List of model objects; empty if no roles are found.
+ * @throws PortalAPIException
+ * If any error occurs while processing the request; e.g., user not
+ * found.
+ */
+ public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException;
+
+ // Security Interface
+
+ /**
+ * Should return true if the call should be allowed and false if not. Currently
+ * Portal sends two headers of username and password in each request which the
+ * app should check. If match, return true; else return false. If any error
+ * occurs, the method should throw PortalApiException with an appropriate
+ * message. The FW library will catch the exception and send an appropriate
+ * response to Portal.
+ *
+ * @param request
+ * HttpServletRequest
+ * @return true if the request contains appropriate credentials, else false.
+ * @throws PortalAPIException
+ * If an unexpected error occurs while processing the request.
+ */
+ public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException;
+
+ /**
+ * Gets and returns the userId for the logged-in user based on the request. If
+ * any error occurs, the method should throw PortalApiException with an
+ * appropriate message. The FW library will catch the exception and send an
+ * appropriate response to Portal.
+ *
+ * @param request
+ * HttpServletRequest
+ * @return true if the request contains appropriate credentials, else false.
+ * @throws PortalAPIException
+ * If an unexpected error occurs while processing the request.
+ */
+ public String getUserId(HttpServletRequest request) throws PortalAPIException;
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.crossapi;
+
+import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
+
+/**
+ * UEB API Interface for all the onboarding third party applications.
+ */
+
+public interface IPortalUebAPIService {
+ // User Interface
+ public String pushUser(String userJson) throws PortalAPIException;
+
+ public String editUser(String loginId, String userJson) throws PortalAPIException;
+
+ public String getUser(String loginId) throws PortalAPIException;
+
+ public String getUsers() throws PortalAPIException;
+
+ // Roles Interface
+ public String getAvailableRoles() throws PortalAPIException;
+
+ public String getAvailableFullRoles() throws PortalAPIException;
+
+ public String pushUserRole(String loginId, String rolesJson) throws PortalAPIException;
+
+ public String getUserRoles(String loginId) throws PortalAPIException;
+
+ // Security Interface
+ public boolean isAppAuthenticated(String appUserName, String appPassword) throws PortalAPIException;
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.crossapi;
+
+/**
+ * This bean holds a response that is returned by the role and user-management
+ * REST API.
+ */
+public class PortalAPIResponse {
+
+ /**
+ * Either "ok" or "error"
+ */
+ private String status;
+ /**
+ * Optional if status is ok
+ */
+ private String message;
+
+ public PortalAPIResponse(boolean isOk, String msg) {
+ status = (isOk? "ok" : "error");
+ message = msg;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.crossapi;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.ServletException;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
+import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
+import org.onap.portalsdk.core.onboarding.rest.RestWebServiceClient;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+import org.onap.portalsdk.core.restful.domain.EcompRole;
+import org.onap.portalsdk.core.restful.domain.EcompUser;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * This servlet performs the functions described below. It listens on a path
+ * like "/api" (see {@link PortalApiConstants#API_PREFIX}). The servlet checks
+ * for authorized access and rejects unauthorized requests.
+ * <OL>
+ * <LI>Proxies user (i.e., browser) requests for web analytics. The GET method
+ * fetches javascript from the Portal and returns it. The POST method forwards
+ * data sent by the browser on to Portal. These requests are checked for a valid
+ * User UID in a header; these requests do NOT use the application
+ * username-password header.</LI>
+ * <LI>Responds to ECOMP Portal API requests to query and update user, role and
+ * user-role information. The servlet proxies all requests on to a local Java
+ * class that implements {@link IPortalRestAPIService}. These requests must have
+ * the application username-password header.</LI>
+ * </OL>
+ * This servlet will not start if the required portal.properties file is not
+ * found on the classpath.
+ */
+
+@WebServlet(urlPatterns = { PortalApiConstants.API_PREFIX + "/*" })
+public class PortalRestAPIProxy extends HttpServlet implements IPortalRestAPIService {
+ private static final long serialVersionUID = 1L;
+
+ private static final String contentTypeAppJson = "application/json";
+
+ private final Log logger = LogFactory.getLog(getClass());
+
+ /**
+ * Mapper for JSON to object etc.
+ */
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ /**
+ * Client-supplied class that implements our interface.
+ */
+ private static IPortalRestAPIService portalRestApiServiceImpl;
+
+ public PortalRestAPIProxy() {
+ // Ensure that any additional fields sent by the Portal
+ // will be ignored when creating objects.
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ }
+
+ @Override
+ public void init() throws ServletException {
+ String className = PortalApiProperties.getProperty(PortalApiConstants.PORTAL_API_IMPL_CLASS);
+ if (className == null)
+ throw new ServletException(
+ "init: Failed to find class name property " + PortalApiConstants.PORTAL_API_IMPL_CLASS);
+ try {
+ logger.debug("init: creating instance of class " + className);
+ Class<?> implClass = Class.forName(className);
+ portalRestApiServiceImpl = (IPortalRestAPIService) (implClass.getConstructor().newInstance());
+ } catch (Exception ex) {
+ throw new ServletException("init: Failed to find or instantiate class " + className, ex);
+ }
+ }
+
+ @Override
+ protected void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws IOException, ServletException {
+ if (portalRestApiServiceImpl == null) {
+ // Should never happen due to checks in init()
+ logger.error("doPost: no service class instance");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.getWriter().write(buildJsonResponse(false, "Misconfigured - no instance of service class"));
+ return;
+ }
+ String requestUri = request.getRequestURI();
+ String responseJson = "";
+ String storeAnalyticsContextPath = "/storeAnalytics";
+ if (requestUri.endsWith(PortalApiConstants.API_PREFIX + storeAnalyticsContextPath)) {
+ String userId;
+ try {
+ userId = getUserId(request);
+ } catch (PortalAPIException e) {
+ logger.error("Issue with invoking getUserId implemenation !!! ", e);
+ throw new ServletException(e);
+ }
+ if (userId == null || userId.length() == 0) {
+ logger.debug("doPost: userId is null or empty");
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ responseJson = buildJsonResponse(false, "Not authorized for " + storeAnalyticsContextPath);
+ } else {
+ // User ID obtained from request
+ try {
+ String credential = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
+ // for now lets also pass uebkey as user name and password
+ String requestBody = readRequestBody(request);
+ @SuppressWarnings("unchecked")
+ Map<String, String> bodyMap = mapper.readValue(requestBody, Map.class);
+ // add user ID
+ bodyMap.put("userid", userId);
+ requestBody = mapper.writeValueAsString(bodyMap);
+ responseJson = RestWebServiceClient.getInstance().postPortalContent(storeAnalyticsContextPath,
+ userId, credential, null, credential, credential, "application/json", requestBody, true);
+ if (logger.isDebugEnabled())
+ logger.debug("doPost: postPortalContent returns " + responseJson);
+ response.setStatus(HttpServletResponse.SC_OK);
+ } catch (Exception ex) {
+ logger.error("doPost: " + storeAnalyticsContextPath + " caught exception", ex);
+ responseJson = buildJsonResponse(ex);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ }
+ writeAndFlush(response, contentTypeAppJson, responseJson);
+ return;
+ } // post analytics
+
+ boolean secure = false;
+ try {
+ secure = isAppAuthenticated(request);
+ } catch (PortalAPIException ex) {
+ logger.error("doPost: isAppAuthenticated threw exception", ex);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ response.getWriter().write(buildJsonResponse(false, "Failed to authenticate request"));
+ return;
+ }
+ if (!secure) {
+ if (logger.isDebugEnabled())
+ logger.debug("doPost: isAppAuthenticated answered false");
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ writeAndFlush(response, contentTypeAppJson, buildJsonResponse(false, "Not authorized"));
+ return;
+ }
+
+ try {
+ String requestBody = readRequestBody(request);
+ if (logger.isDebugEnabled())
+ logger.debug("doPost: URI = " + requestUri + ", payload = " + requestBody);
+
+ /*
+ * All APIs:
+ *
+ * 1. /user <-- save user
+ *
+ * 2. /user/{loginId} <-- edit user
+ *
+ * 3. /user/{loginId}/roles <-- save roles for user
+ */
+
+ // On success return the empty string.
+
+ if (requestUri.endsWith("/updateSessionTimeOuts")) {
+ if (updateSessionTimeOuts(requestBody)) {
+ if (logger.isDebugEnabled())
+ logger.debug("doPost: updated session timeouts");
+ response.setStatus(HttpServletResponse.SC_OK);
+ } else {
+ String msg = "Failed to update session time outs";
+ logger.error("doPost: " + msg);
+ responseJson = buildJsonResponse(false, msg);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ } else if (requestUri.endsWith("/timeoutSession")) {
+ String portalJSessionId = request.getParameter("portalJSessionId");
+ if (portalJSessionId == null) {
+ portalJSessionId = "";
+ }
+ if (timeoutSession(portalJSessionId)) {
+ if (logger.isDebugEnabled())
+ logger.debug("doPost: timed out session");
+ response.setStatus(HttpServletResponse.SC_OK);
+ } else {
+ String msg = "Failed to timeout session";
+ logger.error("doPost: " + msg);
+ responseJson = buildJsonResponse(false, msg);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ } else
+ // Example: /user <-- create user
+ if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/user")) {
+ try {
+ EcompUser user = mapper.readValue(requestBody, EcompUser.class);
+ pushUser(user);
+ if (logger.isDebugEnabled())
+ logger.debug("doPost: pushUser: success");
+ responseJson = buildJsonResponse(true, null);
+ response.setStatus(HttpServletResponse.SC_OK);
+ } catch (Exception ex) {
+ responseJson = buildJsonResponse(ex);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ logger.error("doPost: pushUser: caught exception", ex);
+ }
+ } else
+ // Example: /user/fi241c <-- edit user fi241c
+ if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && !(requestUri.endsWith("/roles"))) {
+ String loginId = requestUri.substring(requestUri.lastIndexOf('/') + 1);
+ try {
+ EcompUser user = mapper.readValue(requestBody, EcompUser.class);
+ editUser(loginId, user);
+ if (logger.isDebugEnabled())
+ logger.debug("doPost: editUser: success");
+ responseJson = buildJsonResponse(true, null);
+ response.setStatus(HttpServletResponse.SC_OK);
+ } catch (Exception ex) {
+ responseJson = buildJsonResponse(ex);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ logger.error("doPost: editUser: caught exception", ex);
+ }
+ } else
+ // Example: /user/{loginId}/roles <-- save roles for user
+ if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && requestUri.endsWith("/roles")) {
+ String loginId = requestUri.substring(requestUri.indexOf("/user/") + ("/user").length() + 1,
+ requestUri.lastIndexOf('/'));
+ try {
+ TypeReference<List<EcompRole>> typeRef = new TypeReference<List<EcompRole>>() {
+ };
+ List<EcompRole> roles = mapper.readValue(requestBody, typeRef);
+ pushUserRole(loginId, roles);
+ if (logger.isDebugEnabled())
+ logger.debug("doPost: pushUserRole: success");
+ responseJson = buildJsonResponse(true, null);
+ response.setStatus(HttpServletResponse.SC_OK);
+ } catch (Exception ex) {
+ responseJson = buildJsonResponse(ex);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ logger.error("doPost: pushUserRole: caught exception", ex);
+ }
+ } else {
+ String msg = "doPost: no match for request " + requestUri;
+ logger.warn(msg);
+ responseJson = buildJsonResponse(false, msg);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ } catch (Exception ex) {
+ logger.error("doPost: Failed to process request " + requestUri, ex);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ responseJson = buildJsonResponse(ex);
+ }
+
+ writeAndFlush(response, contentTypeAppJson, responseJson);
+
+ }
+
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws IOException, ServletException {
+
+ if (portalRestApiServiceImpl == null) {
+ // Should never happen due to checks in init()
+ logger.error("doGet: no service class instance");
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ writeAndFlush(response, contentTypeAppJson,
+ buildJsonResponse(false, "Misconfigured - no instance of service class"));
+ return;
+ }
+
+ String requestUri = request.getRequestURI();
+ String responseString = "";
+ String contentType = contentTypeAppJson;
+
+ String webAnalyticsContextPath = "/analytics";
+ if (requestUri.endsWith(PortalApiConstants.API_PREFIX + webAnalyticsContextPath)) {
+ String userId;
+ try {
+ userId = getUserId(request);
+ } catch (PortalAPIException e) {
+ logger.error("Issue with invoking getUserId implemenation !!! ", e);
+ throw new ServletException(e);
+ }
+ if (userId == null || userId.length() == 0) {
+ logger.debug("doGet: userId is null or empty");
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ responseString = buildJsonResponse(false, "Not authorized for " + webAnalyticsContextPath);
+ } else {
+ // User ID obtained from request
+ try {
+ String credential = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
+ // for now lets also pass uebkey as user name and password
+ contentType = "text/javascript";
+
+ responseString = RestWebServiceClient.getInstance().getPortalContent(webAnalyticsContextPath,
+ userId, credential, null, credential, credential, true);
+ if (logger.isDebugEnabled())
+ logger.debug("doGet: " + webAnalyticsContextPath + ": " + responseString);
+ response.setStatus(HttpServletResponse.SC_OK);
+ } catch (Exception ex) {
+ responseString = buildJsonResponse(ex);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ logger.error("doGet: " + webAnalyticsContextPath + " caught exception", ex);
+ }
+ }
+ writeAndFlush(response, contentType, responseString);
+ return;
+ }
+
+ boolean secure = false;
+ try {
+ secure = isAppAuthenticated(request);
+ } catch (PortalAPIException ex) {
+ logger.error("doGet: isAppAuthenticated threw exception", ex);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ writeAndFlush(response, contentTypeAppJson, buildJsonResponse(false, "Failed to authenticate request"));
+ return;
+ }
+
+ if (!secure) {
+ if (logger.isDebugEnabled())
+ logger.debug("doGet: isAppAuthenticated answered false");
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ writeAndFlush(response, contentTypeAppJson, buildJsonResponse(false, "Not authorized"));
+ return;
+ }
+
+ String responseJson = null;
+ try {
+ // Ignore any request body in a GET.
+ // String requestBody = readRequestBody(request);
+ if (logger.isDebugEnabled())
+ logger.debug("doGet: URI = " + requestUri);
+
+ /*
+ * 1. /roles <-- get roles
+ *
+ * 2. /user/{loginId} <-- get user
+ *
+ * 3. /users <-- get all users
+ *
+ * 4. /user/{loginId}/roles <-- get roles for user
+ */
+
+ if (requestUri.endsWith("/sessionTimeOuts")) {
+ responseJson = getSessionTimeOuts();
+ if (responseJson != null && responseJson.length() > 0) {
+ if (logger.isDebugEnabled())
+ logger.debug("doGet: got session timeouts");
+ response.setStatus(HttpServletResponse.SC_OK);
+ } else {
+ String msg = "Failed to get session time outs";
+ logger.error("doGet: " + msg);
+ responseJson = buildJsonResponse(false, msg);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ } else
+ // Example: /users <-- get all users
+ if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/users")) {
+ try {
+ List<EcompUser> users = getUsers();
+ responseJson = mapper.writeValueAsString(users);
+ if (logger.isDebugEnabled())
+ logger.debug("doGet: getUsers: " + responseJson);
+ } catch (Exception ex) {
+ responseJson = buildJsonResponse(ex);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ logger.error("doGet: getUsers: caught exception", ex);
+ }
+ } else
+ // Example: /roles <-- get all roles
+
+ if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/roles")) {
+ try {
+ List<EcompRole> roles = getAvailableRoles(getUserId(request));
+ responseJson = mapper.writeValueAsString(roles);
+ if (logger.isDebugEnabled())
+ logger.debug("doGet: getAvailableRoles: " + responseJson);
+ } catch (Exception ex) {
+ responseJson = buildJsonResponse(ex);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ logger.error("doGet: getAvailableRoles: caught exception", ex);
+ }
+ } else
+ // Example: /user/fi241c <-- get user fi241c
+ if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && !requestUri.endsWith("/roles")) {
+ String loginId = requestUri.substring(requestUri.lastIndexOf('/') + 1);
+ try {
+ EcompUser user = getUser(loginId);
+ responseJson = mapper.writeValueAsString(user);
+ if (logger.isDebugEnabled())
+ logger.debug("doGet: getUser: " + responseJson);
+ } catch (Exception ex) {
+ responseJson = buildJsonResponse(ex);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ logger.error("doGet: getUser: caught exception", ex);
+ }
+ }
+ // Example: /user/fi241c/roles <-- get roles for user fi241c
+ else if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && requestUri.endsWith("/roles")) {
+ String loginId = requestUri.substring(requestUri.indexOf("/user/") + ("/user").length() + 1,
+ requestUri.lastIndexOf('/'));
+ try {
+ List<EcompRole> roles = getUserRoles(loginId);
+ responseJson = mapper.writeValueAsString(roles);
+ if (logger.isDebugEnabled())
+ logger.debug("doGet: getUserRoles: " + responseJson);
+ } catch (Exception ex) {
+ responseJson = buildJsonResponse(ex);
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ logger.error("doGet: getUserRoles: caught exception", ex);
+ }
+ } else {
+ logger.warn("doGet: no match found for request");
+ responseJson = buildJsonResponse(false, "No match for request");
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ } catch (Exception ex) {
+ logger.error("doGet: Failed to process request", ex);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ responseJson = buildJsonResponse(ex);
+ }
+ writeAndFlush(response, contentTypeAppJson, responseJson);
+ }
+
+ public String getSessionTimeOuts() {
+ return PortalTimeoutHandler.gatherSessionExtensions();
+ }
+
+ public boolean timeoutSession(String portalJSessionId) {
+ return PortalTimeoutHandler.invalidateSession(portalJSessionId);
+ }
+
+ public boolean updateSessionTimeOuts(String sessionMap) {
+ return PortalTimeoutHandler.updateSessionExtensions(sessionMap);
+ }
+
+ @Override
+ public void pushUser(EcompUser user) throws PortalAPIException {
+ portalRestApiServiceImpl.pushUser(user);
+ }
+
+ @Override
+ public void editUser(String loginId, EcompUser user) throws PortalAPIException {
+ portalRestApiServiceImpl.editUser(loginId, user);
+ }
+
+ @Override
+ public EcompUser getUser(String loginId) throws PortalAPIException {
+ return portalRestApiServiceImpl.getUser(loginId);
+ }
+
+ @Override
+ public List<EcompUser> getUsers() throws PortalAPIException {
+ return portalRestApiServiceImpl.getUsers();
+ }
+
+ @Override
+ public List<EcompRole> getAvailableRoles(String requestedLoginId) throws PortalAPIException {
+ return portalRestApiServiceImpl.getAvailableRoles(requestedLoginId);
+ }
+
+ @Override
+ public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException {
+ portalRestApiServiceImpl.pushUserRole(loginId, roles);
+ }
+
+ @Override
+ public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException {
+ return portalRestApiServiceImpl.getUserRoles(loginId);
+ }
+
+ @Override
+ public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException {
+ return portalRestApiServiceImpl.isAppAuthenticated(request);
+ }
+
+ /**
+ * Sets the content type and writes the response.
+ *
+ * @param response
+ * @param contentType
+ * @param responseBody
+ * @throws IOException
+ */
+ private void writeAndFlush(HttpServletResponse response, String contentType, String responseBody)
+ throws IOException {
+ response.setContentType(contentType);
+ PrintWriter out = response.getWriter();
+ out.print(responseBody);
+ out.flush();
+ }
+
+ /**
+ * Reads the request body and closes the input stream.
+ *
+ * @param request
+ * @return String read from the request, the empty string if nothing is read.
+ * @throws IOException
+ */
+ private static String readRequestBody(HttpServletRequest request) throws IOException {
+
+ String body = null;
+ StringBuilder stringBuilder = new StringBuilder();
+ BufferedReader bufferedReader = null;
+ try {
+ InputStream inputStream = request.getInputStream();
+ if (inputStream != null) {
+ bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
+ char[] charBuffer = new char[1024];
+ int bytesRead = -1;
+ while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
+ stringBuilder.append(charBuffer, 0, bytesRead);
+ }
+ } else {
+ stringBuilder.append("");
+ }
+ } finally {
+ if (bufferedReader != null) {
+ try {
+ bufferedReader.close();
+ } catch (IOException ex) {
+ throw ex;
+ }
+ }
+ }
+ body = stringBuilder.toString();
+ return body;
+ }
+
+ /**
+ * Builds JSON object with status + message response body.
+ *
+ * @param success
+ * True to indicate success, false to signal failure.
+ * @param msg
+ * Message to include in the response object; ignored if null.
+ * @return
+ *
+ * <pre>
+ * { "status" : "ok" (or "error"), "message": "some explanation" }
+ * </pre>
+ */
+ private String buildJsonResponse(boolean success, String msg) {
+ PortalAPIResponse response = new PortalAPIResponse(success, msg);
+ String json = null;
+ try {
+ json = mapper.writeValueAsString(response);
+ } catch (JsonProcessingException ex) {
+ // Truly should never, ever happen
+ json = "{ \"status\": \"error\",\"message\":\"" + ex.toString() + "\" }";
+ }
+ return json;
+ }
+
+ /**
+ * Builds JSON object with status of error and message containing stack trace
+ * for the specified throwable.
+ *
+ * @param t
+ * Throwable with stack trace to use as message
+ *
+ * @return
+ *
+ * <pre>
+ * { "status" : "error", "message": "some-big-stacktrace" }
+ * </pre>
+ */
+ private String buildJsonResponse(Throwable t) {
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw);
+ t.printStackTrace(pw);
+ return buildJsonResponse(false, sw.toString());
+ }
+
+ @Override
+ public String getUserId(HttpServletRequest request) throws PortalAPIException {
+ return portalRestApiServiceImpl.getUserId(request);
+ }
+
+ public static IPortalRestAPIService getPortalRestApiServiceImpl() {
+ return portalRestApiServiceImpl;
+ }
+
+ public static void setPortalRestApiServiceImpl(IPortalRestAPIService portalRestApiServiceImpl) {
+ PortalRestAPIProxy.portalRestApiServiceImpl = portalRestApiServiceImpl;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.crossapi;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class SessionCommunicationService {
+
+ protected static final Log logger = LogFactory.getLog(SessionCommunicationService.class);
+
+ /**
+ * Calls the ECOMP Portal to retrieve the session slot check interval.
+ *
+ * @param ecompRestURL
+ * Remote system URL
+ * @param userName
+ * application user name used for authentication at Portal
+ * @param password
+ * application password used for authentication at Portal
+ * @param uebKey
+ * application UEB key (basically application ID) used for
+ * authentication at Portal
+ * @return Content read from the remote REST endpoint
+ */
+ public static String getSessionSlotCheckInterval(String ecompRestURL, String userName, String password,
+ String uebKey) {
+ try {
+ String url = ecompRestURL + "/getSessionSlotCheckInterval";
+
+ URL obj = new URL(url);
+
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+
+ // optional default is GET
+ con.setRequestMethod("GET");
+ con.setConnectTimeout(3000);
+ con.setReadTimeout(8000);
+ // add request header
+ con.setRequestProperty("username", userName);
+ con.setRequestProperty("password", password);
+ con.setRequestProperty("uebkey", uebKey);
+
+ int responseCode = con.getResponseCode();
+ if (logger.isDebugEnabled()) {
+ logger.debug("getSessionSlotCheckInterval: Sending 'GET' request to URL : " + url);
+ logger.debug("getSessionSlotCheckInterval: Response Code : " + responseCode);
+ }
+
+ StringBuffer response = new StringBuffer();
+ try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"))) {
+ String inputLine;
+ while ((inputLine = in.readLine()) != null)
+ response.append(inputLine);
+ }
+ catch (Exception ex) {
+ logger.error("getSessionSlotCheckInterval failed to read stream", ex);
+ }
+ return response.toString();
+ } catch (Exception e) {
+ logger.error("getSessionSlotCheckInterval: failed to fetch the session slot check", e);
+ return null;
+ }
+
+ }
+
+ /**
+ * Calls the ECOMP Portal to request an extension of the current session.
+ *
+ * @param ecompRestURL
+ * Remote system URL
+ * @param userName
+ * application user name used for authentication at Portal
+ * @param password
+ * application password used for authentication at Portal
+ * @param uebKey
+ * application UEB key (basically application ID) used for
+ * authentication at Portal
+ * @param sessionTimeoutMap
+ * Session timeout map
+ * @return Content read from the remote REST endpoint
+ */
+ public static String requestPortalSessionTimeoutExtension(String ecompRestURL, String userName, String password,
+ String uebKey, String sessionTimeoutMap) {
+
+ try {
+
+ String url = ecompRestURL + "/extendSessionTimeOuts";
+ URL obj = new URL(url);
+
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+
+ con.setRequestMethod("POST");
+ con.setConnectTimeout(3000);
+ con.setReadTimeout(15000);
+
+ // add request header
+ con.setRequestProperty("username", userName);
+ con.setRequestProperty("password", password);
+ con.setRequestProperty("uebkey", uebKey);
+ con.setRequestProperty("sessionMap", sessionTimeoutMap);
+ con.setDoInput(true);
+ con.setDoOutput(true);
+ con.getOutputStream().write(sessionTimeoutMap.getBytes());
+ con.getOutputStream().flush();
+ con.getOutputStream().close();
+
+ // con.set
+
+ int responseCode = con.getResponseCode();
+ if (logger.isDebugEnabled()) {
+ logger.debug("requestPortalSessionTimeoutExtension: Sending 'GET' request to URL : " + url);
+ logger.debug("requestPortalSessionTimeoutExtension: Response Code : " + responseCode);
+ }
+
+ StringBuffer response = new StringBuffer();
+ try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
+ String inputLine;
+ while ((inputLine = in.readLine()) != null) {
+ response.append(inputLine);
+ }
+ } catch (Exception ex) {
+ logger.error("requestPortalSessionTimeoutExtension failed", ex);
+ }
+ return response.toString();
+ } catch (Exception e) {
+ logger.error("requestPortalSessionTimeoutExtension: failed to request Portal to extend time out ", e);
+ return null;
+ }
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.exception;
+
+public class CipherUtilException extends Exception {
+
+ private static final long serialVersionUID = -4163367786939629691L;
+
+ public CipherUtilException() {
+ super();
+ }
+
+ public CipherUtilException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+
+ public CipherUtilException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public CipherUtilException(String message) {
+ super(message);
+ }
+
+ public CipherUtilException(Throwable cause) {
+ super(cause);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.exception;
+
+public class PortalAPIException extends Exception{
+
+ private static final long serialVersionUID = 4854048794984375707L;
+
+ public PortalAPIException() {
+ super();
+ }
+
+ public PortalAPIException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+
+ public PortalAPIException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public PortalAPIException(String message) {
+ super(message);
+ }
+
+ public PortalAPIException(Throwable cause) {
+ super(cause);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.listener;
+
+import java.io.Serializable;
+
+import javax.servlet.http.HttpSession;
+import javax.servlet.http.HttpSessionBindingEvent;
+import javax.servlet.http.HttpSessionBindingListener;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+
+public class PortalTimeoutBindingListener implements HttpSessionBindingListener, Serializable {
+
+ private static final long serialVersionUID = -8036365986695276137L;
+
+ private final Log logger = LogFactory.getLog(getClass());
+
+ @Override
+ public void valueBound(HttpSessionBindingEvent event) {
+ final HttpSession session = event.getSession();
+ PortalTimeoutHandler.sessionMap.put((String) session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID),
+ session);
+ }
+
+ @Override
+ public void valueUnbound(HttpSessionBindingEvent event) {
+ final HttpSession session = event.getSession();
+ String portalJSessionId = (String) session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID);
+ logger.debug(portalJSessionId + " getting removed");
+ PortalTimeoutHandler.sessionMap.remove(portalJSessionId);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.listener;
+
+import java.util.Calendar;
+import java.util.Hashtable;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.onap.portalsdk.core.onboarding.crossapi.SessionCommunicationService;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.restful.domain.PortalTimeoutVO;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * Invoked by listeners (UserContextListener and UserSessionListener) to track
+ * user sessions.
+ */
+public class PortalTimeoutHandler {
+
+ protected static final SessionCommInf sessionComm = new SessionComm();
+
+ public interface SessionCommInf {
+ public Integer fetchSessionSlotCheckInterval(String... params);
+
+ public void extendSessionTimeOuts(String... sessionMap);
+ }
+
+ public static class SessionComm implements SessionCommInf {
+ public Integer fetchSessionSlotCheckInterval(String... params) {
+
+ String ecompRestURL = params[0];
+ String userName = params[1];
+ String pwd = params[2];
+ String uebKey = params[3];
+
+ String sessionSlot = SessionCommunicationService.getSessionSlotCheckInterval(ecompRestURL, userName, pwd,
+ uebKey);
+ if (sessionSlot == null)
+ return null;
+ return Integer.parseInt(sessionSlot);
+ }
+
+ public void extendSessionTimeOuts(String... params) {
+
+ String ecompRestURL = params[0];
+ String userName = params[1];
+ String pwd = params[2];
+ String uebKey = params[3];
+ String sessionTimeoutMap = params[4];
+
+ SessionCommunicationService.requestPortalSessionTimeoutExtension(ecompRestURL, userName, pwd, uebKey,
+ sessionTimeoutMap);
+ }
+ }
+
+ public static final Map<String, HttpSession> sessionMap = new Hashtable<String, HttpSession>();
+ public static final Integer repeatInterval = 15 * 60; // 15 minutes
+ protected static final Log logger = LogFactory.getLog(PortalTimeoutHandler.class);
+ static ObjectMapper mapper = new ObjectMapper();
+ private static PortalTimeoutHandler timeoutHandler;
+
+ public static PortalTimeoutHandler getInstance() {
+ if (timeoutHandler == null)
+ timeoutHandler = new PortalTimeoutHandler();
+
+ return timeoutHandler;
+ }
+
+ /**
+ * TODO: remove static
+ *
+ * @param portalJSessionId
+ * Portal (remote) session ID
+ * @param jSessionId
+ * Local session ID
+ * @param session
+ * HttpSession
+ */
+ public static void sessionCreated(String portalJSessionId, String jSessionId, HttpSession session) {
+
+ storeMaxInactiveTime(session);
+
+ // this key is a combination of portal jsession id and app session id
+ String jSessionKey = jSessionKey(jSessionId, portalJSessionId);
+ Object jSessionKeySessionVal = session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID);
+
+ // do not reset the attributes if the same values have already been set
+ // because that will cause PortalTimeoutBindingListener to unbound the
+ // value from map
+ if (jSessionKeySessionVal != null && jSessionKeySessionVal.equals(jSessionKey)) {
+ logger.debug(" Session Values already exist in te map for sessionKey " + jSessionKey);
+ return;
+ }
+
+ session.setAttribute(PortalApiConstants.PORTAL_JSESSION_ID, jSessionKey);
+
+ // session binding listener will add this value to the static map
+ // and with session replication the listener will fire in all tomcat
+ // instances
+ session.setAttribute(PortalApiConstants.PORTAL_JSESSION_BIND, new PortalTimeoutBindingListener());
+ // sessionMap.put((String)session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID),
+ // session);
+
+ }
+
+ /**
+ * TODO: remove static
+ *
+ * @param session
+ */
+ protected static void storeMaxInactiveTime(HttpSession session) {
+ if (session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME) == null)
+ session.setAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME, session.getMaxInactiveInterval());
+ }
+
+ /**
+ * TODO: remove static
+ *
+ * @param session
+ * HttpSession
+ */
+ public static void sessionDestroyed(HttpSession session) {
+ try {
+ logger.info(" Session getting destroyed - id: " + session.getId());
+ session.removeAttribute(PortalApiConstants.PORTAL_JSESSION_BIND);
+ // sessionMap.remove((String)session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID));
+ } catch (Exception e) {
+ logger.error("sessionDestroyed failed", e);
+ }
+ }
+
+ /***
+ * TODO: remove static
+ *
+ * @param portalJSessionId
+ * Portal session ID
+ * @return true on success, false if the session cannot be found, etc.
+ */
+ public static boolean invalidateSession(String portalJSessionId) {
+ boolean result = false;
+ logger.debug("Session Management: request from Portal to invalidate the session: " + portalJSessionId);
+ for (String jSessionKey : sessionMap.keySet()) {
+ try {
+ HttpSession session = sessionMap.get(jSessionKey);
+ if (portalJSessionId(jSessionKey).equals(portalJSessionId)) {
+ session.invalidate();
+ result = true;
+ }
+ } catch (Exception e) {
+ logger.error("invalidateSession failed", e);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * TODO: remove static
+ *
+ * @return json version of the timeout map: session ID -> timeout object
+ */
+ public static String gatherSessionExtensions() {
+ logger.debug("Session Management: gatherSessionExtensions");
+
+ Map<String, PortalTimeoutVO> sessionTimeoutMap = new Hashtable<String, PortalTimeoutVO>();
+ String jsonMap = "";
+
+ for (String jSessionKey : sessionMap.keySet()) {
+
+ try {
+ // get the expirytime in seconds
+ HttpSession session = sessionMap.get(jSessionKey);
+
+ Long lastAccessedTimeMilliSec = session.getLastAccessedTime();
+ Long maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000L;
+ // Long currentTimeMilliSec =
+ // Calendar.getInstance().getTimeInMillis() ;
+ // (maxIntervalMilliSec - (currentTimeMilliSec -
+ // lastAccessedTimeMilliSec) + ;
+ Calendar instance = Calendar.getInstance();
+ instance.setTimeInMillis(session.getLastAccessedTime());
+ logger.debug("Session Management: Last Accessed time for " + jSessionKey + ": " + instance.getTime());
+
+ Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec;
+
+ sessionTimeoutMap.put(portalJSessionId(jSessionKey),
+ getSingleSessionTimeoutObj(jSessionKey, sessionTimOutMilliSec));
+ logger.debug("Session Management: putting session in map " + jSessionKey + " sessionTimoutSec"
+ + (int) (sessionTimOutMilliSec / 1000));
+
+ jsonMap = mapper.writeValueAsString(sessionTimeoutMap);
+
+ } catch (Exception e) {
+ logger.error("gatherSessionExtensions failed", e);
+ }
+
+ }
+
+ return jsonMap;
+
+ }
+
+ /**
+ * TODO: remove static
+ *
+ * @param sessionTimeoutMapStr
+ * Session timeout map as string
+ * @return true on success, false otherwise
+ */
+ public static boolean updateSessionExtensions(String sessionTimeoutMapStr) {
+ logger.debug("Session Management: updateSessionExtensions");
+ // Map<String,Object> sessionTimeoutMap =
+ // mapper.readValue(sessionTimeoutMapStr, Map.class);
+ Map<String, PortalTimeoutVO> sessionTimeoutMap = null;
+
+ try {
+ TypeReference<Hashtable<String, PortalTimeoutVO>> typeRef = new TypeReference<Hashtable<String, PortalTimeoutVO>>() {
+ };
+ sessionTimeoutMap = mapper.readValue(sessionTimeoutMapStr, typeRef);
+ } catch (Exception e) {
+ logger.error("updateSessionExtensions failed to parse the sessionTimeoutMap from portal", e);
+ return false;
+ }
+
+ boolean result = true;
+ for (String jPortalSessionId : sessionTimeoutMap.keySet()) {
+ try {
+ PortalTimeoutVO extendedTimeoutVO = mapper.readValue(
+ mapper.writeValueAsString(sessionTimeoutMap.get(jPortalSessionId)), PortalTimeoutVO.class);
+ HttpSession session = sessionMap.get(jSessionKey(extendedTimeoutVO.getjSessionId(), jPortalSessionId));
+
+ if (session == null) {
+ continue;
+ }
+
+ Long lastAccessedTimeMilliSec = session.getLastAccessedTime();
+ Long maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000L;
+ Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec;
+
+ Long maxTimeoutTimeMilliSec = extendedTimeoutVO.getSessionTimOutMilliSec();
+ if (maxTimeoutTimeMilliSec > sessionTimOutMilliSec) {
+ session.setMaxInactiveInterval((int) (maxTimeoutTimeMilliSec - lastAccessedTimeMilliSec) / 1000);
+ logger.debug("Session Management: extended session for :" + session.getId() + " to :"
+ + (int) (maxTimeoutTimeMilliSec / 1000));
+ // System.out.println("!!!!!!!!!extended session for :" +
+ // session.getId() + " to :" +
+ // (int)(maxTimeoutTimeMilliSec/1000));
+ }
+ } catch (Exception e) {
+ logger.error("updateSessionExtensions failed to update session timeouts", e);
+ // Signal a problem if any one of them fails
+ result = false;
+ }
+
+ }
+ return result;
+ }
+
+ /**
+ * TODO: Remove static
+ *
+ * @param request
+ * HttpServletRequest
+ * @param userName
+ * User name
+ * @param pwd
+ * Password
+ * @param uebKey
+ * UEB key (application ID)
+ * @param ecompRestURL
+ * Remote system URL
+ * @param _sessionComm
+ * Session communication information
+ */
+ public static void handleSessionUpdatesNative(HttpServletRequest request, String userName, String pwd,
+ String uebKey, String ecompRestURL, SessionCommInf _sessionComm) {
+
+ if (_sessionComm == null) {
+ _sessionComm = sessionComm;
+ }
+ try {
+ synchronizeSessionForLastMinuteRequests(request, ecompRestURL, userName, pwd, uebKey, _sessionComm);
+ } catch (Exception e) {
+ logger.error("handleSesionUpdatesNative failed", e);
+ }
+ resetSessionMaxIdleTimeOut(request);
+ }
+
+ /**
+ * TODO: remove Static
+ *
+ * @param request
+ * HttpServletRequest
+ * @param ecompRestURL
+ * Remote URL
+ * @param userName
+ * user name
+ * @param pwd
+ * password
+ * @param uebKey
+ * UEB key
+ * @param _sessionComm
+ * session information
+ * @throws JsonProcessingException
+ * On failure to serialize
+ */
+ public static void synchronizeSessionForLastMinuteRequests(HttpServletRequest request, String ecompRestURL,
+ String userName, String pwd, String uebKey, SessionCommInf _sessionComm) throws JsonProcessingException {
+
+ HttpSession session = request.getSession(false);
+ if (session == null)
+ return;
+
+ Object portalSessionSlotCheckObj = session.getServletContext()
+ .getAttribute(PortalApiConstants.PORTAL_SESSION_SLOT_CHECK);
+ Integer portalSessionSlotCheckinMilliSec = 5 * 60 * 1000; // (5 minutes)
+ if (portalSessionSlotCheckObj != null) {
+ portalSessionSlotCheckinMilliSec = Integer.valueOf(portalSessionSlotCheckObj.toString());
+ } else {
+ portalSessionSlotCheckObj = _sessionComm
+ .fetchSessionSlotCheckInterval(new String[] { ecompRestURL, userName, pwd, uebKey });
+ logger.debug("Fetching Portal Session Slot Object: " + portalSessionSlotCheckObj);
+ if (portalSessionSlotCheckObj != null) {
+ portalSessionSlotCheckinMilliSec = Integer.valueOf(portalSessionSlotCheckObj.toString());
+ session.getServletContext().setAttribute(PortalApiConstants.PORTAL_SESSION_SLOT_CHECK,
+ portalSessionSlotCheckinMilliSec);
+ }
+ }
+
+ Object previousToLastAccessTimeObj = session.getAttribute(PortalApiConstants.SESSION_PREVIOUS_ACCESS_TIME);
+ final long lastAccessedTimeMilliSec = session.getLastAccessedTime();
+ if (previousToLastAccessTimeObj == null) {
+ previousToLastAccessTimeObj = lastAccessedTimeMilliSec;
+ session.setAttribute(PortalApiConstants.SESSION_PREVIOUS_ACCESS_TIME, previousToLastAccessTimeObj);
+ } else {
+ Long previousToLastAccessTime = (Long) previousToLastAccessTimeObj;
+ final int maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000;
+ if (maxIntervalMilliSec
+ - (lastAccessedTimeMilliSec - previousToLastAccessTime) <= portalSessionSlotCheckinMilliSec) {
+
+ String jSessionKey = (String) session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID);
+ Map<String, PortalTimeoutVO> sessionTimeoutMap = new Hashtable<String, PortalTimeoutVO>();
+ Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec;
+
+ sessionTimeoutMap.put(PortalTimeoutHandler.portalJSessionId(jSessionKey),
+ PortalTimeoutHandler.getSingleSessionTimeoutObj(jSessionKey, sessionTimOutMilliSec));
+ String jsonMap = mapper.writeValueAsString(sessionTimeoutMap);
+ logger.debug("Extension requested for all the Apps and Portal; JessionKey: " + jSessionKey
+ + "; SessionMap: " + sessionTimeoutMap);
+ _sessionComm.extendSessionTimeOuts(new String[] { ecompRestURL, userName, pwd, uebKey, jsonMap });
+ }
+
+ }
+ }
+
+ /**
+ * TODO: remove static
+ *
+ * @param request
+ * HttpServletRequest
+ */
+ public static void resetSessionMaxIdleTimeOut(HttpServletRequest request) {
+ try {
+ HttpSession session = request.getSession(false);
+ if (session == null)
+ return;
+ final Object maxIdleAttribute = session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME);
+ if (maxIdleAttribute != null) {
+ session.setMaxInactiveInterval(Integer.parseInt(maxIdleAttribute.toString()));
+ }
+ } catch (Exception e) {
+ logger.error("resetSessionMaxIdleTimeout failed", e);
+ }
+
+ }
+
+ /**
+ *
+ * @param jSessionKey
+ * @param sessionTimOutMilliSec
+ * @return
+ */
+ private static PortalTimeoutVO getSingleSessionTimeoutObj(String jSessionKey, Long sessionTimOutMilliSec) {
+ return new PortalTimeoutVO(jSessionId(jSessionKey), sessionTimOutMilliSec);
+ }
+
+ /**
+ *
+ * @param jSessionId
+ * @param portalJSessionId
+ * @return
+ */
+ private static String jSessionKey(String jSessionId, String portalJSessionId) {
+ return portalJSessionId + "-" + jSessionId;
+ }
+
+ /**
+ *
+ * @param jSessionKey
+ * @return
+ */
+ private static String portalJSessionId(String jSessionKey) {
+ return jSessionKey.split("-")[0];
+ }
+
+ /**
+ *
+ * @param jSessionKey
+ * @return
+ */
+ private static String jSessionId(String jSessionKey) {
+ return jSessionKey.split("-")[1];
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.listener;
+
+import java.util.HashMap;
+
+import javax.servlet.ServletContext;
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+import javax.servlet.annotation.WebListener;
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+
+@WebListener
+public class UserContextListener implements ServletContextListener {
+
+ public void contextInitialized(ServletContextEvent event) {
+ ServletContext context = event.getServletContext();
+ //
+ // create a map to store references to all the active
+ // sessions and bind it to context scope.
+ //
+ HashMap<String, HttpSession> activeUsers = new HashMap<String, HttpSession>();
+ context.setAttribute(PortalApiConstants.ACTIVE_USERS_NAME, activeUsers);
+ }
+
+ /**
+ * Needed for the ServletContextListener interface.
+ */
+ public void contextDestroyed(ServletContextEvent event) {
+ // To overcome the problem with losing the session references
+ // during server restarts, put code here to serialize the
+ // activeUsers HashMap. Then put code in the contextInitialized
+ // method that reads and reloads it if it exists...
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.listener;
+
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.annotation.WebListener;
+import javax.servlet.http.HttpSession;
+import javax.servlet.http.HttpSessionEvent;
+import javax.servlet.http.HttpSessionListener;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+
+/**
+ * Listens to session-create and session-destroy events.
+ */
+@WebListener
+public class UserSessionListener implements HttpSessionListener {
+
+ private Log logger = LogFactory.getLog(getClass());
+
+ public static Map<String, HttpSession> activeSessions = new Hashtable<String, HttpSession>();
+
+ public void init(ServletConfig config) {
+ }
+
+ /**
+ * Adds sessions to the context-scoped HashMap when they begin.
+ */
+ public void sessionCreated(HttpSessionEvent event) {
+ HttpSession session = event.getSession();
+ ServletContext context = session.getServletContext();
+ @SuppressWarnings("unchecked")
+ HashMap<String, HttpSession> activeUsers = (HashMap<String, HttpSession>) context
+ .getAttribute(PortalApiConstants.ACTIVE_USERS_NAME);
+ if (activeUsers != null)
+ activeUsers.put(session.getId(), session);
+ context.setAttribute(PortalApiConstants.ACTIVE_USERS_NAME, activeUsers);
+ activeSessions.put(session.getId(), session);
+ session.getServletContext().setAttribute(PortalApiConstants.MAX_IDLE_TIME, session.getMaxInactiveInterval());
+ }
+
+ /**
+ * Removes sessions from the context-scoped HashMap when they expire or are
+ * invalidated.
+ */
+ public void sessionDestroyed(HttpSessionEvent event) {
+ try {
+ HttpSession session = event.getSession();
+ ServletContext context = session.getServletContext();
+ @SuppressWarnings("unchecked")
+ HashMap<String, HttpSession> activeUsers = (HashMap<String, HttpSession>) context
+ .getAttribute(PortalApiConstants.ACTIVE_USERS_NAME);
+ if (activeUsers != null)
+ activeUsers.remove(session.getId());
+ activeSessions.remove(session.getId());
+ PortalTimeoutHandler.sessionDestroyed(session);
+ } catch (Exception e) {
+ logger.warn(e.getMessage(), e);
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.rest;
+
+import java.io.IOException;
+
+/**
+ * Provides a convenience method for fetching the favorites for a user from the
+ * ECOMP Portal.
+ */
+public class FavoritesClient {
+
+ /**
+ * Fetches the favorites data from portal
+ *
+ * @param userId
+ * userId value that it should be using to fetch the
+ * data
+ * @param appName
+ * Application name for logging etc.
+ * @param requestId
+ * 128-bit UUID value to uniquely identify the transaction; if null, a new one is generated.
+ * @param appUserName
+ * REST API user-name
+ * @param appPassword
+ * REST API decrypted password
+ * @return JSON with favorites
+ * @throws IOException
+ * on any failure
+ */
+ public static String getFavorites(String userId, String appName, String requestId, String appUserName,
+ String appPassword) throws IOException {
+ return RestWebServiceClient.getInstance().getPortalContent("/getFavorites", userId, appName, requestId, appUserName,
+ appPassword,true);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.rest;
+
+import java.io.IOException;
+
+/**
+ * Provides a convenience method for fetching the functional menu for a user
+ * from the ECOMP Portal via UEB.
+ */
+public class FunctionalMenuClient {
+
+ /**
+ * Fetches the functional menu data from the configured ECOMP Portal
+ * instance.
+ *
+ * @param userId
+ * userId for the user to whom the menu will be shown
+ * @param appName
+ * Application name for logging etc.
+ * @param requestId
+ * 128-bit UUID value to uniquely identify the transaction; if
+ * null, a new one is generated.
+ * @param appUserName
+ * REST API user name, used by Portal to authenticate the request
+ * @param appPassword
+ * REST API password (in the clear, not encrypted), used by
+ * Portal to authenticate the request
+ * @return JSON with functional menu
+ * @throws IOException
+ * on any failure
+ */
+ public static String getFunctionalMenu(String userId, String appName, String requestId, String appUserName,
+ String appPassword) throws IOException {
+ return RestWebServiceClient.getInstance().getPortalContent("/functionalMenuItemsForUser", userId, appName,
+ requestId, appUserName, appPassword,true);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.rest;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.Base64;
+import java.util.UUID;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
+
+/**
+ * Simple REST client for GET, POST and DELETE operations against the Portal
+ * application.
+ */
+public class RestWebServiceClient {
+
+ private final Log logger = LogFactory.getLog(RestWebServiceClient.class);
+
+ /**
+ * Singleton instance
+ */
+ private static RestWebServiceClient instance = null;
+
+ /**
+ * Constructor is private. Clients should obtain an instance via getInstance().
+ */
+ private RestWebServiceClient() {
+ }
+
+ /**
+ * Gets the static instance of RestWebServiceClient; creates it if necessary.
+ * Synchronized to be thread safe.
+ *
+ * @return Static instance of RestWebServiceClient.
+ */
+ public static synchronized RestWebServiceClient getInstance() {
+ if (instance == null)
+ instance = new RestWebServiceClient();
+ return instance;
+ }
+
+ /**
+ * Convenience method that fetches the URL for the Portal REST API endpoint and
+ * the application UEB key, then calls
+ * {@link #get(String, String, String, String, String, String, String)} to
+ * access the Portal's REST endpoint.
+ *
+ * @param restPath
+ * Partial path of the endpoint; e.g., "/specialRestService"
+ * @param userId
+ * userId for the user originating the request
+ * @param appName
+ * Application Name for logging.
+ * @param requestId
+ * 128-bit UUID value to uniquely identify the transaction.
+ * @param appUserName
+ * REST API user name for Portal to authenticate the request
+ * @param appPassword
+ * REST API password (in the clear, not encrypted) for Portal to
+ * authenticate the request
+ * @param isBasicAuth
+ * If true, send credentials as HTTP Basic Authentication
+ * @return Content from REST endpoint
+ * @throws IOException
+ * on any failure
+ */
+ public String getPortalContent(String restPath, String userId, String appName, String requestId, String appUserName,
+ String appPassword, boolean isBasicAuth) throws IOException {
+ String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
+ if (restURL == null) {
+ String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
+ logger.error(msg);
+ throw new IOException(msg);
+ }
+ String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
+ if (appUebKey == null) {
+ String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
+ logger.error(msg);
+ throw new IOException(msg);
+ }
+ final String restEndpointUrl = restURL + restPath;
+ if (isBasicAuth) {
+ return get(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, isBasicAuth);
+ }
+ return get(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword);
+ }
+
+ /**
+ * Makes a call to a Portal REST API using the specified URL and parameters.
+ *
+ * @param url
+ * Complete URL of the REST endpoint.
+ * @param loginId
+ * User that it should be fetching the data
+ * @param appName
+ * Application name for logging; if null or empty, defaulted to
+ * Unknown.
+ * @param requestId
+ * 128-bit UUID value to uniquely identify the transaction; if null
+ * or empty, one is generated.
+ * @param appUebKey
+ * Unique key for the application, used by Portal to authenticate the
+ * request
+ * @param appUserName
+ * REST API user name, used by Portal to authenticate the request
+ * @param appPassword
+ * REST API password, used by Portal to authenticate the request
+ * @return Content from REST endpoint
+ * @throws IOException
+ * On any failure; e.g., unknown host.
+ */
+ public String get(String url, String loginId, String appName, String requestId, String appUebKey,
+ String appUserName, String appPassword) throws IOException {
+ return get(url, loginId, appName, requestId, appUebKey, appUserName, appPassword, false);
+ }
+
+ /**
+ * Makes a call to a Portal REST API using the specified URL and parameters.
+ *
+ * @param url
+ * Complete URL of the REST endpoint.
+ * @param loginId
+ * User that it should be fetching the data
+ * @param appName
+ * Application name for logging; if null or empty, defaulted to
+ * Unknown.
+ * @param requestId
+ * 128-bit UUID value to uniquely identify the transaction; if null
+ * or empty, one is generated.
+ * @param appUebKey
+ * Unique key for the application, used by Portal to authenticate the
+ * request
+ * @param appUserName
+ * REST API user name, used by Portal to authenticate the request
+ * @param appPassword
+ * REST API password, used by Portal to authenticate the request
+ * @param useBasicAuth
+ * If true, send credentials as HTTP Basic Authentication
+ * @return Content from REST endpoint
+ * @throws IOException
+ * On any failure; e.g., unknown host.
+ */
+ public String get(String url, String loginId, String appName, String requestId, String appUebKey,
+ String appUserName, String appPassword, Boolean useBasicAuth) throws IOException {
+
+ logger.debug("RestWebServiceClient.get (" + url + ") operation is started.");
+
+ if (appName == null || appName.trim().length() == 0)
+ appName = "Unknown";
+ if (requestId == null || requestId.trim().length() == 0)
+ requestId = UUID.randomUUID().toString();
+
+ URL obj = new URL(url);
+ // Create the connection object
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+ con.setRequestMethod("GET");
+ // if the portal property is set then gets the timeout value from portal
+ // properties
+ con.setConnectTimeout(3000);
+ if (PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT) != null)
+ con.setConnectTimeout(Integer
+ .parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)));
+ con.setReadTimeout(8000);
+ if (PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT) != null)
+ con.setReadTimeout(
+ Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)));
+
+ // add request header
+ con.setRequestProperty("uebkey", appUebKey);
+ con.setRequestProperty("LoginId", loginId);
+ con.setRequestProperty("user-agent", appName);
+ con.setRequestProperty("X-ECOMP-RequestID", requestId);
+ con.setRequestProperty("username", appUserName);
+ con.setRequestProperty("password", appPassword);
+ if (useBasicAuth) {
+ String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
+ con.setRequestProperty("Authorization", "Basic " + encoding);
+ }
+
+ int responseCode = con.getResponseCode();
+ logger.debug("get: received response code '" + responseCode + "' while getting the '" + url + "' for user: "
+ + loginId);
+
+ final String response = readAndCloseStream(con.getInputStream());
+ if (logger.isDebugEnabled())
+ logger.debug("get: url " + url + " yielded " + response);
+ return response;
+ }
+
+ /**
+ * Convenience method that fetches the URL for the Portal REST API endpoint and
+ * the application UEB key, then calls
+ * {@link #post(String, String, String, String, String, String, String, String, String, boolean)}
+ * to access the Portal's REST endpoint.
+ *
+ * @param restPath
+ * Partial path of the endpoint; e.g., "/specialRestService"
+ * @param userId
+ * ID for the user originating the request
+ * @param appName
+ * Application Name for logging.
+ * @param requestId
+ * 128-bit UUID value to uniquely identify the transaction.
+ * @param appUserName
+ * REST API user name for Portal to authenticate the request; ignored
+ * if null
+ * @param appPassword
+ * REST API password (in the clear, not encrypted) for Portal to
+ * authenticate the request; ignored if null
+ * @param contentType
+ * content type for header
+ * @param content
+ * String to post
+ * @param isBasicAuth
+ * If true, use HTTP Basic Authentication
+ * @return Content from REST endpoint
+ * @throws IOException
+ * on any failure
+ */
+ public String postPortalContent(String restPath, String userId, String appName, String requestId,
+ String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth)
+ throws IOException {
+ String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
+
+ if (restURL == null) {
+ String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
+ logger.error(msg);
+ throw new IOException(msg);
+ }
+ String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
+ if (appUebKey == null) {
+ String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
+ logger.error(msg);
+ throw new IOException(msg);
+ }
+ final String separator = restURL.endsWith("/") || restPath.startsWith("/") ? "" : "/";
+ final String restEndpointUrl = restURL + separator + restPath;
+ return post(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, contentType,
+ content, isBasicAuth);
+ }
+
+ /**
+ * Makes a POST call to a Portal REST API using the specified URL and
+ * parameters.
+ *
+ * @param url
+ * Complete URL of the REST endpoint.
+ * @param loginId
+ * User who is fetching the data
+ * @param appName
+ * Application name for logging; if null or empty, defaulted to
+ * Unknown.
+ * @param requestId
+ * 128-bit UUID value to uniquely identify the transaction; if null
+ * or empty, one is generated.
+ * @param appUebKey
+ * Unique key for the application, used by Portal to authenticate the
+ * request
+ * @param appUserName
+ * REST API user name used by Portal to authenticate the request;
+ * ignored if null
+ * @param appPassword
+ * REST API password used by Portal to authenticate the request;
+ * ignored if null
+ * @param contentType
+ * MIME header
+ * @param content
+ * Content to POST
+ * @param isBasicAuth
+ * If true, use HTTP Basic Authentication
+ * @return Any content read from the endpoint
+ * @throws IOException
+ * On any error
+ */
+ public String post(String url, String loginId, String appName, String requestId, String appUebKey,
+ String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth)
+ throws IOException {
+
+ if (logger.isDebugEnabled())
+ logger.debug("RestWebServiceClient.post to URL " + url);
+ if (appName == null || appName.trim().length() == 0)
+ appName = "Unknown";
+ if (requestId == null || requestId.trim().length() == 0)
+ requestId = UUID.randomUUID().toString();
+
+ URL obj = new URL(url);
+ // Create the connection object
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+ con.setRequestMethod("POST");
+
+ con.setConnectTimeout(3000);
+ // if the portal property is set then gets the timeout value from portal
+ // properties
+ if (PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT) != null)
+ con.setConnectTimeout(Integer
+ .parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)));
+ con.setReadTimeout(15000);
+ if (PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT) != null)
+ con.setReadTimeout(
+ Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)));
+
+ // add request header
+ con.setRequestProperty("uebkey", appUebKey);
+ if (appUserName != null)
+ con.setRequestProperty("username", appUserName);
+ if (appPassword != null)
+ con.setRequestProperty("password", appPassword);
+ con.setRequestProperty("LoginId", loginId);
+ con.setRequestProperty("user-agent", appName);
+ con.setRequestProperty("X-ECOMP-RequestID", requestId);
+ con.setRequestProperty("Content-Type", contentType);
+ if (isBasicAuth) {
+ String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
+ con.setRequestProperty("Authorization", "Basic " + encoding);
+ }
+
+ con.setDoInput(true);
+ con.setDoOutput(true);
+ if (content != null) {
+ con.getOutputStream().write(content.getBytes());
+ }
+ con.getOutputStream().flush();
+ con.getOutputStream().close();
+
+ int responseCode = con.getResponseCode();
+ logger.debug("Response Code : " + responseCode);
+ final String response = readAndCloseStream(con.getInputStream());
+ return response;
+ }
+
+ /**
+ * Convenience method that fetches the URL for the Portal REST API endpoint and
+ * the application UEB key, then calls
+ * {@link #delete(String, String, String, String, String, String, String, String, String, boolean)}
+ * to access the Portal's REST endpoint.
+ *
+ * @param restPath
+ * Complete URL of the REST endpoint.
+ * @param userId
+ * User who is fetching the data
+ * @param appName
+ * Application name for logging; if null or empty, defaulted to
+ * Unknown.
+ * @param requestId
+ * 128-bit UUID value to uniquely identify the transaction; if null
+ * or empty, one is generated.
+ * @param appUserName
+ * REST API user name used by Portal to authenticate the request;
+ * ignored if null
+ * @param appPassword
+ * REST API password used by Portal to authenticate the request;
+ * ignored if null
+ * @param contentType
+ * MIME header
+ * @param content
+ * Content
+ * @param isBasicAuth
+ * If true, use HTTP Basic Authentication
+ * @return Any content read from the endpoint
+ * @throws IOException
+ * On any error
+ */
+ public String deletePortalContent(String restPath, String userId, String appName, String requestId,
+ String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth)
+ throws IOException {
+ String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
+ if (restURL == null) {
+ String msg = "deletePortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
+ logger.error(msg);
+ throw new IOException(msg);
+ }
+ String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
+ if (appUebKey == null) {
+ String msg = "deletePortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
+ logger.error(msg);
+ throw new IOException(msg);
+ }
+ final String separator = restURL.endsWith("/") || restPath.startsWith("/") ? "" : "/";
+ final String restEndpointUrl = restURL + separator + restPath;
+ return delete(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, contentType,
+ content, isBasicAuth);
+ }
+
+ /**
+ * Makes a DELETE call to a Portal REST API using the specified URL and
+ * parameters.
+ *
+ * @param url
+ * Complete URL of the REST endpoint.
+ * @param loginId
+ * User who is fetching the data
+ * @param appName
+ * Application name for logging; if null or empty, defaulted to
+ * Unknown.
+ * @param requestId
+ * 128-bit UUID value to uniquely identify the transaction; if null
+ * or empty, one is generated.
+ * @param appUebKey
+ * Unique key for the application, used by Portal to authenticate the
+ * request
+ * @param appUserName
+ * REST API user name used by Portal to authenticate the request;
+ * ignored if null
+ * @param appPassword
+ * REST API password used by Portal to authenticate the request;
+ * ignored if null
+ * @param contentType
+ * MIME header
+ * @param content
+ * Content
+ * @param isBasicAuth
+ * If true, use HTTP Basic Authentication
+ * @return Any content read from the endpoint
+ * @throws IOException
+ * On any error
+ */
+ public String delete(String url, String loginId, String appName, String requestId, String appUebKey,
+ String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth)
+ throws IOException {
+
+ if (logger.isDebugEnabled())
+ logger.debug("RestWebServiceClient.post to URL " + url);
+ if (appName == null || appName.trim().length() == 0)
+ appName = "Unknown";
+ if (requestId == null || requestId.trim().length() == 0)
+ requestId = UUID.randomUUID().toString();
+
+ URL obj = new URL(url);
+ // Create the connection object
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+ con.setRequestMethod("DELETE");
+ con.setConnectTimeout(3000);
+ // if the portal property is set then gets the timeout value from portal
+ // properties
+ if (PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT) != null)
+ con.setConnectTimeout(Integer
+ .parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)));
+ con.setReadTimeout(15000);
+ if (PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT) != null)
+ con.setReadTimeout(
+ Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)));
+
+ // add request header
+ con.setRequestProperty("uebkey", appUebKey);
+ if (appUserName != null)
+ con.setRequestProperty("username", appUserName);
+ if (appPassword != null)
+ con.setRequestProperty("password", appPassword);
+ con.setRequestProperty("LoginId", loginId);
+ con.setRequestProperty("user-agent", appName);
+ con.setRequestProperty("X-ECOMP-RequestID", requestId);
+ con.setRequestProperty("Content-Type", contentType);
+ if (isBasicAuth) {
+ String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
+ con.setRequestProperty("Authorization", "Basic " + encoding);
+ }
+
+ con.setDoInput(true);
+ con.setDoOutput(true);
+ if (content != null)
+ con.getOutputStream().write(content.getBytes());
+ con.getOutputStream().flush();
+ con.getOutputStream().close();
+
+ int responseCode = con.getResponseCode();
+ logger.debug("Response Code : " + responseCode);
+ final String response = readAndCloseStream(con.getInputStream());
+ return response;
+ }
+
+ /**
+ * Reads content of string to a StringBuffer, decoded as UTF-8, and returns as
+ * string.
+ *
+ * @param inputStream
+ * Stream to read
+ * @return String read
+ * @throws IOException
+ */
+ private String readAndCloseStream(InputStream inputStream) throws IOException {
+ StringBuffer sb = new StringBuffer();
+ InputStreamReader in = null;
+ char[] buf = new char[8196];
+ int bytes;
+ try {
+ in = new InputStreamReader(inputStream, "UTF-8");
+ while ((bytes = in.read(buf)) > 0)
+ sb.append(new String(buf, 0, bytes));
+ } finally {
+ if (in != null)
+ in.close();
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Basic unit test for the client to call Portal app on localhost.
+ *
+ * @param args
+ * Ignored
+ * @throws IOException
+ * On failure
+ */
+ public static void main(String[] args) throws IOException {
+ RestWebServiceClient client = RestWebServiceClient.getInstance();
+ final String getUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/analytics";
+ String get = client.get(getUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword", null);
+ System.out.println("Get result:\n" + get);
+ final String postUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/storeAnalytics";
+ final String content = " { " + " \"action\" : \"test1\", " + " \"page\" : \"test2\", "
+ + " \"function\" : \"test3\", " + " \"userid\" : \"ab1234\" " + "}";
+ String post = client.post(postUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword",
+ "application/json", content, true);
+ System.out.println("Post result:\n" + post);
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.util;
+
+import java.io.UnsupportedEncodingException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
+
+public class CipherUtil {
+
+ private static final Log logger = LogFactory.getLog(CipherUtil.class);
+
+ /**
+ * Default key.
+ */
+ private final static String key = "AGLDdG4D04BKm2IxIWEr8o==!";
+
+ /**
+ * Encrypts the text using the specified secret key.
+ *
+ * @param plainText
+ * Text to encrypt
+ * @param secretKey
+ * Key to use for encryption
+ * @return encrypted version of plain text.
+ * @throws CipherUtilException
+ * if any encryption step fails
+ */
+ public static String encrypt(String plainText, String secretKey) throws CipherUtilException {
+ String encryptedString = null;
+ try {
+ byte[] encryptText = plainText.getBytes("UTF-8");
+ byte[] rawKey = Base64.decodeBase64(secretKey);
+ SecretKeySpec sKeySpec = new SecretKeySpec(rawKey, "AES");
+ Cipher cipher = Cipher.getInstance("AES");
+ cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
+ encryptedString = Base64.encodeBase64String(cipher.doFinal(encryptText));
+ } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException
+ | NoSuchPaddingException | UnsupportedEncodingException ex) {
+ logger.error("encrypt failed", ex);
+ throw new CipherUtilException(ex);
+ }
+ return encryptedString;
+ }
+
+ /**
+ * Encrypts the text using a default secret key.
+ *
+ * @param plainText
+ * Text to encrypt
+ * @return Encrypted Text
+ * @throws CipherUtilException
+ * if any decryption step fails
+ */
+ public static String encrypt(String plainText) throws CipherUtilException {
+ return CipherUtil.encrypt(plainText, key);
+ }
+
+ /**
+ * Decrypts the text using the specified secret key.
+ *
+ * @param encryptedText
+ * Text to decrypt
+ * @param secretKey
+ * Key to use for decryption
+ * @return plain text version of encrypted text
+ * @throws CipherUtilException
+ * if any decryption step fails
+ */
+ public static String decrypt(String encryptedText, String secretKey) throws CipherUtilException {
+ String encryptedString = null;
+ try {
+ byte[] rawKey = Base64.decodeBase64(secretKey);
+ SecretKeySpec sKeySpec = new SecretKeySpec(rawKey, "AES");
+ byte[] encryptText = Base64.decodeBase64(encryptedText.getBytes("UTF-8"));
+ Cipher cipher = Cipher.getInstance("AES");
+ cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
+ encryptedString = new String(cipher.doFinal(encryptText));
+ } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException
+ | NoSuchPaddingException | UnsupportedEncodingException ex) {
+ logger.error("decrypt failed", ex);
+ throw new CipherUtilException(ex);
+ }
+ return encryptedString;
+ }
+
+ /**
+ * Decrypts the text using a default secret key.
+ *
+ * @param encryptedText
+ * Text to decrypt
+ * @return Decrypted text
+ * @throws CipherUtilException
+ * if any decryption step fails
+ */
+ public static String decrypt(String encryptedText) throws CipherUtilException {
+ return CipherUtil.decrypt(encryptedText, key);
+ }
+
+ public static void main(String[] args) throws CipherUtilException {
+
+ String password = "Welcome123";
+ String encrypted;
+ String decrypted;
+
+ if (args.length != 2) {
+ System.out.println("Default password testing... ");
+ System.out.println("Plain password: " + password);
+ encrypted = encrypt(password);
+ System.out.println("Encrypted password: " + encrypted);
+ decrypted = decrypt(encrypted);
+ System.out.println("Decrypted password: " + decrypted);
+ } else {
+ String whatToDo = args[0];
+ if (whatToDo.equalsIgnoreCase("d")) {
+ encrypted = args[1];
+ System.out.println("Encrypted Text: " + encrypted);
+ decrypted = decrypt(encrypted);
+ System.out.println("Decrypted Text: " + decrypted);
+ } else {
+ decrypted = args[1];
+ System.out.println("Plain Text: " + decrypted);
+ encrypted = encrypt(decrypted);
+ System.out.println("Encrypted Text" + encrypted);
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.util;
+
+public interface PortalApiConstants {
+ public static final String API_PREFIX = "/api/v2";
+ public static final String PORTAL_JSESSION_ID = "PORTAL_JSESSION_ID";
+ public static final String PORTAL_JSESSION_BIND = "PORTAL_JSESSION_BIND";
+ public static final String ACTIVE_USERS_NAME = "activeUsers";
+
+ /** Portal service cookie name */
+ public static final String EP_SERVICE = "EPService";
+
+ public static final String GLOBAL_SESSION_MAX_IDLE_TIME = "global_session_max_idle_time";
+ public static final String PORTAL_SESSION_SLOT_CHECK = "portal_session_slot_check";
+ public static final String SESSION_PREVIOUS_ACCESS_TIME = "session_previous_access_time";
+ public static final String MAX_IDLE_TIME = "max.idle.time";
+
+ // Names of keys in the portal.properties file
+ public static final String PORTAL_API_IMPL_CLASS = "portal.api.impl.class";
+ public static final String ECOMP_REDIRECT_URL = "ecomp_redirect_url";
+ public static final String ECOMP_REST_URL = "ecomp_rest_url";
+ public static final String ROLE_ACCESS_CENTRALIZED = "role_access_centralized";
+ public static final String CSP_COOKIE_NAME = "csp_cookie_name";
+ public static final String CSP_GATE_KEEPER_PROD_KEY = "csp_gate_keeper_prod_key";
+
+ // UEB related
+ public static final String UEB_URL_LIST = "ueb_url_list"; // In properties file
+ public static final String ECOMP_PORTAL_INBOX_NAME = "ecomp_portal_inbox_name";
+ public static final String ECOMP_DEFAULT_MSG_ID = "0";
+ public static final String ECOMP_GENERAL_UEB_PARTITION = "EPGeneralPartition";
+ public static final String UEB_LISTENERS_ENABLE = "ueb_listeners_enable";
+ public static final String UEB_APP_INBOUND_MAILBOX_NAME = "ueb_app_mailbox_name";
+ public static final String UEB_APP_CONSUMER_GROUP_NAME = "ueb_app_consumer_group_name";
+
+ // UebManager generates a consumer group name for special token {UUID}
+ public static final String UEB_APP_CONSUMER_GROUP_NAME_GENERATOR = "{UUID}";
+ public static final String UEB_APP_KEY = "ueb_app_key";
+ public static final String UEB_APP_SECRET = "ueb_app_secret";
+ public static final String ECOMP_UEB_INVALID_MSG = "100: Invalid Message format.";
+ public static final String ECOMP_UEB_TIMEOUT_ERROR = "101: Timeout";
+ public static final String ECOMP_UEB_UNKNOWN_PUBLISH_ERROR = "102: Unknown error during publish";
+ public static final String ECOMP_UEB_UNKNOWN_CONSUME_ERROR = "103: Unknown error during consume";
+ public static final String USE_REST_FOR_FUNCTIONAL_MENU = "use_rest_for_functional_menu";
+
+ public static final String EXT_REQUEST_CONNECTION_TIMEOUT = "ext_req_connection_timeout";
+ public static final String EXT_REQUEST_READ_TIMEOUT = "ext_req_read_timeout";
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Singleton Class representing portal properties. Searches the classpath for
+ * the file "portal.properties".
+ *
+ * To put the file "portal.properties" on the classpath, it can be in the same
+ * directory where the first package folder is - 'myClasses' folder in the
+ * following case as an example:
+ *
+ */
+public class PortalApiProperties {
+
+ private static final Log logger = LogFactory.getLog(PortalApiProperties.class);
+
+ private static Properties properties;
+ private static String propertyFileName = "portal.properties";
+
+ private static final Object lockObject = new Object();
+
+ /**
+ * Constructor is private.
+ */
+ private PortalApiProperties() {
+ }
+
+ /**
+ * Gets the property value for the specified key. If a value is found, leading
+ * and trailing space is trimmed.
+ *
+ * @param property
+ * Property key
+ * @return Value for the named property; null if the property file was not
+ * loaded or the key was not found.
+ */
+ public static String getProperty(String property) {
+ if (properties == null) {
+ synchronized (lockObject) {
+ try {
+ if (!initialize()) {
+ logger.error("Failed to read property file " + propertyFileName);
+ return null;
+ }
+ } catch (IOException e) {
+ logger.error("Failed to read property file " + propertyFileName, e);
+ return null;
+ }
+ }
+ }
+ String value = properties.getProperty(property);
+ if (value != null)
+ value = value.trim();
+ return value;
+ }
+
+ /**
+ * Reads properties from a portal.properties file on the classpath.
+ *
+ * Clients do NOT need to call this method. Clients MAY call this method to test
+ * whether the properties file can be loaded successfully.
+ *
+ * @return True if properties were successfully loaded, else false.
+ * @throws IOException
+ * On failure
+ */
+ public static boolean initialize() throws IOException {
+ if (properties != null)
+ return true;
+ InputStream in = PortalApiProperties.class.getClassLoader().getResourceAsStream(propertyFileName);
+ if (in == null)
+ return false;
+ properties = new Properties();
+ try {
+ properties.load(in);
+ } finally {
+ in.close();
+ }
+ return true;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.portalsdk.core.onboarding.util;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.onap.portalsdk.core.onboarding.crossapi.PortalRestAPIProxy;
+import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
+
+public class SSOFilter implements Filter {
+
+ private final Log logger = LogFactory.getLog(getClass());
+
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws java.io.IOException, ServletException {
+
+ try {
+ if (PortalRestAPIProxy.getPortalRestApiServiceImpl().getUserId((HttpServletRequest) request) == null) {
+ String redirectURL = SSOUtil.getECOMPSSORedirectURL(((HttpServletRequest) request),
+ ((HttpServletResponse) response),
+ (((HttpServletRequest) request).getRequestURI()
+ .substring(((HttpServletRequest) request).getContextPath().length() + 1)
+ + (((HttpServletRequest) request).getQueryString() != null
+ ? ("?" + ((HttpServletRequest) request).getQueryString())
+ : "")));
+
+ ((HttpServletResponse) response).sendRedirect(redirectURL);
+
+ } else {
+ // Pass request back down the filter chain
+ chain.doFilter(request, response);
+
+ }
+ } catch (PortalAPIException e) {
+ logger.error("Issue calling getUserId method ");
+ throw new ServletException(e);
+ }
+
+ }
+
+ public void destroy() {
+
+ }
+
+ public void init(FilterConfig arg0) throws ServletException {
+ // TODO Auto-generated method stub
+
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.onboarding.util;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class SSOUtil {
+
+ private static final Log logger = LogFactory.getLog(SSOUtil.class);
+
+ /**
+ * Constructs a path for this server, this app's context, etc.
+ *
+ * @param request
+ * HttpServletRequest
+ * @param response
+ * HttpServletResponse
+ * @param forwardPath
+ * Path to forward user
+ * @return Redirect URL
+ */
+ public static String getECOMPSSORedirectURL(HttpServletRequest request, HttpServletResponse response,
+ String forwardPath) {
+ String appURL = (request.isSecure() ? "https://" : "http://") + request.getServerName() + ":"
+ + request.getServerPort() + request.getContextPath() + "/" + forwardPath;
+ String encodedAppURL = null;
+ try {
+ encodedAppURL = URLEncoder.encode(appURL, "UTF-8");
+ } catch (UnsupportedEncodingException ex) {
+ logger.error("getECOMPSSORedirectURL: Failed to encode app URL " + appURL);
+ }
+ String portalURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
+ if (portalURL == null || portalURL.length() == 0) {
+ logger.error("getECOMPSSORedirectURL: Failed to get property " + PortalApiConstants.ECOMP_REDIRECT_URL);
+ return null;
+ }
+ String redirectURL = portalURL + "?redirectUrl=" + encodedAppURL;
+ return redirectURL;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.restful.domain;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * This bean holds the information for a role in the role and user management
+ * REST API.
+ */
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class EcompRole implements Comparable<EcompRole> {
+
+ protected Long id;
+ private String name;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ EcompRole other = (EcompRole) obj;
+ if (id == null) {
+ if (other.id != null)
+ return false;
+ } else if (!id.equals(other.id))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ String s = "@EcompRole[id: " + id + "; name: " + name + "]";
+ return s;
+ }
+
+ @Override
+ public int compareTo(EcompRole o) {
+ return this.id.compareTo(o.id);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.restful.domain;
+
+import java.util.Set;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * This bean holds the information for a user in the role and user management
+ * REST API.
+ */
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class EcompUser implements Comparable<EcompUser> {
+
+ private Long orgId;
+ private String managerId;
+ private String firstName;
+ private String middleInitial;
+ private String lastName;
+ private String phone;
+ private String email;
+ private String hrid;
+ private String orgUserId;
+ private String orgCode;
+ private String orgManagerUserId;
+ private String jobTitle;
+ private String loginId;
+ private boolean active;
+
+ private Set<EcompRole> roles;
+
+ public Long getOrgId() {
+ return orgId;
+ }
+
+ public void setOrgId(Long orgId) {
+ this.orgId = orgId;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getMiddleInitial() {
+ return middleInitial;
+ }
+
+ public void setMiddleInitial(String middleInitial) {
+ this.middleInitial = middleInitial;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public String getPhone() {
+ return phone;
+ }
+
+ public void setPhone(String phone) {
+ this.phone = phone;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getHrid() {
+ return hrid;
+ }
+
+ public void setHrid(String hrid) {
+ this.hrid = hrid;
+ }
+
+ public String getOrgUserId() {
+ return orgUserId;
+ }
+
+ public void setOrgUserId(String orgUserId) {
+ this.orgUserId = orgUserId;
+ }
+
+ public String getOrgCode() {
+ return orgCode;
+ }
+
+ public void setOrgCode(String orgCode) {
+ this.orgCode = orgCode;
+ }
+
+ public String getOrgManagerUserId() {
+ return orgManagerUserId;
+ }
+
+ public void setOrgManagerUserId(String orgManagerUserId) {
+ this.orgManagerUserId = orgManagerUserId;
+ }
+
+ public String getJobTitle() {
+ return jobTitle;
+ }
+
+ public void setJobTitle(String jobTitle) {
+ this.jobTitle = jobTitle;
+ }
+
+ public String getLoginId() {
+ return loginId;
+ }
+
+ public void setLoginId(String loginId) {
+ this.loginId = loginId;
+ }
+
+ public boolean isActive() {
+ return active;
+ }
+
+ public void setActive(boolean active) {
+ this.active = active;
+ }
+
+ public Set<EcompRole> getRoles() {
+ return roles;
+ }
+
+ public void setRoles(Set<EcompRole> roles) {
+ this.roles = roles;
+ }
+
+ public String getManagerId() {
+ return managerId;
+ }
+
+ public void setManagerId(String managerId) {
+ this.managerId = managerId;
+ }
+
+ @Override
+ public String toString() {
+ String s = "@EcompUser[orgId: " + orgId //
+ + ", firstName: " + firstName //
+ + ", mi: " + middleInitial //
+ + ", lastName: " + lastName //
+ + ", phone: " + phone //
+ + ", email: " + email //
+ + ", hrid: " + hrid //
+ + ", orgUserId: " + orgUserId //
+ + ", orgCode: " + orgCode //
+ + ", orgManagerUserId: " + orgManagerUserId //
+ + ", jobTitle: " + jobTitle //
+ + ", loginId: " + loginId //
+ + ", active:" + active //
+ + "]";
+ return s;
+ }
+
+ @Override
+ public int compareTo(EcompUser o) {
+ return this.loginId.compareTo(o.loginId);
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.restful.domain;
+
+public class PortalTimeoutVO implements Comparable<PortalTimeoutVO> {
+
+ private String jSessionId;
+ private Long sessionTimOutMilliSec;
+
+ public PortalTimeoutVO() {
+
+ }
+
+ public PortalTimeoutVO(String _jSessionId, Long _sessionTimOutMilliSec) {
+ setjSessionId(_jSessionId);
+ setSessionTimOutMilliSec(_sessionTimOutMilliSec);
+
+ }
+
+ public String getjSessionId() {
+ return jSessionId;
+ }
+
+ public void setjSessionId(String jSessionId) {
+ this.jSessionId = jSessionId;
+ }
+
+ public Long getSessionTimOutMilliSec() {
+ return sessionTimOutMilliSec;
+ }
+
+ public void setSessionTimOutMilliSec(Long sessionTimOutMilliSec) {
+ this.sessionTimOutMilliSec = sessionTimOutMilliSec;
+ }
+
+ @Override
+ public int compareTo(PortalTimeoutVO o) {
+ return sessionTimOutMilliSec.compareTo(o.sessionTimOutMilliSec);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.core.restful.domain;
+
+import java.util.Objects;
+
+/**
+ * Bean that represents shared-context data transferred in JSON objects. This is
+ * a minimum example:
+ *
+ * <PRE>
+ * {
+ * "context_id": "abc123",
+ * "ckey": "myKey",
+ * "cvalue": "my context value to share"
+ * }
+ * </PRE>
+ */
+public class SharedContext {
+
+ // Response field indicates nothing else is present
+ private String response;
+ // Required fields when data is present
+ private String context_id, ckey, cvalue;
+ private Long id, create_time;
+ // Additional database fields from the DomainVO object.
+ private String created, modified, createdId, modifiedId, auditUserId, auditTrail, rowNum;
+
+ /**
+ * Gets the response field.
+ *
+ * @return response
+ */
+ public String getResponse() {
+ return response;
+ }
+
+ /**
+ * Sets the response field.
+ *
+ * @param response
+ * The response to set
+ */
+ public void setResponse(final String response) {
+ this.response = response;
+ }
+
+ /**
+ * Gets the database row ID.
+ *
+ * @return Database row ID
+ */
+ public Long getId() {
+ return id;
+ }
+
+ /**
+ * Sets the database row ID.
+ *
+ * @param id
+ * Row ID
+ */
+ public void setId(final Long id) {
+ this.id = id;
+ }
+
+ /**
+ * Gets the creation time
+ *
+ * @return Creation time as a Long
+ */
+ public Long getCreate_time() {
+ return create_time;
+ }
+
+ /**
+ * Sets the creation time
+ *
+ * @param create_time
+ * Creation time
+ */
+ public void setCreate_time(final Long create_time) {
+ this.create_time = create_time;
+ }
+
+ /**
+ * Gets the context ID
+ *
+ * @return Context ID
+ */
+ public String getContext_id() {
+ return context_id;
+ }
+
+ /**
+ * Sets the context ID
+ *
+ * @param context_id
+ * Context ID
+ */
+ public void setContext_id(final String context_id) {
+ this.context_id = context_id;
+ }
+
+ /**
+ * Gets the key of the key-value pair. Called ckey because "key" is a reserved
+ * word in Mysql.
+ *
+ * @return The key
+ */
+ public String getCkey() {
+ return ckey;
+ }
+
+ /**
+ * Sets the key of the key-value pair.
+ *
+ * @param ckey
+ * Context key
+ */
+ public void setCkey(final String ckey) {
+ this.ckey = ckey;
+ }
+
+ /**
+ * Gets the value of the key-value pair. Called cvalue because "value" is a
+ * reserved word in Mysql.
+ *
+ * @return Value of the key-value pair.
+ */
+ public String getCvalue() {
+ return cvalue;
+ }
+
+ /**
+ * Sets the value of the key-value pair.
+ *
+ * @param cvalue
+ * Context value
+ */
+ public void setCvalue(final String cvalue) {
+ this.cvalue = cvalue;
+ }
+
+ /**
+ * Gets the created value.
+ *
+ * @return Created info from database
+ */
+ public String getCreated() {
+ return created;
+ }
+
+ /**
+ * Sets the created value.
+ *
+ * @param created
+ * Created value
+ */
+ public void setCreated(String created) {
+ this.created = created;
+ }
+
+ /**
+ * Gets the modified value.
+ *
+ * @return Modified info from database
+ */
+ public String getModified() {
+ return modified;
+ }
+
+ /**
+ * Sets the modified value.
+ *
+ * @param modified
+ * Modified value
+ */
+ public void setModified(String modified) {
+ this.modified = modified;
+ }
+
+ /**
+ * Gets the createdId value.
+ *
+ * @return CreatedId info from database
+ */
+ public String getCreatedId() {
+ return createdId;
+ }
+
+ /**
+ * Sets the createdId value.
+ *
+ * @param createdId
+ * Created ID
+ */
+ public void setCreatedId(String createdId) {
+ this.createdId = createdId;
+ }
+
+ /**
+ * Gets the modifiedId value.
+ *
+ * @return ModifiedId info from database
+ */
+ public String getModifiedId() {
+ return modifiedId;
+ }
+
+ /**
+ * Sets the modifiedId value.
+ *
+ * @param modifiedId
+ * Modified ID
+ */
+ public void setModifiedId(String modifiedId) {
+ this.modifiedId = modifiedId;
+ }
+
+ /**
+ * Gets the audit user ID value.
+ *
+ * @return AuditUserId from database
+ */
+ public String getAuditUserId() {
+ return auditUserId;
+ }
+
+ /**
+ * Sets the audit user ID value.
+ *
+ * @param auditUserId
+ * Audit user ID
+ */
+ public void setAuditUserId(String auditUserId) {
+ this.auditUserId = auditUserId;
+ }
+
+ /**
+ * Gets the audit trail value.
+ *
+ * @return AuditTrail from database.
+ */
+ public String getAuditTrail() {
+ return auditTrail;
+ }
+
+ /**
+ * Sets the audit trail value.
+ *
+ * @param auditTrail
+ * Audit trail
+ */
+ public void setAuditTrail(String auditTrail) {
+ this.auditTrail = auditTrail;
+ }
+
+ /**
+ * Gets the row num value.
+ *
+ * @return rowNum from database.
+ */
+ public String getRowNum() {
+ return rowNum;
+ }
+
+ /**
+ * Sets the row num value.
+ *
+ * @param rowNum
+ * row number
+ */
+ public void setRowNum(String rowNum) {
+ this.rowNum = rowNum;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null || !(obj instanceof SharedContext))
+ return false;
+ SharedContext other = (SharedContext) obj;
+ return Objects.equals(id, other.id) && Objects.equals(context_id, other.context_id) && Objects.equals(ckey, other.ckey)
+ && Objects.equals(cvalue, other.cvalue);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id, context_id, ckey, cvalue);
+ }
+
+ @Override
+ public String toString() {
+ String s = "@SharedContext[id: " + id + "; context_id: " + context_id + "; ckey: " + ckey + "; cvalue: "
+ + cvalue + "]";
+ return s;
+ }
+
+}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.crossapi;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException;
-import org.openecomp.portalsdk.core.restful.domain.EcompRole;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-
-/**
- * Defines the REST API Interface that an on-boarding application must implement
- * to answer queries and accept updates from the ECOMP Portal about the
- * application's users, roles and user-role assignments.
- */
-public interface IPortalRestAPIService {
-
- // EcompUser Interface
-
- /**
- * Creates a user with the specified details. If any error occurs, for
- * example the user exists, the method should throw PortalApiException with
- * an appropriate message. The FW library will catch the exception and send
- * an appropriate response to Portal.
- *
- * @param user
- * Model object with attributes of user to be created.
- * @throws PortalAPIException
- * If any error occurs while processing the request; for
- * example, user exists.
- */
- public void pushUser(EcompUser user) throws PortalAPIException;
-
- /**
- * Updates details about the user with the specified loginId. For example,
- * mark user as inactive. If any error occurs, the method should throw
- * PortalApiException with an appropriate message. The FW library will catch
- * the exception and send an appropriate response to Portal.
- *
- * @param loginId
- * EcompUser ID to be updated.
- * @param user
- * Model object with attributes of user to be updated.
- * @throws PortalAPIException
- * If any error occurs while processing the request; for
- * example, unknown user.
- */
- public void editUser(String loginId, EcompUser user) throws PortalAPIException;
-
- /**
- * Gets and returns the user object with the specified loginId. If any error
- * occurs, the method should throw PortalApiException with an appropriate
- * message. The FW library will catch the exception and send an appropriate
- * response to Portal
- *
- * @param loginId
- * EcompUser ID to be fetched
- * @return Model object with user attributes.
- * @throws PortalAPIException
- * If any error occurs while processing the request; for
- * example, unknown user.
- */
- public EcompUser getUser(String loginId) throws PortalAPIException;
-
- /**
- * Gets and returns a list of active users. If any error occurs, the method
- * should throw PortalApiException with an appropriate message. The FW
- * library will catch the exception and send an appropriate response to
- * Portal.
- *
- * @return List of user attribute model objects; empty list if none are
- * found.
- * @throws PortalAPIException
- * If any error occurs while processing the request.
- */
- public List<EcompUser> getUsers() throws PortalAPIException;
-
- // Roles Interface
-
- /**
- * Gets and returns a list of active roles. If any error occurs, the method
- * should throw PortalApiException with an appropriate message. The FW
- * library will catch the exception and send an appropriate response to
- * Portal.
- *
- * @param requestedLoginId
- * requested userloginId to fetch available roles
- * @return List of role attribute objects; empty list if none are found.
- * @throws PortalAPIException
- * If an unexpected error occurs while processing the request.
- */
- public List<EcompRole> getAvailableRoles(String requestedLoginId) throws PortalAPIException;
-
- /**
- * Updates roles for the user with the specified loginId to the list of
- * roles provided as the second argument. After this operation, the should
- * have ONLY the roles provided in the list above. For example, if user had
- * roles r1, r2 and r3; and a call was made to pushUserRole with a list
- * containing only roles r3 and r4, this method should leave the user with
- * roles r3 and r4 since those were the ONLY roles provided in second
- * argument. If any error occurs, the method should throw PortalApiException
- * with an appropriate message. The FW library will catch the exception and
- * send an appropriate response to Portal.
- *
- * @param loginId
- * EcompUser ID to be updated.
- * @param roles
- * List of role attribute objects
- * @throws PortalAPIException
- * If any error occurs while processing the request.
- */
- public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException;
-
- /**
- * Gets and returns a list of roles for the user with the specified loginId.
- * If any error occurs, the method should throw PortalApiException with an
- * appropriate message. The FW library will catch the exception and send an
- * appropriate response to Portal.
- *
- * @param loginId
- * @return List of model objects; empty if no roles are found.
- * @throws PortalAPIException
- * If any error occurs while processing the request; e.g., user
- * not found.
- */
- public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException;
-
- // Security Interface
-
- /**
- * Should return true if the call should be allowed and false if not.
- * Currently Portal sends two headers of username and password in each
- * request which the app should check. If match, return true; else return
- * false. If any error occurs, the method should throw PortalApiException
- * with an appropriate message. The FW library will catch the exception and
- * send an appropriate response to Portal.
- *
- * @param request
- * @return true if the request contains appropriate credentials, else false.
- * @throws PortalAPIException
- * If an unexpected error occurs while processing the request.
- */
- public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException;
-
- /**
- * Gets and returns the userId for the logged-in user based on the request.
- * If any error occurs, the method should throw PortalApiException with an
- * appropriate message. The FW library will catch the exception and send an
- * appropriate response to Portal.
- *
- * @param request
- * @return true if the request contains appropriate credentials, else false.
- * @throws PortalAPIException
- * If an unexpected error occurs while processing the request.
- */
- public String getUserId(HttpServletRequest request) throws PortalAPIException;
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.crossapi;
-
-import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException;
-
-/**
- *
- * @author Ikram Ikramullah
- *
- * UEB API Interface for all the onboarding third party applications.
- *
- */
-
-public interface IPortalUebAPIService {
- //User Interface
- public String pushUser(String userJson) throws PortalAPIException;
- public String editUser(String loginId, String userJson) throws PortalAPIException;
- public String getUser(String loginId) throws PortalAPIException;
- public String getUsers() throws PortalAPIException;
-
- //Roles Interface
- public String getAvailableRoles() throws PortalAPIException;
- public String getAvailableFullRoles() throws PortalAPIException;
- public String pushUserRole(String loginId, String rolesJson) throws PortalAPIException;
- public String getUserRoles(String loginId) throws PortalAPIException;
-
- //Security Interface
- public boolean isAppAuthenticated(String appUserName, String appPassword) throws PortalAPIException;
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.crossapi;
-
-/**
- * This bean holds a response that is returned by the role and user-management
- * REST API.
- */
-public class PortalAPIResponse {
-
- /**
- * Either "ok" or "error"
- */
- private String status;
- /**
- * Optional if status is ok
- */
- private String message;
-
- public PortalAPIResponse(boolean isOk, String msg) {
- status = (isOk? "ok" : "error");
- message = msg;
- }
-
- public String getStatus() {
- return status;
- }
-
- public void setStatus(String status) {
- this.status = status;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.crossapi;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.ServletException;
-import javax.servlet.annotation.WebServlet;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException;
-import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
-import org.openecomp.portalsdk.core.onboarding.rest.RestWebServiceClient;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-import org.openecomp.portalsdk.core.restful.domain.EcompRole;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-/**
- * This servlet performs the functions described below. It listens on a path
- * like "/api" (see {@link PortalApiConstants#API_PREFIX}). The servlet checks
- * for authorized access and rejects unauthorized requests.
- * <OL>
- * <LI>Proxies user (i.e., browser) requests for web analytics. The GET method
- * fetches javascript from the Portal and returns it. The POST method forwards
- * data sent by the browser on to Portal. These requests are checked for a valid
- * User UID in a header; these requests do NOT use the application
- * username-password header.</LI>
- * <LI>Responds to ECOMP Portal API requests to query and update user, role and
- * user-role information. The servlet proxies all requests on to a local Java
- * class that implements {@link IPortalRestAPIService}. These requests must have
- * the application username-password header.</LI>
- * </OL>
- * This servlet will not start if the required portal.properties file is not
- * found on the classpath.
- */
-
-@WebServlet(urlPatterns = { PortalApiConstants.API_PREFIX + "/*" })
-public class PortalRestAPIProxy extends HttpServlet implements IPortalRestAPIService {
- private static final long serialVersionUID = 1L;
-
- private static final String contentTypeAppJson = "application/json";
-
- private final Log logger = LogFactory.getLog(getClass());
-
- /**
- * Mapper for JSON to object etc.
- */
- private final ObjectMapper mapper = new ObjectMapper();
-
- /**
- * Client-supplied class that implements our interface.
- */
- private static IPortalRestAPIService portalRestApiServiceImpl;
-
- public PortalRestAPIProxy() {
- // Ensure that any additional fields sent by the Portal
- // will be ignored when creating objects.
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- }
-
- @Override
- public void init() throws ServletException {
- String className = PortalApiProperties.getProperty(PortalApiConstants.PORTAL_API_IMPL_CLASS);
- if (className == null)
- throw new ServletException(
- "init: Failed to find class name property " + PortalApiConstants.PORTAL_API_IMPL_CLASS);
- try {
- logger.debug("init: creating instance of class " + className);
- Class<?> implClass = Class.forName(className);
- portalRestApiServiceImpl = (IPortalRestAPIService) (implClass.getConstructor().newInstance());
- } catch (Exception ex) {
- throw new ServletException("init: Failed to find or instantiate class " + className, ex);
- }
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
- if (portalRestApiServiceImpl == null) {
- // Should never happen due to checks in init()
- logger.error("doPost: no service class instance");
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.getWriter().write(buildJsonResponse(false, "Misconfigured - no instance of service class"));
- return;
- }
- String requestUri = request.getRequestURI();
- String responseJson = "";
- String storeAnalyticsContextPath = "/storeAnalytics";
- if (requestUri.endsWith(PortalApiConstants.API_PREFIX + storeAnalyticsContextPath)) {
- String userId;
- try {
- userId = getUserId(request);
- } catch (PortalAPIException e) {
- logger.error("Issue with invoking getUserId implemenation !!! ", e);
- throw new ServletException(e);
- }
- if (userId == null || userId.length() == 0) {
- logger.debug("doPost: userId is null or empty");
- response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
- responseJson = buildJsonResponse(false, "Not authorized for " + storeAnalyticsContextPath);
- } else {
- // User ID obtained from request
- try {
- String credential = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
- // for now lets also pass uebkey as user name and password
- String requestBody = readRequestBody(request);
- @SuppressWarnings("unchecked")
- Map<String, String> bodyMap = mapper.readValue(requestBody, Map.class);
- // add user ID
- bodyMap.put("userid", userId);
- requestBody = mapper.writeValueAsString(bodyMap);
- responseJson = RestWebServiceClient.getInstance().postPortalContent(storeAnalyticsContextPath,
- userId, credential, null, credential, credential, "application/json", requestBody, true);
- if (logger.isDebugEnabled())
- logger.debug("doPost: postPortalContent returns " + responseJson);
- response.setStatus(HttpServletResponse.SC_OK);
- } catch (Exception ex) {
- logger.error("doPost: " + storeAnalyticsContextPath + " caught exception", ex);
- responseJson = buildJsonResponse(ex);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- }
- writeAndFlush(response, contentTypeAppJson, responseJson);
- return;
- } // post analytics
-
- boolean secure = false;
- try {
- secure = isAppAuthenticated(request);
- } catch (PortalAPIException ex) {
- logger.error("doPost: isAppAuthenticated threw exception", ex);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- response.getWriter().write(buildJsonResponse(false, "Failed to authenticate request"));
- return;
- }
- if (!secure) {
- if (logger.isDebugEnabled())
- logger.debug("doPost: isAppAuthenticated answered false");
- response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
- writeAndFlush(response, contentTypeAppJson, buildJsonResponse(false, "Not authorized"));
- return;
- }
-
- try {
- String requestBody = readRequestBody(request);
- if (logger.isDebugEnabled())
- logger.debug("doPost: URI = " + requestUri + ", payload = " + requestBody);
-
- /*
- * All APIs:
- *
- * 1. /user <-- save user
- *
- * 2. /user/{loginId} <-- edit user
- *
- * 3. /user/{loginId}/roles <-- save roles for user
- */
-
- // On success return the empty string.
-
- if (requestUri.endsWith("/updateSessionTimeOuts")) {
- if (updateSessionTimeOuts(requestBody)) {
- if (logger.isDebugEnabled())
- logger.debug("doPost: updated session timeouts");
- response.setStatus(HttpServletResponse.SC_OK);
- } else {
- String msg = "Failed to update session time outs";
- logger.error("doPost: " + msg);
- responseJson = buildJsonResponse(false, msg);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- } else if (requestUri.endsWith("/timeoutSession")) {
- String portalJSessionId = request.getParameter("portalJSessionId");
- if (portalJSessionId == null) {
- portalJSessionId = "";
- }
- if (timeoutSession(portalJSessionId)) {
- if (logger.isDebugEnabled())
- logger.debug("doPost: timed out session");
- response.setStatus(HttpServletResponse.SC_OK);
- } else {
- String msg = "Failed to timeout session";
- logger.error("doPost: " + msg);
- responseJson = buildJsonResponse(false, msg);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- } else
- // Example: /user <-- create user
- if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/user")) {
- try {
- EcompUser user = mapper.readValue(requestBody, EcompUser.class);
- pushUser(user);
- if (logger.isDebugEnabled())
- logger.debug("doPost: pushUser: success");
- responseJson = buildJsonResponse(true, null);
- response.setStatus(HttpServletResponse.SC_OK);
- } catch (Exception ex) {
- responseJson = buildJsonResponse(ex);
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- logger.error("doPost: pushUser: caught exception", ex);
- }
- } else
- // Example: /user/fi241c <-- edit user fi241c
- if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && !(requestUri.endsWith("/roles"))) {
- String loginId = requestUri.substring(requestUri.lastIndexOf('/') + 1);
- try {
- EcompUser user = mapper.readValue(requestBody, EcompUser.class);
- editUser(loginId, user);
- if (logger.isDebugEnabled())
- logger.debug("doPost: editUser: success");
- responseJson = buildJsonResponse(true, null);
- response.setStatus(HttpServletResponse.SC_OK);
- } catch (Exception ex) {
- responseJson = buildJsonResponse(ex);
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- logger.error("doPost: editUser: caught exception", ex);
- }
- } else
- // Example: /user/{loginId}/roles <-- save roles for user
- if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && requestUri.endsWith("/roles")) {
- String loginId = requestUri.substring(requestUri.indexOf("/user/") + ("/user").length() + 1,
- requestUri.lastIndexOf('/'));
- try {
- TypeReference<List<EcompRole>> typeRef = new TypeReference<List<EcompRole>>() {
- };
- List<EcompRole> roles = mapper.readValue(requestBody, typeRef);
- pushUserRole(loginId, roles);
- if (logger.isDebugEnabled())
- logger.debug("doPost: pushUserRole: success");
- responseJson = buildJsonResponse(true, null);
- response.setStatus(HttpServletResponse.SC_OK);
- } catch (Exception ex) {
- responseJson = buildJsonResponse(ex);
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- logger.error("doPost: pushUserRole: caught exception", ex);
- }
- } else {
- String msg = "doPost: no match for request " + requestUri;
- logger.warn(msg);
- responseJson = buildJsonResponse(false, msg);
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- }
- } catch (Exception ex) {
- logger.error("doPost: Failed to process request " + requestUri, ex);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- responseJson = buildJsonResponse(ex);
- }
-
- writeAndFlush(response, contentTypeAppJson, responseJson);
-
- }
-
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
-
- if (portalRestApiServiceImpl == null) {
- // Should never happen due to checks in init()
- logger.error("doGet: no service class instance");
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- writeAndFlush(response, contentTypeAppJson,
- buildJsonResponse(false, "Misconfigured - no instance of service class"));
- return;
- }
-
- String requestUri = request.getRequestURI();
- String responseString = "";
- String contentType = contentTypeAppJson;
-
- String webAnalyticsContextPath = "/analytics";
- if (requestUri.endsWith(PortalApiConstants.API_PREFIX + webAnalyticsContextPath)) {
- String userId;
- try {
- userId = getUserId(request);
- } catch (PortalAPIException e) {
- logger.error("Issue with invoking getUserId implemenation !!! ", e);
- throw new ServletException(e);
- }
- if (userId == null || userId.length() == 0) {
- logger.debug("doGet: userId is null or empty");
- response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
- responseString = buildJsonResponse(false, "Not authorized for " + webAnalyticsContextPath);
- } else {
- // User ID obtained from request
- try {
- String credential = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
- // for now lets also pass uebkey as user name and password
- contentType = "text/javascript";
-
- responseString = RestWebServiceClient.getInstance().getPortalContent(webAnalyticsContextPath,
- userId, credential, null, credential, credential,true);
- if (logger.isDebugEnabled())
- logger.debug("doGet: " + webAnalyticsContextPath + ": " + responseString);
- response.setStatus(HttpServletResponse.SC_OK);
- } catch (Exception ex) {
- responseString = buildJsonResponse(ex);
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- logger.error("doGet: " + webAnalyticsContextPath + " caught exception", ex);
- }
- }
- writeAndFlush(response, contentType, responseString);
- return;
- }
-
- boolean secure = false;
- try {
- secure = isAppAuthenticated(request);
- } catch (PortalAPIException ex) {
- logger.error("doGet: isAppAuthenticated threw exception", ex);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- writeAndFlush(response, contentTypeAppJson, buildJsonResponse(false, "Failed to authenticate request"));
- return;
- }
-
- if (!secure) {
- if (logger.isDebugEnabled())
- logger.debug("doGet: isAppAuthenticated answered false");
- response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
- writeAndFlush(response, contentTypeAppJson, buildJsonResponse(false, "Not authorized"));
- return;
- }
-
- String responseJson = null;
- try {
- // Ignore any request body in a GET.
- // String requestBody = readRequestBody(request);
- if (logger.isDebugEnabled())
- logger.debug("doGet: URI = " + requestUri);
-
- /*
- * 1. /roles <-- get roles
- *
- * 2. /user/{loginId} <-- get user
- *
- * 3. /users <-- get all users
- *
- * 4. /user/{loginId}/roles <-- get roles for user
- */
-
- if (requestUri.endsWith("/sessionTimeOuts")) {
- responseJson = getSessionTimeOuts();
- if (responseJson != null && responseJson.length() > 0) {
- if (logger.isDebugEnabled())
- logger.debug("doGet: got session timeouts");
- response.setStatus(HttpServletResponse.SC_OK);
- } else {
- String msg = "Failed to get session time outs";
- logger.error("doGet: " + msg);
- responseJson = buildJsonResponse(false, msg);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- } else
- // Example: /users <-- get all users
- if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/users")) {
- try {
- List<EcompUser> users = getUsers();
- responseJson = mapper.writeValueAsString(users);
- if (logger.isDebugEnabled())
- logger.debug("doGet: getUsers: " + responseJson);
- } catch (Exception ex) {
- responseJson = buildJsonResponse(ex);
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- logger.error("doGet: getUsers: caught exception", ex);
- }
- } else
- // Example: /roles <-- get all roles
-
- if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/roles")) {
- try {
- List<EcompRole> roles = getAvailableRoles(getUserId(request));
- responseJson = mapper.writeValueAsString(roles);
- if (logger.isDebugEnabled())
- logger.debug("doGet: getAvailableRoles: " + responseJson);
- } catch (Exception ex) {
- responseJson = buildJsonResponse(ex);
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- logger.error("doGet: getAvailableRoles: caught exception", ex);
- }
- } else
- // Example: /user/fi241c <-- get user fi241c
- if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && !requestUri.endsWith("/roles")) {
- String loginId = requestUri.substring(requestUri.lastIndexOf('/') + 1);
- try {
- EcompUser user = getUser(loginId);
- responseJson = mapper.writeValueAsString(user);
- if (logger.isDebugEnabled())
- logger.debug("doGet: getUser: " + responseJson);
- } catch (Exception ex) {
- responseJson = buildJsonResponse(ex);
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- logger.error("doGet: getUser: caught exception", ex);
- }
- }
- // Example: /user/fi241c/roles <-- get roles for user fi241c
- else if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && requestUri.endsWith("/roles")) {
- String loginId = requestUri.substring(requestUri.indexOf("/user/") + ("/user").length() + 1,
- requestUri.lastIndexOf('/'));
- try {
- List<EcompRole> roles = getUserRoles(loginId);
- responseJson = mapper.writeValueAsString(roles);
- if (logger.isDebugEnabled())
- logger.debug("doGet: getUserRoles: " + responseJson);
- } catch (Exception ex) {
- responseJson = buildJsonResponse(ex);
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- logger.error("doGet: getUserRoles: caught exception", ex);
- }
- } else {
- logger.warn("doGet: no match found for request");
- responseJson = buildJsonResponse(false, "No match for request");
- response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
- }
- } catch (Exception ex) {
- logger.error("doGet: Failed to process request", ex);
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- responseJson = buildJsonResponse(ex);
- }
- writeAndFlush(response, contentTypeAppJson, responseJson);
- }
-
- public String getSessionTimeOuts() throws Exception {
- return PortalTimeoutHandler.gatherSessionExtensions();
- }
-
- public boolean timeoutSession(String portalJSessionId) throws Exception {
- return PortalTimeoutHandler.invalidateSession(portalJSessionId);
- }
-
- public boolean updateSessionTimeOuts(String sessionMap) throws Exception {
- return PortalTimeoutHandler.updateSessionExtensions(sessionMap);
- }
-
- @Override
- public void pushUser(EcompUser user) throws PortalAPIException {
- portalRestApiServiceImpl.pushUser(user);
- }
-
- @Override
- public void editUser(String loginId, EcompUser user) throws PortalAPIException {
- portalRestApiServiceImpl.editUser(loginId, user);
- }
-
- @Override
- public EcompUser getUser(String loginId) throws PortalAPIException {
- return portalRestApiServiceImpl.getUser(loginId);
- }
-
- @Override
- public List<EcompUser> getUsers() throws PortalAPIException {
- return portalRestApiServiceImpl.getUsers();
- }
-
- @Override
- public List<EcompRole> getAvailableRoles(String requestedLoginId) throws PortalAPIException {
- return portalRestApiServiceImpl.getAvailableRoles(requestedLoginId);
- }
-
- @Override
- public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException {
- portalRestApiServiceImpl.pushUserRole(loginId, roles);
- }
-
- @Override
- public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException {
- return portalRestApiServiceImpl.getUserRoles(loginId);
- }
-
- @Override
- public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException {
- return portalRestApiServiceImpl.isAppAuthenticated(request);
- }
-
- /**
- * Sets the content type and writes the response.
- *
- * @param response
- * @param contentType
- * @param responseBody
- * @throws IOException
- */
- private void writeAndFlush(HttpServletResponse response, String contentType, String responseBody)
- throws IOException {
- response.setContentType(contentType);
- PrintWriter out = response.getWriter();
- out.print(responseBody);
- out.flush();
- }
-
- /**
- * Reads the request body and closes the input stream.
- *
- * @param request
- * @return String read from the request, the empty string if nothing is
- * read.
- * @throws IOException
- */
- private static String readRequestBody(HttpServletRequest request) throws IOException {
-
- String body = null;
- StringBuilder stringBuilder = new StringBuilder();
- BufferedReader bufferedReader = null;
- try {
- InputStream inputStream = request.getInputStream();
- if (inputStream != null) {
- bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
- char[] charBuffer = new char[1024];
- int bytesRead = -1;
- while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
- stringBuilder.append(charBuffer, 0, bytesRead);
- }
- } else {
- stringBuilder.append("");
- }
- } finally {
- if (bufferedReader != null) {
- try {
- bufferedReader.close();
- } catch (IOException ex) {
- throw ex;
- }
- }
- }
- body = stringBuilder.toString();
- return body;
- }
-
- /**
- * Builds JSON object with status + message response body.
- *
- * @param success
- * True to indicate success, false to signal failure.
- * @param msg
- * Message to include in the response object; ignored if null.
- * @return
- *
- * <pre>
- * { "status" : "ok" (or "error"), "message": "some explanation" }
- * </pre>
- */
- private String buildJsonResponse(boolean success, String msg) {
- PortalAPIResponse response = new PortalAPIResponse(success, msg);
- String json = null;
- try {
- json = mapper.writeValueAsString(response);
- } catch (JsonProcessingException ex) {
- // Truly should never, ever happen
- json = "{ \"status\": \"error\",\"message\":\"" + ex.toString() + "\" }";
- }
- return json;
- }
-
- /**
- * Builds JSON object with status of error and message containing stack
- * trace for the specified throwable.
- *
- * @param t
- * Throwable with stack trace to use as message
- *
- * @return
- *
- * <pre>
- * { "status" : "error", "message": "some-big-stacktrace" }
- * </pre>
- */
- private String buildJsonResponse(Throwable t) {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- t.printStackTrace(pw);
- return buildJsonResponse(false, sw.toString());
- }
-
- @Override
- public String getUserId(HttpServletRequest request) throws PortalAPIException {
- return portalRestApiServiceImpl.getUserId(request);
- }
-
- public static IPortalRestAPIService getPortalRestApiServiceImpl() {
- return portalRestApiServiceImpl;
- }
-
- public static void setPortalRestApiServiceImpl(IPortalRestAPIService portalRestApiServiceImpl) {
- PortalRestAPIProxy.portalRestApiServiceImpl = portalRestApiServiceImpl;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.crossapi;
-
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.net.HttpURLConnection;
-import java.net.URL;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class SessionCommunicationService {
-
- protected static final Log logger = LogFactory.getLog(SessionCommunicationService.class);
-
- /**
- * Calls the ECOMP Portal to retrieve the session slot check interval.
- *
- * @param ecompRestURL
- * @param userName
- * application user name used for authentication at Portal
- * @param password
- * application password used for authentication at Portal
- * @param uebKey
- * application UEB key (basically application ID) used for
- * authentication at Portal
- * @return Content read from the remote REST endpoint
- */
- public static String getSessionSlotCheckInterval(String ecompRestURL, String userName, String password,
- String uebKey) {
- try {
- String url = ecompRestURL + "/getSessionSlotCheckInterval";
-
- URL obj = new URL(url);
-
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
-
- // optional default is GET
- con.setRequestMethod("GET");
- con.setConnectTimeout(3000);
- con.setReadTimeout(8000);
- // add request header
- con.setRequestProperty("username", userName);
- con.setRequestProperty("password", password);
- con.setRequestProperty("uebkey", uebKey);
-
- int responseCode = con.getResponseCode();
- if (logger.isDebugEnabled()) {
- logger.debug("getSessionSlotCheckInterval: Sending 'GET' request to URL : " + url);
- logger.debug("getSessionSlotCheckInterval: Response Code : " + responseCode);
- }
-
- StringBuffer response = new StringBuffer();
-
- BufferedReader in = null;
- try {
- in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
- String inputLine;
- while ((inputLine = in.readLine()) != null)
- response.append(inputLine);
- } finally {
- in.close();
- }
- return response.toString();
- } catch (Exception e) {
- logger.error("getSessionSlotCheckInterval: failed to fetch the session slot check", e);
- return null;
- }
-
- }
-
- /**
- * Calls the ECOMP Portal to request an extension of the current session.
- *
- * @param ecompRestURL
- * @param userName
- * application user name used for authentication at Portal
- * @param password
- * application password used for authentication at Portal
- * @param uebKey
- * application UEB key (basically application ID) used for
- * authentication at Portal
- * @param sessionTimeoutMap
- * @return Content read from the remote REST endpoint
- * @throws Exception
- */
- public static String requestPortalSessionTimeoutExtension(String ecompRestURL, String userName, String password,
- String uebKey, String sessionTimeoutMap) throws Exception {
-
- try {
-
- String url = ecompRestURL + "/extendSessionTimeOuts";
- // String decreptedPwd =
- // app.appPassword;//CipherUtil.decrypt(encriptedPwdDB,
- // SystemProperties.getProperty(SystemProperties.SECRET_KEY));
-
- URL obj = new URL(url);
-
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
-
- con.setRequestMethod("POST");
- con.setConnectTimeout(3000);
- con.setReadTimeout(15000);
-
- // add request header
- con.setRequestProperty("username", userName);
- con.setRequestProperty("password", password);
- con.setRequestProperty("uebkey", uebKey);
- con.setRequestProperty("sessionMap", sessionTimeoutMap);
- con.setDoInput(true);
- con.setDoOutput(true);
- con.getOutputStream().write(sessionTimeoutMap.getBytes());
- con.getOutputStream().flush();
- con.getOutputStream().close();
-
- // con.set
-
- int responseCode = con.getResponseCode();
- if (logger.isDebugEnabled()) {
- logger.debug("requestPortalSessionTimeoutExtension: Sending 'GET' request to URL : " + url);
- logger.debug("requestPortalSessionTimeoutExtension: Response Code : " + responseCode);
- }
-
- StringBuffer response = new StringBuffer();
- BufferedReader in = null;
- try {
- in = new BufferedReader(new InputStreamReader(con.getInputStream()));
- String inputLine;
- while ((inputLine = in.readLine()) != null) {
- response.append(inputLine);
- }
- } finally {
- in.close();
- }
- return response.toString();
- } catch (Exception e) {
- logger.error("requestPortalSessionTimeoutExtension: failed to request Portal to extend time out ", e);
- return null;
- }
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.exception;
-
-public class PortalAPIException extends Exception{
-
- private static final long serialVersionUID = 4854048794984375707L;
-
- public PortalAPIException() {
- super();
- }
-
- public PortalAPIException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
-
- public PortalAPIException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public PortalAPIException(String message) {
- super(message);
- }
-
- public PortalAPIException(Throwable cause) {
- super(cause);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.listener;
-
-import java.io.Serializable;
-
-import javax.servlet.http.HttpSession;
-import javax.servlet.http.HttpSessionBindingEvent;
-import javax.servlet.http.HttpSessionBindingListener;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-
-public class PortalTimeoutBindingListener implements HttpSessionBindingListener, Serializable {
-
- private final Log logger = LogFactory.getLog(getClass());
-
- private static final long serialVersionUID = 1L;
-
- @Override
- public void valueBound(HttpSessionBindingEvent event) {
- final HttpSession session = event.getSession();
- PortalTimeoutHandler.sessionMap.put((String) session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID),
- session);
- }
-
- @Override
- public void valueUnbound(HttpSessionBindingEvent event) {
- final HttpSession session = event.getSession();
- String portalJSessionId = (String) session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID);
- logger.debug(portalJSessionId + " getting removed");
- PortalTimeoutHandler.sessionMap.remove(portalJSessionId);
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.listener;
-
-import java.util.Calendar;
-import java.util.Hashtable;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.openecomp.portalsdk.core.onboarding.crossapi.SessionCommunicationService;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.restful.domain.PortalTimeoutVO;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-/**
- * Invoked by listeners (UserContextListener and UserSessionListener) to track
- * user sessions.
- */
-public class PortalTimeoutHandler {
-
- protected static final SessionCommInf sessionComm = new SessionComm();
-
- public interface SessionCommInf {
- public Integer fetchSessionSlotCheckInterval(String... params) throws Exception;
-
- public void extendSessionTimeOuts(String... sessionMap) throws Exception;
- }
-
- public static class SessionComm implements SessionCommInf {
- public Integer fetchSessionSlotCheckInterval(String... params) throws Exception {
-
- String ecompRestURL = params[0];
- String userName = params[1];
- String pwd = params[2];
- String uebKey = params[3];
-
- String sessionSlot = SessionCommunicationService.getSessionSlotCheckInterval(ecompRestURL, userName, pwd,
- uebKey);
- if (sessionSlot == null)
- return null;
- return Integer.parseInt(sessionSlot);
- }
-
- public void extendSessionTimeOuts(String... params) throws Exception {
-
- String ecompRestURL = params[0];
- String userName = params[1];
- String pwd = params[2];
- String uebKey = params[3];
- String sessionTimeoutMap = params[4];
-
- SessionCommunicationService.requestPortalSessionTimeoutExtension(ecompRestURL, userName, pwd, uebKey,
- sessionTimeoutMap);
- }
- }
-
- public static final Map<String, HttpSession> sessionMap = new Hashtable<String, HttpSession>();
- public static final Integer repeatInterval = 15 * 60; // 15 minutes
- protected static final Log logger = LogFactory.getLog(PortalTimeoutHandler.class);
- static ObjectMapper mapper = new ObjectMapper();
- private static PortalTimeoutHandler timeoutHandler;
-
- public static PortalTimeoutHandler getInstance() {
- if (timeoutHandler == null)
- timeoutHandler = new PortalTimeoutHandler();
-
- return timeoutHandler;
- }
-
- /**
- * TODO: remove static
- *
- * @param portalJSessionId
- * @param jSessionId
- * @param session
- */
- public static void sessionCreated(String portalJSessionId, String jSessionId, HttpSession session) {
-
- storeMaxInactiveTime(session);
-
- // this key is a combination of portal jsession id and app session id
- String jSessionKey = jSessionKey(jSessionId, portalJSessionId);
- Object jSessionKeySessionVal = session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID);
-
- // do not reset the attributes if the same values have already been set
- // because that will cause PortalTimeoutBindingListener to unbound the
- // value from map
- if (jSessionKeySessionVal != null && jSessionKeySessionVal.equals(jSessionKey)) {
- logger.debug(" Session Values already exist in te map for sessionKey " + jSessionKey);
- return;
- }
-
- session.setAttribute(PortalApiConstants.PORTAL_JSESSION_ID, jSessionKey);
-
- // session binding listener will add this value to the static map
- // and with session replication the listener will fire in all tomcat
- // instances
- session.setAttribute(PortalApiConstants.PORTAL_JSESSION_BIND, new PortalTimeoutBindingListener());
- // sessionMap.put((String)session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID),
- // session);
-
- }
-
- /**
- * TODO: remove static
- *
- * @param session
- */
- protected static void storeMaxInactiveTime(HttpSession session) {
- if (session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME) == null)
- session.setAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME, session.getMaxInactiveInterval());
- }
-
- /**
- * TODO: remove static
- *
- * @param session
- */
- public static void sessionDestroyed(HttpSession session) {
- try {
- logger.info(" Session getting destroyed - id: " + session.getId());
- session.removeAttribute(PortalApiConstants.PORTAL_JSESSION_BIND);
- // sessionMap.remove((String)session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID));
- } catch (Exception e) {
- logger.error("sessionDestroyed failed", e);
- }
- }
-
- /***
- * TODO: remove static
- *
- * @param portalJSessionId
- * @return true on success, false if the session cannot be found, etc.
- */
- public static boolean invalidateSession(String portalJSessionId) {
- boolean result = false;
- logger.debug("Session Management: request from Portal to invalidate the session: " + portalJSessionId);
- for (String jSessionKey : sessionMap.keySet()) {
- try {
- HttpSession session = sessionMap.get(jSessionKey);
- if (portalJSessionId(jSessionKey).equals(portalJSessionId)) {
- session.invalidate();
- result = true;
- }
- } catch (Exception e) {
- logger.error("invalidateSession failed", e);
- }
- }
- return result;
- }
-
- /**
- * TODO: remove static
- *
- * @return json version of the timeout map: session ID -> timeout object
- */
- public static String gatherSessionExtensions() {
- logger.debug("Session Management: gatherSessionExtensions");
-
- Map<String, PortalTimeoutVO> sessionTimeoutMap = new Hashtable<String, PortalTimeoutVO>();
- String jsonMap = "";
-
- for (String jSessionKey : sessionMap.keySet()) {
-
- try {
- // get the expirytime in seconds
- HttpSession session = sessionMap.get(jSessionKey);
-
- Long lastAccessedTimeMilliSec = session.getLastAccessedTime();
- Long maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000L;
- // Long currentTimeMilliSec =
- // Calendar.getInstance().getTimeInMillis() ;
- // (maxIntervalMilliSec - (currentTimeMilliSec -
- // lastAccessedTimeMilliSec) + ;
- Calendar instance = Calendar.getInstance();
- instance.setTimeInMillis(session.getLastAccessedTime());
- logger.debug("Session Management: Last Accessed time for " + jSessionKey + ": " + instance.getTime());
-
- Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec;
-
- sessionTimeoutMap.put(portalJSessionId(jSessionKey),
- getSingleSessionTimeoutObj(jSessionKey, sessionTimOutMilliSec));
- logger.debug("Session Management: putting session in map " + jSessionKey + " sessionTimoutSec"
- + (int) (sessionTimOutMilliSec / 1000));
-
- jsonMap = mapper.writeValueAsString(sessionTimeoutMap);
-
- } catch (Exception e) {
- logger.error("gatherSessionExtensions failed", e);
- }
-
- }
-
- return jsonMap;
-
- }
-
- /**
- * TODO: remove static
- *
- * @param sessionTimeoutMapStr
- * @return true on success, false otherwise
- * @throws Exception
- */
- public static boolean updateSessionExtensions(String sessionTimeoutMapStr) throws Exception {
- logger.debug("Session Management: updateSessionExtensions");
- // Map<String,Object> sessionTimeoutMap =
- // mapper.readValue(sessionTimeoutMapStr, Map.class);
- Map<String, PortalTimeoutVO> sessionTimeoutMap = null;
-
- try {
- TypeReference<Hashtable<String, PortalTimeoutVO>> typeRef = new TypeReference<Hashtable<String, PortalTimeoutVO>>() {
- };
- sessionTimeoutMap = mapper.readValue(sessionTimeoutMapStr, typeRef);
- } catch (Exception e) {
- logger.error("updateSessionExtensions failed to parse the sessionTimeoutMap from portal", e);
- return false;
- }
-
- boolean result = true;
- for (String jPortalSessionId : sessionTimeoutMap.keySet()) {
- try {
- PortalTimeoutVO extendedTimeoutVO = mapper.readValue(
- mapper.writeValueAsString(sessionTimeoutMap.get(jPortalSessionId)), PortalTimeoutVO.class);
- HttpSession session = sessionMap.get(jSessionKey(extendedTimeoutVO.getjSessionId(), jPortalSessionId));
-
- if (session == null) {
- continue;
- }
-
- Long lastAccessedTimeMilliSec = session.getLastAccessedTime();
- Long maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000L;
- Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec;
-
- Long maxTimeoutTimeMilliSec = extendedTimeoutVO.getSessionTimOutMilliSec();
- if (maxTimeoutTimeMilliSec > sessionTimOutMilliSec) {
- session.setMaxInactiveInterval((int) (maxTimeoutTimeMilliSec - lastAccessedTimeMilliSec) / 1000);
- logger.debug("Session Management: extended session for :" + session.getId() + " to :"
- + (int) (maxTimeoutTimeMilliSec / 1000));
- // System.out.println("!!!!!!!!!extended session for :" +
- // session.getId() + " to :" +
- // (int)(maxTimeoutTimeMilliSec/1000));
- }
- } catch (Exception e) {
- logger.error("updateSessionExtensions failed to update session timeouts", e);
- // Signal a problem if any one of them fails
- result = false;
- }
-
- }
- return result;
- }
-
- /**
- * TODO: Remove static
- *
- * @param request
- * @param userName
- * @param pwd
- * @param ecompRestURL
- * @param _sessionComm
- */
- public static void handleSessionUpdatesNative(HttpServletRequest request, String userName, String pwd,
- String uebKey, String ecompRestURL, SessionCommInf _sessionComm) {
-
- if (_sessionComm == null) {
- _sessionComm = sessionComm;
- }
- try {
- synchronizeSessionForLastMinuteRequests(request, ecompRestURL, userName, pwd, uebKey, _sessionComm);
- } catch (Exception e) {
- logger.error("handleSesionUpdatesNative failed", e);
- }
- resetSessionMaxIdleTimeOut(request);
- }
-
- /**
- * TODO: remove Static
- *
- * @param request
- * @param ecompRestURL
- * @param userName
- * @param pwd
- * @param _sessionComm
- * @throws JsonProcessingException
- * @throws Exception
- */
- public static void synchronizeSessionForLastMinuteRequests(HttpServletRequest request, String ecompRestURL,
- String userName, String pwd, String uebKey, SessionCommInf _sessionComm)
- throws JsonProcessingException, Exception {
-
- HttpSession session = request.getSession(false);
- if (session == null)
- return;
-
- Object portalSessionSlotCheckObj = session.getServletContext()
- .getAttribute(PortalApiConstants.PORTAL_SESSION_SLOT_CHECK);
- Integer portalSessionSlotCheckinMilliSec = 5 * 60 * 1000; // (5 minutes)
- if (portalSessionSlotCheckObj != null) {
- portalSessionSlotCheckinMilliSec = Integer.valueOf(portalSessionSlotCheckObj.toString());
- } else {
- portalSessionSlotCheckObj = _sessionComm
- .fetchSessionSlotCheckInterval(new String[] { ecompRestURL, userName, pwd, uebKey });
- logger.debug("Fetching Portal Session Slot Object: " + portalSessionSlotCheckObj);
- if (portalSessionSlotCheckObj != null) {
- portalSessionSlotCheckinMilliSec = Integer.valueOf(portalSessionSlotCheckObj.toString());
- session.getServletContext().setAttribute(PortalApiConstants.PORTAL_SESSION_SLOT_CHECK,
- portalSessionSlotCheckinMilliSec);
- }
- }
-
- Object previousToLastAccessTimeObj = session.getAttribute(PortalApiConstants.SESSION_PREVIOUS_ACCESS_TIME);
- final long lastAccessedTimeMilliSec = session.getLastAccessedTime();
- if (previousToLastAccessTimeObj == null) {
- previousToLastAccessTimeObj = lastAccessedTimeMilliSec;
- session.setAttribute(PortalApiConstants.SESSION_PREVIOUS_ACCESS_TIME, previousToLastAccessTimeObj);
- } else {
- Long previousToLastAccessTime = (Long) previousToLastAccessTimeObj;
- final int maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000;
- if (maxIntervalMilliSec
- - (lastAccessedTimeMilliSec - previousToLastAccessTime) <= portalSessionSlotCheckinMilliSec) {
-
- String jSessionKey = (String) session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID);
- Map<String, PortalTimeoutVO> sessionTimeoutMap = new Hashtable<String, PortalTimeoutVO>();
- Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec;
-
- sessionTimeoutMap.put(PortalTimeoutHandler.portalJSessionId(jSessionKey),
- PortalTimeoutHandler.getSingleSessionTimeoutObj(jSessionKey, sessionTimOutMilliSec));
- String jsonMap = mapper.writeValueAsString(sessionTimeoutMap);
- logger.debug("Extension requested for all the Apps and Portal; JessionKey: " + jSessionKey
- + "; SessionMap: " + sessionTimeoutMap);
- _sessionComm.extendSessionTimeOuts(new String[] { ecompRestURL, userName, pwd, uebKey, jsonMap });
- }
-
- }
- }
-
- /**
- * TODO: remove static
- *
- * @param request
- */
- public static void resetSessionMaxIdleTimeOut(HttpServletRequest request) {
- try {
- HttpSession session = request.getSession(false);
- if (session == null)
- return;
- final Object maxIdleAttribute = session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME);
- if (maxIdleAttribute != null) {
- session.setMaxInactiveInterval(Integer.parseInt(maxIdleAttribute.toString()));
- }
- } catch (Exception e) {
- logger.error("resetSessionMaxIdleTimeout failed", e);
- }
-
- }
-
- /**
- *
- * @param jSessionKey
- * @param sessionTimOutMilliSec
- * @return
- */
- private static PortalTimeoutVO getSingleSessionTimeoutObj(String jSessionKey, Long sessionTimOutMilliSec) {
- return new PortalTimeoutVO(jSessionId(jSessionKey), sessionTimOutMilliSec);
- }
-
- /**
- *
- * @param jSessionId
- * @param portalJSessionId
- * @return
- */
- private static String jSessionKey(String jSessionId, String portalJSessionId) {
- return portalJSessionId + "-" + jSessionId;
- }
-
- /**
- *
- * @param jSessionKey
- * @return
- */
- private static String portalJSessionId(String jSessionKey) {
- return jSessionKey.split("-")[0];
- }
-
- /**
- *
- * @param jSessionKey
- * @return
- */
- private static String jSessionId(String jSessionKey) {
- return jSessionKey.split("-")[1];
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.listener;
-
-import java.util.HashMap;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletContextEvent;
-import javax.servlet.ServletContextListener;
-import javax.servlet.annotation.WebListener;
-import javax.servlet.http.HttpSession;
-
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-
-@WebListener
-public class UserContextListener implements ServletContextListener{
-
- public void contextInitialized(ServletContextEvent event){
- ServletContext context = event.getServletContext();
- //
- // instanciate a map to store references to all the active
- // sessions and bind it to context scope.
- //
- HashMap<String, HttpSession> activeUsers = new HashMap<String, HttpSession>();
- context.setAttribute(PortalApiConstants.ACTIVE_USERS_NAME, activeUsers);
- }
-
- /**
- * Needed for the ServletContextListener interface.
- */
- public void contextDestroyed(ServletContextEvent event){
- // To overcome the problem with losing the session references
- // during server restarts, put code here to serialize the
- // activeUsers HashMap. Then put code in the contextInitialized
- // method that reads and reloads it if it exists...
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.listener;
-
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Map;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.annotation.WebListener;
-import javax.servlet.http.HttpSession;
-import javax.servlet.http.HttpSessionEvent;
-import javax.servlet.http.HttpSessionListener;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-
-/**
- * Listens to session-create and session-destroy events.
- */
-@WebListener
-public class UserSessionListener implements HttpSessionListener {
-
- private Log logger = LogFactory.getLog(getClass());
-
- public static Map<String, HttpSession> activeSessions = new Hashtable<String, HttpSession>();
-
- public void init(ServletConfig config) {
- }
-
- /**
- * Adds sessions to the context-scoped HashMap when they begin.
- */
- public void sessionCreated(HttpSessionEvent event) {
- HttpSession session = event.getSession();
- ServletContext context = session.getServletContext();
- @SuppressWarnings("unchecked")
- HashMap<String, HttpSession> activeUsers = (HashMap<String, HttpSession>) context
- .getAttribute(PortalApiConstants.ACTIVE_USERS_NAME);
- if (activeUsers != null)
- activeUsers.put(session.getId(), session);
- context.setAttribute(PortalApiConstants.ACTIVE_USERS_NAME, activeUsers);
- activeSessions.put(session.getId(), session);
- session.getServletContext().setAttribute(PortalApiConstants.MAX_IDLE_TIME, session.getMaxInactiveInterval());
- }
-
- /**
- * Removes sessions from the context-scoped HashMap when they expire or are
- * invalidated.
- */
- public void sessionDestroyed(HttpSessionEvent event) {
- try {
- HttpSession session = event.getSession();
- ServletContext context = session.getServletContext();
- @SuppressWarnings("unchecked")
- HashMap<String, HttpSession> activeUsers = (HashMap<String, HttpSession>) context
- .getAttribute(PortalApiConstants.ACTIVE_USERS_NAME);
- if (activeUsers != null)
- activeUsers.remove(session.getId());
- activeSessions.remove(session.getId());
- PortalTimeoutHandler.sessionDestroyed(session);
- } catch (Exception e) {
- logger.warn(e.getMessage(), e);
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.rest;
-
-/**
- * Provides a convenience method for fetching the favorites for a user from the
- * ECOMP Portal.
- */
-public class FavoritesClient {
-
- /**
- * Fetches the favorites data from portal
- *
- * @param userId
- * userId value that it should be using to fetch the
- * data
- * @param appName
- * Application name for logging etc.
- * @param requestId
- * 128-bit UUID value to uniquely identify the transaction; if null, a new one is generated.
- * @param appUserName
- * REST API user-name
- * @param appPassword
- * REST API decrypted password
- * @return JSON with favorites
- * @throws Exception
- * on any failure
- */
- public static String getFavorites(String userId, String appName, String requestId, String appUserName,
- String appPassword) throws Exception {
- return RestWebServiceClient.getInstance().getPortalContent("/getFavorites", userId, appName, requestId, appUserName,
- appPassword,true);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.rest;
-
-/**
- * Provides a convenience method for fetching the functional menu for a user
- * from the ECOMP Portal via UEB.
- */
-public class FunctionalMenuClient {
-
- /**
- * Fetches the functional menu data from the configured ECOMP Portal
- * instance.
- *
- * @param userId
- * userId for the user to whom the menu will be shown
- * @param appName
- * Application name for logging etc.
- * @param requestId
- * 128-bit UUID value to uniquely identify the transaction; if
- * null, a new one is generated.
- * @param appUserName
- * REST API user name, used by Portal to authenticate the request
- * @param appPassword
- * REST API password (in the clear, not encrypted), used by
- * Portal to authenticate the request
- * @return JSON with functional menu
- * @throws Exception
- * on any failure
- */
- public static String getFunctionalMenu(String userId, String appName, String requestId, String appUserName,
- String appPassword) throws Exception {
- return RestWebServiceClient.getInstance().getPortalContent("/functionalMenuItemsForUser", userId, appName,
- requestId, appUserName, appPassword,true);
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.rest;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.util.Base64;
-import java.util.UUID;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-
-/**
- * Simple REST client for GET-ing content from and POST-ing content , Delete to the
- * Portal application.
- */
-public class RestWebServiceClient {
-
- private final Log logger = LogFactory.getLog(RestWebServiceClient.class);
-
- /**
- * Singleton instance
- */
- private static RestWebServiceClient instance = null;
-
- /**
- * Constructor is private. Clients should obtain an instance via
- * getInstance().
- */
- private RestWebServiceClient() {
- }
-
- /**
- * Gets the static instance of RestWebServiceClient; creates it if
- * necessary. Synchronized to be thread safe.
- *
- * @return Static instance of RestWebServiceClient.
- */
- public static synchronized RestWebServiceClient getInstance() {
- if (instance == null)
- instance = new RestWebServiceClient();
- return instance;
- }
-
- /**
- * Convenience method that fetches the URL for the Portal REST API endpoint
- * and the application UEB key, then calls
- * {@link #get(String, String, String, String, String, String, String)} to
- * access the Portal's REST endpoint.
- *
- * @param restPath
- * Partial path of the endpoint; e.g., "/specialRestService"
- * @param userId
- * userId for the user originating the request
- * @param appName
- * Application Name for logging.
- * @param requestId
- * 128-bit UUID value to uniquely identify the transaction.
- * @param appUserName
- * REST API user name for Portal to authenticate the request
- * @param appPassword
- * REST API password (in the clear, not encrypted) for Portal to
- * authenticate the request
- * @return Content from REST endpoint
- * @throws Exception
- * on any failure
- */
- public String getPortalContent(String restPath,String userId, String appName, String requestId, String appUserName, String appPassword, boolean isBasicAuth) throws Exception {
- String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
-
- if (restURL == null) {
- // should never happen
- String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
- logger.error(msg);
- throw new Exception(msg);
- }
- String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
-
- if (appUebKey == null) {
- // should never happen
- String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
-
- logger.error(msg);
- throw new Exception(msg);
- }
- final String restEndpointUrl = restURL + restPath;
- if(isBasicAuth)
- {
- return get(restEndpointUrl, userId,appName, requestId, appUebKey, appUserName, appPassword,isBasicAuth);
- }
- return get(restEndpointUrl, userId,appName, requestId, appUebKey, appUserName, appPassword);
- }
-
-
- /**
- * Makes a call to a Portal REST API using the specified URL and parameters.
- *
- * @param url
- * Complete URL of the REST endpoint.
- * @param loginId
- * User that it should be fetching the data
- * @param appName
- * Application name for logging; if null or empty, defaulted to
- * Unknown.
- * @param requestId
- * 128-bit UUID value to uniquely identify the transaction; if
- * null or empty, one is generated.
- * @param appUebKey
- * Unique key for the application, used by Portal to authenticate
- * the request
- * @param appUserName
- * REST API user name, used by Portal to authenticate the request
- * @param appPassword
- * REST API password, used by Portal to authenticate the request
- * @return Content from REST endpoint
- * @throws Exception
- * On any failure; e.g., unknown host.
- */
-
- public String get(String url, String loginId, String appName, String requestId, String appUebKey,
- String appUserName, String appPassword) throws Exception {
- return get(url, loginId, appName,requestId, appUebKey, appUserName, appPassword, false);
- }
-
-
- /**
- * Makes a call to a Portal REST API using the specified URL and parameters.
- *
- * @param url
- * Complete URL of the REST endpoint.
- * @param loginId
- * User that it should be fetching the data
- * @param appName
- * Application name for logging; if null or empty, defaulted to
- * Unknown.
- * @param requestId
- * 128-bit UUID value to uniquely identify the transaction; if
- * null or empty, one is generated.
- * @param appUebKey
- * Unique key for the application, used by Portal to authenticate
- * the request
- * @param appUserName
- * REST API user name, used by Portal to authenticate the request
- * @param appPassword
- * REST API password, used by Portal to authenticate the request
- * @return Content from REST endpoint
- * @throws Exception
- * On any failure; e.g., unknown host.
- */
- public String get(String url, String loginId, String appName, String requestId, String appUebKey,
- String appUserName, String appPassword, Boolean useBasicAuth) throws Exception {
-
- logger.debug("RestWebServiceClient.get (" + url + ") operation is started.");
-
- if (appName == null || appName.trim().length() == 0)
- appName = "Unknown";
- if (requestId == null || requestId.trim().length() == 0)
- requestId = UUID.randomUUID().toString();
-
- URL obj = new URL(url);
- // Create the connection object
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
- con.setRequestMethod("GET");
-
- con.setConnectTimeout(3000);
- // if the portal property is set then gets the timeout value from portal properties
- if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)!= null){
- con.setConnectTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)));
- }
- con.setReadTimeout(8000);
- if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)!= null){
- con.setReadTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)));
- }
-
- // add request header
- con.setRequestProperty("uebkey", appUebKey);
- con.setRequestProperty("LoginId", loginId);
- con.setRequestProperty("user-agent", appName);
- con.setRequestProperty("X-ECOMP-RequestID", requestId);
- con.setRequestProperty("username", appUserName);
- con.setRequestProperty("password", appPassword);
-
- if(useBasicAuth){
- String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
- con.setRequestProperty("Authorization", "Basic "+ encoding);
- }
-
- int responseCode = con.getResponseCode();
- logger.debug("get: received response code '" + responseCode + "' while getting the '" + url + "' for user: "
- + loginId);
-
- StringBuffer sb = new StringBuffer();
- BufferedReader in = null;
- try {
- in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
- String inputLine = null;
- while ((inputLine = in.readLine()) != null)
- sb.append(inputLine);
- } finally {
- try {
- if (in != null)
- in.close();
- } catch (IOException ex) {
- logger.error("get: failed to close reader", ex);
- }
- }
-
- final String response = sb.toString();
- if (logger.isDebugEnabled())
- logger.debug("get: url " + url + " yielded " + response);
- return response;
- }
-
- /**
- * Convenience method that fetches the URL for the Portal REST API endpoint
- * and the application UEB key, then calls
- * {@link #post(String, String, String, String, String, String, String, String, String)}
- * to access the Portal's REST endpoint.
- *
- * @param restPath
- * Partial path of the endpoint; e.g., "/specialRestService"
- * @param userId
- * ID for the user originating the request
- * @param appName
- * Application Name for logging.
- * @param requestId
- * 128-bit UUID value to uniquely identify the transaction.
- * @param appUserName
- * REST API user name for Portal to authenticate the request;
- * ignored if null
- * @param appPassword
- * REST API password (in the clear, not encrypted) for Portal to
- * authenticate the request; ignored if null
- * @param contentType
- * content type for header
- * @param content
- * String to post
- * @return Content from REST endpoint
- * @throws Exception
- * on any failure
- */
- public String postPortalContent(String restPath, String userId, String appName, String requestId,
- String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth) throws Exception {
- String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
-
-
- if (restURL == null) {
- // should never happen
- String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
-
- logger.error(msg);
- throw new Exception(msg);
- }
- String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
-
- if (appUebKey == null) {
- // should never happen
- String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
-
- logger.error(msg);
- throw new Exception(msg);
- }
- final String separator = restURL.endsWith("/") || restPath.startsWith("/") ? "" : "/";
- final String restEndpointUrl = restURL + separator + restPath;
- return post(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, contentType,
- content,isBasicAuth);
- }
-
- /**
- * Makes a POST call to a Portal REST API using the specified URL and
- * parameters.
- *
- * @param url
- * Complete URL of the REST endpoint.
- * @param loginId
- * User who is fetching the data
- * @param appName
- * Application name for logging; if null or empty, defaulted to
- * Unknown.
- * @param requestId
- * 128-bit UUID value to uniquely identify the transaction; if
- * null or empty, one is generated.
- * @param appUebKey
- * Unique key for the application, used by Portal to authenticate
- * the request
- * @param appUserName
- * REST API user name used by Portal to authenticate the request;
- * ignored if null
- * @param appPassword
- * REST API password used by Portal to authenticate the request;
- * ignored if null
- * @param contentType
- * MIME header
- * @param content
- * Content to POST
- * @return Any content read from the endpoint
- * @throws Exception
- * On any error
- */
- public String post(String url, String loginId, String appName, String requestId, String appUebKey,
- String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth) throws Exception {
-
- if (logger.isDebugEnabled())
- logger.debug("RestWebServiceClient.post to URL " + url);
- if (appName == null || appName.trim().length() == 0)
- appName = "Unknown";
- if (requestId == null || requestId.trim().length() == 0)
- requestId = UUID.randomUUID().toString();
-
- URL obj = new URL(url);
- // Create the connection object
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
- con.setRequestMethod("POST");
-
- con.setConnectTimeout(3000);
- // if the portal property is set then gets the timeout value from portal properties
- if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)!= null){
- con.setConnectTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)));
- }
- con.setReadTimeout(15000);
- if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)!= null){
- con.setReadTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)));
- }
-
- // add request header
- con.setRequestProperty("uebkey", appUebKey);
- if (appUserName != null)
- con.setRequestProperty("username", appUserName);
- if (appPassword != null)
- con.setRequestProperty("password", appPassword);
- con.setRequestProperty("LoginId", loginId);
- con.setRequestProperty("user-agent", appName);
- con.setRequestProperty("X-ECOMP-RequestID", requestId);
- con.setRequestProperty("Content-Type", contentType);
- if(isBasicAuth){
- String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
- con.setRequestProperty("Authorization", "Basic "+ encoding);
- }
-
- con.setDoInput(true);
- con.setDoOutput(true);
- if( content != null)
- {
- con.getOutputStream().write(content.getBytes());
- }
- con.getOutputStream().flush();
- con.getOutputStream().close();
-
- int responseCode = con.getResponseCode();
- logger.debug("Response Code : " + responseCode);
-
- StringBuffer sb = new StringBuffer();
- InputStreamReader in = null;
- char[] buf = new char[8196];
- int bytes;
- try {
- in = new InputStreamReader(con.getInputStream(), "UTF-8");
- while ((bytes = in.read(buf)) > 0)
- sb.append(new String(buf, 0, bytes));
- } finally {
- try {
- if (in != null)
- in.close();
- } catch (IOException ex) {
- logger.warn("get: failed to close reader", ex);
- }
- }
-
- return sb.toString();
- }
-
-
- public String deletePortalContent(String restPath, String userId, String appName, String requestId,
- String appUserName, String appPassword, String contentType, String content, boolean isBasicAuth) throws Exception {
- String restURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
-
- if (restURL == null) {
- // should never happen
- String msg = "getPortalContent: failed to get property " + PortalApiConstants.ECOMP_REST_URL;
-
- logger.error(msg);
- throw new Exception(msg);
- }
- String appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
-
- if (appUebKey == null) {
- // should never happen
- String msg = "getPortalContent: failed to get property " + PortalApiConstants.UEB_APP_KEY;
-
- logger.error(msg);
- throw new Exception(msg);
- }
- final String separator = restURL.endsWith("/") || restPath.startsWith("/") ? "" : "/";
- final String restEndpointUrl = restURL + separator + restPath;
- return delete(restEndpointUrl, userId, appName, requestId, appUebKey, appUserName, appPassword, contentType,
- content,isBasicAuth);
- }
-
- public String delete(String url, String loginId, String appName, String requestId, String appUebKey,
- String appUserName, String appPassword, String contentType, String content,boolean isBasicAuth) throws Exception {
-
- if (logger.isDebugEnabled())
- logger.debug("RestWebServiceClient.post to URL " + url);
- if (appName == null || appName.trim().length() == 0)
- appName = "Unknown";
- if (requestId == null || requestId.trim().length() == 0)
- requestId = UUID.randomUUID().toString();
-
- URL obj = new URL(url);
- // Create the connection object
- HttpURLConnection con = (HttpURLConnection) obj.openConnection();
- con.setRequestMethod("DELETE");
- con.setConnectTimeout(3000);
- // if the portal property is set then gets the timeout value from portal properties
- if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)!= null){
- con.setConnectTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_CONNECTION_TIMEOUT)));
- }
- con.setReadTimeout(15000);
- if(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)!= null){
- con.setReadTimeout(Integer.parseInt(PortalApiProperties.getProperty(PortalApiConstants.EXT_REQUEST_READ_TIMEOUT)));
- }
- // add request header
- con.setRequestProperty("uebkey", appUebKey);
- if (appUserName != null)
- con.setRequestProperty("username", appUserName);
- if (appPassword != null)
- con.setRequestProperty("password", appPassword);
- con.setRequestProperty("LoginId", loginId);
- con.setRequestProperty("user-agent", appName);
- con.setRequestProperty("X-ECOMP-RequestID", requestId);
- con.setRequestProperty("Content-Type", contentType);
- if(isBasicAuth){
- String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + appPassword).getBytes());
- con.setRequestProperty("Authorization", "Basic "+ encoding);
- }
-
- con.setDoInput(true);
- con.setDoOutput(true);
- if( content != null)
- {
- con.getOutputStream().write(content.getBytes());
- }
- con.getOutputStream().flush();
- con.getOutputStream().close();
-
- int responseCode = con.getResponseCode();
- logger.debug("Response Code : " + responseCode);
-
- StringBuffer sb = new StringBuffer();
- InputStreamReader in = null;
- char[] buf = new char[8196];
- int bytes;
- try {
- in = new InputStreamReader(con.getInputStream(), "UTF-8");
- while ((bytes = in.read(buf)) > 0)
- sb.append(new String(buf, 0, bytes));
- } finally {
- try {
- if (in != null)
- in.close();
- } catch (IOException ex) {
- logger.warn("get: failed to close reader", ex);
- }
- }
-
- return sb.toString();
- }
-
-
- /**
- * Basic unit test for the client to call Portal app on localhost.
- *
- * @param args
- * Ignored
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- RestWebServiceClient client = RestWebServiceClient.getInstance();
- final String getUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/analytics";
- String get = client.get(getUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword", null);
- System.out.println("Get result:\n" + get);
- final String postUrl = "http://www.ecomp.openecomp.org:8080/ecompportal/auxapi/storeAnalytics";
- final String content = " { " + " \"action\" : \"test1\", " + " \"page\" : \"test2\", "
- + " \"function\" : \"test3\", " + " \"userid\" : \"ab1234\" " + "}";
- String post = client.post(postUrl, "userId", "appName", null, "appUebKey", "appUserName", "appPassword",
- "application/json", content, true);
- System.out.println("Post result:\n" + post);
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.util;
-
-import javax.crypto.Cipher;
-import javax.crypto.spec.SecretKeySpec;
-
-import org.apache.commons.codec.binary.Base64;
-
-public class CipherUtil {
-
- private final static String key = "AGLDdG4D04BKm2IxIWEr8o==!";
-
- /**
- * @param plainText
- * @param secretKey
- * @return encrypted version of plain text.
- * @throws Exception
- */
- public static String encrypt(String plainText, String secretKey) throws Exception{
- byte[] rawKey;
- String encryptedString;
- SecretKeySpec sKeySpec;
- byte[] encryptText = plainText.getBytes("UTF-8");
- Cipher cipher;
- rawKey = Base64.decodeBase64(secretKey);
- sKeySpec = new SecretKeySpec(rawKey, "AES");
- cipher = Cipher.getInstance("AES");
- cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
- encryptedString = Base64.encodeBase64String(cipher.doFinal(encryptText));
-
- return encryptedString;
- }
-
- /**
- *
- * @param plainText
- * @return Encrypted Text
- * @throws Exception
- */
- public static String encrypt(String plainText) throws Exception
- {
- return CipherUtil.encrypt(plainText,key);
- }
-
- /**
- * @param encryptedText
- * @param secretKey
- * @return plain text version of encrypted text
- * @throws Exception
- */
- public static String decrypt(String encryptedText, String secretKey) throws Exception {
- Cipher cipher;
- String encryptedString;
- byte[] encryptText = null;
- byte[] rawKey;
- SecretKeySpec sKeySpec;
-
- rawKey = Base64.decodeBase64(secretKey);
- sKeySpec = new SecretKeySpec(rawKey, "AES");
- encryptText = Base64.decodeBase64(encryptedText.getBytes("UTF-8"));
- cipher = Cipher.getInstance("AES");
- cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
- encryptedString = new String(cipher.doFinal(encryptText));
-
- return encryptedString;
- }
-
- /**
- * @param encryptedText
- * @return Decrypted Text
- * @throws Exception
- */
- public static String decrypt(String encryptedText) throws Exception
- {
- return CipherUtil.decrypt(encryptedText,key);
- }
-
-
- public static void main(String[] args) throws Exception {
-
- String password = "Welcome123";
- String encrypted;
- String decrypted;
-
- if (args.length != 2) {
- System.out.println("Default password testing... ");
- System.out.println("Plain password: " + password);
- encrypted = encrypt(password);
- System.out.println("Encrypted password: " + encrypted);
- decrypted = decrypt(encrypted);
- System.out.println("Decrypted password: " + decrypted);
- } else {
- String whatToDo = args[0];
- if (whatToDo.equalsIgnoreCase("d")) {
- encrypted = args[1];
- System.out.println("Encrypted Text: " + encrypted);
- decrypted = decrypt(encrypted);
- System.out.println("Decrypted Text: " + decrypted);
- } else {
- decrypted = args[1];
- System.out.println("Plain Text: " + decrypted);
- encrypted = encrypt(decrypted);
- System.out.println("Encrypted Text" + encrypted);
- }
- }
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.util;
-
-public interface PortalApiConstants {
- public static final String API_PREFIX = "/api/v2";
- public static final String PORTAL_JSESSION_ID = "PORTAL_JSESSION_ID";
- public static final String PORTAL_JSESSION_BIND = "PORTAL_JSESSION_BIND";
- public static final String ACTIVE_USERS_NAME = "activeUsers";
-
- /** Portal service cookie name */
- public static final String EP_SERVICE = "EPService";
-
- public static final String GLOBAL_SESSION_MAX_IDLE_TIME = "global_session_max_idle_time";
- public static final String PORTAL_SESSION_SLOT_CHECK = "portal_session_slot_check";
- public static final String SESSION_PREVIOUS_ACCESS_TIME = "session_previous_access_time";
- public static final String MAX_IDLE_TIME = "max.idle.time";
-
- // Names of keys in the portal.properties file
- public static final String PORTAL_API_IMPL_CLASS = "portal.api.impl.class";
- public static final String ECOMP_REDIRECT_URL = "ecomp_redirect_url";
- public static final String ECOMP_REST_URL = "ecomp_rest_url";
- public static final String ROLE_ACCESS_CENTRALIZED = "role_access_centralized";
- public static final String CSP_COOKIE_NAME = "csp_cookie_name";
- public static final String CSP_GATE_KEEPER_PROD_KEY = "csp_gate_keeper_prod_key";
-
- // UEB related
- public static final String UEB_URL_LIST = "ueb_url_list"; // In properties file
- public static final String ECOMP_PORTAL_INBOX_NAME = "ecomp_portal_inbox_name";
- public static final String ECOMP_DEFAULT_MSG_ID = "0";
- public static final String ECOMP_GENERAL_UEB_PARTITION = "EPGeneralPartition";
- public static final String UEB_LISTENERS_ENABLE = "ueb_listeners_enable";
- public static final String UEB_APP_INBOUND_MAILBOX_NAME = "ueb_app_mailbox_name";
- public static final String UEB_APP_CONSUMER_GROUP_NAME = "ueb_app_consumer_group_name";
-
- // UebManager generates a consumer group name for special token {UUID}
- public static final String UEB_APP_CONSUMER_GROUP_NAME_GENERATOR = "{UUID}";
- public static final String UEB_APP_KEY = "ueb_app_key";
- public static final String UEB_APP_SECRET = "ueb_app_secret";
- public static final String ECOMP_UEB_INVALID_MSG = "100: Invalid Message format.";
- public static final String ECOMP_UEB_TIMEOUT_ERROR = "101: Timeout";
- public static final String ECOMP_UEB_UNKNOWN_PUBLISH_ERROR = "102: Unknown error during publish";
- public static final String ECOMP_UEB_UNKNOWN_CONSUME_ERROR = "103: Unknown error during consume";
- public static final String USE_REST_FOR_FUNCTIONAL_MENU = "use_rest_for_functional_menu";
-
- public static final String EXT_REQUEST_CONNECTION_TIMEOUT = "ext_req_connection_timeout";
- public static final String EXT_REQUEST_READ_TIMEOUT = "ext_req_read_timeout";
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.onboarding.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * Singleton Class representing portal properties. Searches the classpath for
- * the file "portal.properties".
- *
- * To put the file "portal.properties" on the classpath, it can be in the same
- * directory where the first package folder is - 'myClasses' folder in the
- * following case as an example:
- *
- */
-public class PortalApiProperties {
-
- private static final Log logger = LogFactory.getLog(PortalApiProperties.class);
-
- private static Properties properties;
- private static String propertyFileName = "portal.properties";
-
- /**
- * Constructor is private.
- */
- private PortalApiProperties() {
- }
-
- /**
- * Gets the property value for the specified key. If a value is found,
- * leading and trailing space is trimmed.
- *
- * @param property
- * @return Value for the named property; null if the property file was not
- * loaded or the key was not found.
- */
- public static String getProperty(String property) {
- if (properties == null) {
- synchronized (propertyFileName) {
- try {
- if (!initialize()) {
- logger.error("Failed to read property file " + propertyFileName);
- return null;
- }
- } catch (IOException e) {
- logger.error("Failed to read property file " + propertyFileName, e);
- return null;
- }
- }
- }
- String value = properties.getProperty(property);
- if (value != null)
- value = value.trim();
- return value;
- }
-
- /**
- * Reads properties from a portal.properties file on the classpath.
- *
- * Clients do NOT need to call this method. Clients MAY call this method to
- * test whether the properties file can be loaded successfully.
- *
- * @return True if properties were successfully loaded, else false.
- * @throws IOException
- */
- public static boolean initialize() throws IOException {
- if (properties != null)
- return true;
- InputStream in = PortalApiProperties.class.getClassLoader().getResourceAsStream(propertyFileName);
- if (in == null)
- return false;
- properties = new Properties();
- try {
- properties.load(in);
- } finally {
- in.close();
- }
- return true;
- }
-}
+++ /dev/null
-/* ================================================================================
- * 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.core.onboarding.util;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.openecomp.portalsdk.core.onboarding.crossapi.PortalRestAPIProxy;
-import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException;
-
-public class SSOFilter implements Filter {
-
- private final Log logger = LogFactory.getLog(getClass());
-
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
- throws java.io.IOException, ServletException {
-
- try {
- if (PortalRestAPIProxy.getPortalRestApiServiceImpl().getUserId((HttpServletRequest) request) == null) {
- String redirectURL = SSOUtil.getECOMPSSORedirectURL(((HttpServletRequest) request),
- ((HttpServletResponse) response),
- (((HttpServletRequest) request).getRequestURI()
- .substring(((HttpServletRequest) request).getContextPath().length() + 1)
- + (((HttpServletRequest) request).getQueryString() != null
- ? ("?" + ((HttpServletRequest) request).getQueryString()) : "")));
-
- ((HttpServletResponse) response).sendRedirect(redirectURL);
-
- } else {
- // Pass request back down the filter chain
- chain.doFilter(request, response);
-
- }
- } catch (PortalAPIException e) {
- logger.error("Issue calling getUserId method ");
- throw new ServletException(e);
- }
-
- }
-
- public void destroy() {
-
- }
-
- public void init(FilterConfig arg0) throws ServletException {
- // TODO Auto-generated method stub
-
- }
-}
+++ /dev/null
-package org.openecomp.portalsdk.core.onboarding.util;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class SSOUtil {
-
- private static final Log logger = LogFactory.getLog(SSOUtil.class);
-
- /**
- * Constructs a path for this server, this app's context, etc.
- *
- * @param request
- * HttpServletRequest
- * @param response
- * HttpServletResponse
- * @param forwardPath
- * Path to forward user
- * @return Redirect URL
- */
- public static String getECOMPSSORedirectURL(HttpServletRequest request, HttpServletResponse response,
- String forwardPath) {
- String appURL = (request.isSecure() ? "https://" : "http://") + request.getServerName() + ":"
- + request.getServerPort() + request.getContextPath() + "/" + forwardPath;
- String encodedAppURL = null;
- try {
- encodedAppURL = URLEncoder.encode(appURL, "UTF-8");
- } catch (UnsupportedEncodingException ex) {
- logger.error("getECOMPSSORedirectURL: Failed to encode app URL " + appURL);
- }
- String portalURL = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
- if (portalURL == null || portalURL.length() == 0) {
- logger.error("getECOMPSSORedirectURL: Failed to get property " + PortalApiConstants.ECOMP_REDIRECT_URL);
- return null;
- }
- String redirectURL = portalURL + "?redirectUrl=" + encodedAppURL;
- return redirectURL;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.restful.domain;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-/**
- * This bean holds the information for a role in the role and user management
- * REST API.
- */
-
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class EcompRole implements Comparable<EcompRole>{
-
- protected Long id;
- private String name;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((id == null) ? 0 : id.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- EcompRole other = (EcompRole) obj;
- if (id == null) {
- if (other.id != null)
- return false;
- } else if (!id.equals(other.id))
- return false;
- return true;
- }
-
- @Override
- public String toString() {
- String s = "@EcompRole[id: " + id + "; name: " + name + "]";
- return s;
- }
-
- @Override
- public int compareTo(EcompRole o) {
- return this.id.compareTo(o.id);
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.restful.domain;
-
-import java.util.Set;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-/**
- * This bean holds the information for a user in the role and user management
- * REST API.
- */
-
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class EcompUser implements Comparable<EcompUser>{
-
- private Long orgId;
- private String managerId;
- private String firstName;
- private String middleInitial;
- private String lastName;
- private String phone;
- private String email;
- private String hrid;
- private String orgUserId;
- private String orgCode;
- private String orgManagerUserId;
- private String jobTitle;
- private String loginId;
- private boolean active;
-
-
- private Set<EcompRole> roles;
-
- public Long getOrgId() {
- return orgId;
- }
-
- public void setOrgId(Long orgId) {
- this.orgId = orgId;
- }
-
- public String getFirstName() {
- return firstName;
- }
-
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
-
- public String getMiddleInitial() {
- return middleInitial;
- }
-
- public void setMiddleInitial(String middleInitial) {
- this.middleInitial = middleInitial;
- }
-
- public String getLastName() {
- return lastName;
- }
-
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
-
- public String getPhone() {
- return phone;
- }
-
- public void setPhone(String phone) {
- this.phone = phone;
- }
-
- public String getEmail() {
- return email;
- }
-
- public void setEmail(String email) {
- this.email = email;
- }
-
- public String getHrid() {
- return hrid;
- }
-
- public void setHrid(String hrid) {
- this.hrid = hrid;
- }
-
- public String getOrgUserId() {
- return orgUserId;
- }
-
- public void setOrgUserId(String orgUserId) {
- this.orgUserId = orgUserId;
- }
-
- public String getOrgCode() {
- return orgCode;
- }
-
- public void setOrgCode(String orgCode) {
- this.orgCode = orgCode;
- }
-
- public String getOrgManagerUserId() {
- return orgManagerUserId;
- }
-
- public void setOrgManagerUserId(String orgManagerUserId) {
- this.orgManagerUserId = orgManagerUserId;
- }
-
- public String getJobTitle() {
- return jobTitle;
- }
-
- public void setJobTitle(String jobTitle) {
- this.jobTitle = jobTitle;
- }
-
- public String getLoginId() {
- return loginId;
- }
-
- public void setLoginId(String loginId) {
- this.loginId = loginId;
- }
-
- public boolean isActive() {
- return active;
- }
-
- public void setActive(boolean active) {
- this.active = active;
- }
-
- public Set<EcompRole> getRoles() {
- return roles;
- }
-
- public void setRoles(Set<EcompRole> roles) {
- this.roles = roles;
- }
-
- public String getManagerId() {
- return managerId;
- }
-
- public void setManagerId(String managerId) {
- this.managerId = managerId;
- }
-
- @Override
- public String toString() {
- String s = "@EcompUser[orgId: " + orgId //
- + ", firstName: " + firstName //
- + ", mi: " + middleInitial //
- + ", lastName: " + lastName //
- + ", phone: " + phone //
- + ", email: " + email //
- + ", hrid: " + hrid //
- + ", orgUserId: " + orgUserId //
- + ", orgCode: " + orgCode //
- + ", orgManagerUserId: " + orgManagerUserId //
- + ", jobTitle: " + jobTitle //
- + ", loginId: " + loginId //
- + ", active:" + active //
- + "]";
- return s;
- }
-
- @Override
- public int compareTo(EcompUser o) {
- return this.loginId.compareTo(o.loginId);
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.restful.domain;
-
-public class PortalTimeoutVO implements Comparable<PortalTimeoutVO>{
-
- private String jSessionId;
- private Long sessionTimOutMilliSec;
-
- public PortalTimeoutVO(){
-
- }
-
- public PortalTimeoutVO(String _jSessionId, Long _sessionTimOutMilliSec) {
- setjSessionId(_jSessionId);
- setSessionTimOutMilliSec(_sessionTimOutMilliSec);
-
- }
-
- public String getjSessionId() {
- return jSessionId;
- }
-
- public void setjSessionId(String jSessionId) {
- this.jSessionId = jSessionId;
- }
-
- public Long getSessionTimOutMilliSec() {
- return sessionTimOutMilliSec;
- }
-
- public void setSessionTimOutMilliSec(Long sessionTimOutMilliSec) {
- this.sessionTimOutMilliSec = sessionTimOutMilliSec;
- }
-
- @Override
- public int compareTo(PortalTimeoutVO o) {
- return sessionTimOutMilliSec.compareTo(o.sessionTimOutMilliSec);
- }
-
-
-
-
-
-
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.core.restful.domain;
-
-/**
- * Bean that represents shared-context data transferred in JSON objects. This is
- * a minimum example:
- *
- * <PRE>
- * {
- * "context_id": "abc123",
- * "ckey": "myKey",
- * "cvalue": "my context value to share"
- * }
- * </PRE>
- */
-public class SharedContext {
-
- // Response field indicates nothing else is present
- private String response;
- // Required fields when data is present
- private String context_id, ckey, cvalue;
- private Long id, create_time;
- // Additional database fields from the DomainVO object.
- private String created, modified, createdId, modifiedId, auditUserId, auditTrail, rowNum;
-
- /**
- * Gets the response field.
- *
- * @return response
- */
- public String getResponse() {
- return response;
- }
-
- /**
- * Sets the response field.
- *
- * @param response
- * The response to set
- */
- public void setResponse(final String response) {
- this.response = response;
- }
-
- /**
- * Gets the database row ID.
- *
- * @return Database row ID
- */
- public Long getId() {
- return id;
- }
-
- /**
- * Sets the database row ID.
- *
- * @param id
- */
- public void setId(final Long id) {
- this.id = id;
- }
-
- /**
- * Gets the creation time
- *
- * @return Creation time as a Long
- */
- public Long getCreate_time() {
- return create_time;
- }
-
- /**
- * Sets the creation time
- *
- * @param create_time
- */
- public void setCreate_time(final Long create_time) {
- this.create_time = create_time;
- }
-
- /**
- * Gets the context ID
- *
- * @return Context ID
- */
- public String getContext_id() {
- return context_id;
- }
-
- /**
- * Sets the context ID
- *
- * @param context_id
- */
- public void setContext_id(final String context_id) {
- this.context_id = context_id;
- }
-
- /**
- * Gets the key of the key-value pair. Called ckey because "key" is a
- * reserved word in Mysql.
- *
- * @return The key
- */
- public String getCkey() {
- return ckey;
- }
-
- /**
- * Sets the key of the key-value pair.
- *
- * @param ckey
- */
- public void setCkey(final String ckey) {
- this.ckey = ckey;
- }
-
- /**
- * Gets the value of the key-value pair. Called cvalue because "value" is a
- * reserved word in Mysql.
- *
- * @return Value of the key-value pair.
- */
- public String getCvalue() {
- return cvalue;
- }
-
- /**
- * Sets the value of the key-value pair.
- *
- * @param cvalue
- */
- public void setCvalue(final String cvalue) {
- this.cvalue = cvalue;
- }
-
- /**
- * Gets the created value.
- *
- * @return Created info from database
- */
- public String getCreated() {
- return created;
- }
-
- /**
- * Sets the created value.
- *
- * @param created
- */
- public void setCreated(String created) {
- this.created = created;
- }
-
- /**
- * Gets the modified value.
- *
- * @return Modified info from database
- */
- public String getModified() {
- return modified;
- }
-
- /**
- * Sets the modified value.
- *
- * @param modified
- */
- public void setModified(String modified) {
- this.modified = modified;
- }
-
- /**
- * Gets the createdId value.
- *
- * @return CreatedId info from database
- */
- public String getCreatedId() {
- return createdId;
- }
-
- /**
- * Sets the createdId value.
- *
- * @param createdId
- */
- public void setCreatedId(String createdId) {
- this.createdId = createdId;
- }
-
- /**
- * Gets the modifiedId value.
- *
- * @return ModifiedId info from database
- */
- public String getModifiedId() {
- return modifiedId;
- }
-
- /**
- * Sets the modifiedId value.
- *
- * @param modifiedId
- */
- public void setModifiedId(String modifiedId) {
- this.modifiedId = modifiedId;
- }
-
- /**
- * Gets the audit user ID value.
- *
- * @return AuditUserId from database
- */
- public String getAuditUserId() {
- return auditUserId;
- }
-
- /**
- * Sets the audit user ID value.
- *
- * @param auditUserId
- */
- public void setAuditUserId(String auditUserId) {
- this.auditUserId = auditUserId;
- }
-
- /**
- * Gets the audit trail value.
- *
- * @return AuditTrail from database.
- */
- public String getAuditTrail() {
- return auditTrail;
- }
-
- /**
- * Sets the audit trail value.
- *
- * @param auditTrail
- */
- public void setAuditTrail(String auditTrail) {
- this.auditTrail = auditTrail;
- }
-
- /**
- * Gets the row num value.
- *
- * @return rowNum from database.
- */
- public String getRowNum() {
- return rowNum;
- }
-
- /**
- * Sets the row num value.
- *
- * @param rowNum
- */
- public void setRowNum(String rowNum) {
- this.rowNum = rowNum;
- }
-
- @Override
- public boolean equals(Object obj) {
- SharedContext other = (SharedContext) obj;
- return this.id == other.id && this.context_id.equals(other.context_id) && this.ckey.equals(other.ckey)
- && this.cvalue.equals(other.cvalue);
- }
-
- @Override
- public int hashCode() {
- return (int) (id + context_id.hashCode() + ckey.hashCode() + cvalue.hashCode());
- }
-
- @Override
- public String toString() {
- String s = "@SharedContext[id: " + id + "; context_id: " + context_id + "; ckey: " + ckey + "; cvalue: "
- + cvalue + "]";
- return s;
- }
-
-}
\ No newline at end of file
-# ECOMP Portal SDK Workflow
+# ONAP Portal SDK Workflow
## Overview
-This is the Maven project for the ECOMP Portal SDK Workflow library,
+This is the Maven project for the ONAP Portal SDK Workflow library,
which is distributed as epsdk-workflow-N.N.N.jar. This library
requires Hibernate and Spring, and provides features including
schedulers, workflows and R Cloud integration.
### ONAP Distributions
-Version 1.3.0
-- [Portal-19] Renaming the Group Id in the POM file to org.onap.portal.sdk
+Version 1.4.0
+- PORTAL-19 Rename Java package base to org.onap
+- PORTAL-42 Use OParent as parent POM
+- PORTAL-72 Address Sonar Scan code issues
+- PORTAL-90 Use approved ONAP license text
+
+Version 1.3.0, 28 August 2017
+- Portal-19 Renaming the Group Id in the POM file to org.onap.portal.sdk
Version 1.1.0
-- [Portal-7] Improvements added as part of the rebasing process
+- Portal-7 Improvements added as part of the rebasing process
Version 1.0.0
- Initial release
<parent>
<groupId>org.onap.portal.sdk</groupId>
<artifactId>epsdk-project</artifactId>
- <version>1.3.0-SNAPSHOT</version>
+ <version>1.4.0-SNAPSHOT</version>
</parent>
<!-- GroupId is inherited from parent -->
<artifactId>epsdk-workflow</artifactId>
<!-- Version is inherited from parent -->
<packaging>jar</packaging>
- <name>ECOMP Portal SDK Workflow</name>
+ <name>ONAP Portal SDK Workflow</name>
<description>Provides workflow features for SDK applications</description>
+ <!-- properties are inherited from parent -->
+
<!-- repositories are inherited from parent -->
<dependencies>
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.rnotebookintegration.controller;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.UserProfileService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+@Controller
+@RequestMapping("/")
+public class NotebookController extends RestrictedBaseController{
+
+ @RequestMapping(value = {"/notebook" }, method = RequestMethod.GET)
+ public ModelAndView noteBook(HttpServletRequest request) {
+
+ try {
+
+ } catch (Exception e) {
+
+
+ }
+ return new ModelAndView(getViewName());
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+
+package org.onap.portalsdk.rnotebookintegration.controller;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+@Controller
+@RequestMapping("/")
+public class NotebookTestController extends RestrictedBaseController{
+
+ @RequestMapping(value = {"/nbooktest" }, method = RequestMethod.GET)
+ public ModelAndView noteBook(HttpServletRequest request) {
+ return new ModelAndView(getViewName());
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.rnotebookintegration.controller;
+
+import java.util.HashMap;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.hibernate.validator.internal.util.privilegedactions.GetMethodFromPropertyName;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.controller.RestrictedRESTfulBaseController;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.restful.domain.EcompUser;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.onap.portalsdk.rnotebookintegration.exception.RNotebookIntegrationException;
+import org.onap.portalsdk.rnotebookintegration.service.RNoteBookIntegrationService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/rNotebook/")
+
+public class RNoteBookController extends RestrictedRESTfulBaseController {
+
+ @Autowired
+ private RNoteBookIntegrationService rNoteBookIntegrationService;
+
+
+
+ public RNoteBookIntegrationService getrNoteBookIntegrationService() {
+ return rNoteBookIntegrationService;
+ }
+
+
+
+ public void setrNoteBookIntegrationService(
+ RNoteBookIntegrationService rNoteBookIntegrationService) {
+ this.rNoteBookIntegrationService = rNoteBookIntegrationService;
+ }
+
+
+
+ @RequestMapping(value = { "authCr" }, method = RequestMethod.GET, produces = "application/json")
+ public @ResponseBody ResponseEntity<String> getRNotebookCredentials (String token) throws Exception {
+ //ObjectMapper mapper = new ObjectMapper();
+ //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ //JsonNode root = mapper.readTree(request.getReader());
+ //String token = root.get("authenticationToken").textValue();
+
+ String returnJSON = "";
+ try{
+ returnJSON = this.getrNoteBookIntegrationService().getRNotebookCredentials(token);
+ } catch(RNotebookIntegrationException re){
+ if (re.getErrorCode().equals(RNotebookIntegrationException.ERROR_CODE_TOKEN_EXPIRED)){
+ return new ResponseEntity<String>(JsonMessage.buildJsonResponse(false, re.getMessage()), HttpStatus.BAD_REQUEST);
+ }
+ else {
+ return new ResponseEntity<String>(JsonMessage.buildJsonResponse(false, re.getMessage()), HttpStatus.BAD_REQUEST);
+ }
+ }
+ catch (Exception e){
+ return new ResponseEntity<String>(JsonMessage.buildJsonResponse(false, e.getMessage()), HttpStatus.BAD_REQUEST);
+ }
+
+ return new ResponseEntity<String>(returnJSON, HttpStatus.OK);
+
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.rnotebookintegration.controller;
+
+import java.util.HashMap;
+import java.util.Iterator;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.restful.domain.EcompUser;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.onap.portalsdk.rnotebookintegration.exception.RNotebookIntegrationException;
+import org.onap.portalsdk.rnotebookintegration.service.RNoteBookIntegrationService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+@Controller
+@RequestMapping("/rNotebookFE/")
+public class RNoteBookFEController extends RestrictedBaseController {
+ @Autowired
+ private RNoteBookIntegrationService rNoteBookIntegrationService;
+
+
+
+ public RNoteBookIntegrationService getrNoteBookIntegrationService() {
+ return rNoteBookIntegrationService;
+ }
+
+
+
+ public void setrNoteBookIntegrationService(
+ RNoteBookIntegrationService rNoteBookIntegrationService) {
+ this.rNoteBookIntegrationService = rNoteBookIntegrationService;
+ }
+
+ @RequestMapping(value = { "authCr" }, method = RequestMethod.POST, produces = "application/json")
+ public @ResponseBody ResponseEntity<String> saveRNotebookCredentials (@RequestBody String notebookId, HttpServletRequest request,
+ HttpServletResponse response) throws Exception {
+ //ObjectMapper mapper = new ObjectMapper();
+ //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ //JsonNode root = mapper.readTree(request.getReader());
+ //String token = root.get("authenticationToken").textValue();
+ System.out.println("Notebook id "+notebookId);
+ System.out.println("Query parameters "+request.getParameter("qparams"));
+ String retUrl = "";
+ try{
+
+ User user = UserUtils.getUserSession(request);
+ user = (User) this.getDataAccessService().getDomainObject(User.class, user.getId(), null);
+
+ EcompUser ecUser =UserUtils.convertToEcompUser(user);
+
+ HashMap<String, String> map = new HashMap<String, String>();
+ JSONObject jObject = new JSONObject(request.getParameter("qparams"));
+ Iterator<?> keys = jObject.keys();
+
+ while( keys.hasNext() ){
+ String key = (String)keys.next();
+ String value = jObject.getString(key);
+ map.put(key, value);
+
+ }
+
+ System.out.println("json : "+jObject);
+ System.out.println("map : "+map);
+
+ // String token = this.getrNoteBookIntegrationService().saveRNotebookCredentials(notebookId, ecUser, new HashMap<String, String>());
+ String token = this.getrNoteBookIntegrationService().saveRNotebookCredentials(notebookId, ecUser, map);
+
+ String guard = SystemProperties.getProperty("guard_notebook_url");
+
+ retUrl = guard + "id=" + token;
+
+
+ } catch (RNotebookIntegrationException re){
+ return new ResponseEntity<String>(re.getMessage(), HttpStatus.BAD_REQUEST);
+ } catch (Exception e){
+ return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
+ }
+
+ return new ResponseEntity<String>(retUrl, HttpStatus.OK);
+
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.rnotebookintegration.domain;
+
+import java.util.Date;
+import java.util.Map;
+
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.domain.support.DomainVo;
+import org.onap.portalsdk.core.restful.domain.EcompUser;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+public class RNoteBookCredentials extends DomainVo {
+ private EcompUser userInfo;
+ private String token;
+ private Date createdDate;
+ private String notebookID;
+ private Map<String, String> parameters;
+ private Date tokenReadDate;
+ @JsonIgnore
+ private String userString;
+ @JsonIgnore
+ private String parametersString;
+
+ public String getToken() {
+ return token;
+ }
+ public void setToken(String token) {
+ this.token = token;
+ }
+ public Date getCreatedDate() {
+ return createdDate;
+ }
+ public void setCreatedDate(Date createdDate) {
+ this.createdDate = createdDate;
+ }
+ public String getNotebookID() {
+ return notebookID;
+ }
+ public EcompUser getUserInfo() {
+ return userInfo;
+ }
+ public void setUserInfo(EcompUser userInfo) {
+ this.userInfo = userInfo;
+ }
+ public void setNotebookID(String notebookID) {
+ this.notebookID = notebookID;
+ }
+ public String getUserString() {
+ return userString;
+ }
+ public void setUserString(String userString) {
+ this.userString = userString;
+ }
+ public Map<String, String> getParameters() {
+ return parameters;
+ }
+ public void setParameters(Map<String, String> parameters) {
+ this.parameters = parameters;
+ }
+ public String getParametersString() {
+ return parametersString;
+ }
+ public void setParametersString(String parametersString) {
+ this.parametersString = parametersString;
+ }
+ public Date getTokenReadDate() {
+ return tokenReadDate;
+ }
+ public void setTokenReadDate(Date tokenReadDate) {
+ this.tokenReadDate = tokenReadDate;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.rnotebookintegration.exception;
+
+public class RNotebookIntegrationException extends Exception {
+ public static final String ERROR_CODE_TOKEN_EXPIRED = "ERROR_CODE_TOKEN_EXPIRED";
+ public static final String ERROR_CODE_TOKEN_INVALID = "ERROR_CODE_TOKEN_INVALID";
+
+ String errorCode;
+
+ public RNotebookIntegrationException(String errorCodeStr){
+ super(errorCodeStr);
+ this.errorCode = errorCodeStr;
+ }
+
+ public String getErrorCode() {
+ return errorCode;
+ }
+
+ public void setErrorCode(String errorCode) {
+ this.errorCode = errorCode;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.rnotebookintegration.service;
+
+import java.util.Map;
+
+import org.onap.portalsdk.core.restful.domain.EcompUser;
+import org.onap.portalsdk.rnotebookintegration.exception.RNotebookIntegrationException;
+
+public interface RNoteBookIntegrationService {
+ public String getRNotebookCredentials(String token) throws RNotebookIntegrationException, Exception;
+
+ public String saveRNotebookCredentials(String notebookId, EcompUser user, Map<String, String> params) throws RNotebookIntegrationException, Exception;
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.rnotebookintegration.service;
+
+import java.security.SecureRandom;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.restful.domain.EcompUser;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.onap.portalsdk.rnotebookintegration.domain.RNoteBookCredentials;
+import org.onap.portalsdk.rnotebookintegration.exception.RNotebookIntegrationException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Service("RNoteBookIntegrationService")
+@Transactional
+public class RNoteBookIntegrationServiceImpl implements RNoteBookIntegrationService {
+
+ private final long tokenTTL = 50000L;
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RNoteBookIntegrationServiceImpl.class);
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ @Override
+ public String getRNotebookCredentials(String token) throws RNotebookIntegrationException, Exception {
+ String retString = "";
+
+ try{
+ RNoteBookCredentials notebookCredentials = (RNoteBookCredentials) this.getDataAccessService().getDomainObject(RNoteBookCredentials.class, token, new HashMap<String, String>());
+ if (notebookCredentials.getToken() == null || notebookCredentials.getToken().equals("")){
+ throw new RNotebookIntegrationException(RNotebookIntegrationException.ERROR_CODE_TOKEN_INVALID);
+ }
+ Date currDate = new Date();
+ if ((currDate.getTime() - notebookCredentials.getCreatedDate().getTime() > tokenTTL) || (notebookCredentials.getTokenReadDate() != null)){
+ throw new RNotebookIntegrationException(RNotebookIntegrationException.ERROR_CODE_TOKEN_EXPIRED);
+ }
+ ObjectMapper mapper = new ObjectMapper();
+
+ try{
+ EcompUser userInfo = mapper.readValue(notebookCredentials.getUserString(), EcompUser.class);
+ notebookCredentials.setUserInfo(userInfo);
+ } catch(JsonMappingException me){
+ logger.error("error converting string to user. from JSON" + me.getMessage());
+ } catch(JsonParseException pe){
+ logger.error("error converting string to user. from JSON" + pe.getMessage());
+ }
+
+ try{
+ Map<String, String> params = mapper.readValue(notebookCredentials.getParametersString(), HashMap.class);
+ notebookCredentials.setParameters(params);
+ } catch(JsonMappingException me){
+ logger.error("error converting string to parameters. from JSON" + me.getMessage());
+ } catch(JsonParseException pe){
+ logger.error("error converting string to parameters. from JSON" + pe.getMessage());
+ }
+
+ //expiring the token
+ try{
+ notebookCredentials.setTokenReadDate(new Date());
+ this.getDataAccessService().saveDomainObject(notebookCredentials, null);
+ } catch(Exception e){
+ logger.info("Error while expiring the token");
+ logger.error(e.getMessage());
+ throw new Exception();
+ }
+ //notebookCredentials.setUserString(null);
+ retString = mapper.writeValueAsString(notebookCredentials);
+ } catch(RNotebookIntegrationException re){
+ logger.error(re.getMessage());
+ throw re;
+ } catch(Exception e){
+ logger.info("Error while parsing the rcloud notebook credentials");
+ logger.error(e.getMessage());
+ throw new Exception();
+ }
+
+ return retString;
+ }
+
+ @Override
+ public String saveRNotebookCredentials(String notebookId, EcompUser user, Map<String, String> params) throws RNotebookIntegrationException, Exception {
+
+ String token = "";
+ try{
+ token = UUID.randomUUID().toString();
+
+ ObjectMapper mapper = new ObjectMapper();
+ ;
+ RNoteBookCredentials rc = new RNoteBookCredentials();
+ rc.setToken(token);
+ rc.setCreatedDate(new Date());
+ rc.setNotebookID(notebookId);
+ rc.setParametersString(mapper.writeValueAsString(params));
+ rc.setUserString(mapper.writeValueAsString(user));
+
+ this.getDataAccessService().saveDomainObject(rc, null);
+
+ } catch(Exception e){
+ logger.info("Error while parsing the rcloud notebook credentials");
+ logger.error(e.getMessage());
+ throw new Exception();
+ }
+
+ return token;
+ }
+
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.controllers;
+
+import java.io.PrintWriter;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.workflow.domain.WorkflowSchedule;
+import org.onap.portalsdk.workflow.models.Workflow;
+import org.onap.portalsdk.workflow.models.WorkflowLite;
+import org.onap.portalsdk.workflow.services.WorkflowService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * Created by Ikram on 02/15/2016.
+ */
+@Controller
+@RequestMapping("/")
+public class WorkflowController extends RestrictedBaseController {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WorkflowController.class);
+
+ @Autowired
+ private WorkflowService workflowService;
+ // @Autowired
+ // private CronJobService cronJobService;
+
+ @RequestMapping(value = { "workflows/saveCronJob" }, method = RequestMethod.POST)
+ public void saveCronJob(HttpServletRequest request, HttpServletResponse response) throws Exception {
+
+ try {
+ // System.out.println("inside save cron job...");
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+
+ WorkflowSchedule domainCronJobData = new WorkflowSchedule();
+ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
+
+ domainCronJobData.setCronDetails(root.get("cronJobDataObj").get("startDateTime_CRON").textValue());
+ domainCronJobData.setWorkflowKey(root.get("cronJobDataObj").get("workflowKey").textValue());
+ domainCronJobData.setArguments(root.get("cronJobDataObj").get("workflow_arguments").textValue());
+ domainCronJobData.setServerUrl(root.get("cronJobDataObj").get("workflow_server_url").textValue());
+ domainCronJobData
+ .setStartDateTime(dateFormat.parse(root.get("cronJobDataObj").get("startDateTime").textValue()));
+ domainCronJobData
+ .setEndDateTime(dateFormat.parse(root.get("cronJobDataObj").get("endDateTime").textValue()));
+ domainCronJobData.setRecurrence(root.get("cronJobDataObj").get("recurrence").textValue());
+
+ workflowService.saveCronJob(domainCronJobData);
+
+ // response.getWriter().write("hello".toString());
+
+ } catch (Exception e) {
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+
+ }
+
+ }
+
+ @RequestMapping(value = { "workflows/list" }, method = RequestMethod.GET, produces = "application/json")
+ public @ResponseBody String getWorkflowList() {
+ ObjectMapper mapper = new ObjectMapper();
+ List<Workflow> workflows = workflowService.getAllWorkflows();
+ List<WorkflowLite> workflowLites = new ArrayList<WorkflowLite>();
+
+ try {
+
+ for (Workflow workflow : workflows) {
+ WorkflowLite wfl = new WorkflowLite();
+ wfl.setId(workflow.getId());
+ wfl.setName(workflow.getName());
+ wfl.setDescription(workflow.getDescription());
+ wfl.setActive(workflow.getActive() == null ? "" : workflow.getActive().toString());
+ wfl.setCreated(workflow.getCreated() == null ? "" : workflow.getCreated().toString());
+ wfl.setCreatedBy(workflow.getCreatedBy() == null ? ""
+ : workflow.getCreatedBy().getFirstName() + " " + workflow.getCreatedBy().getLastName());
+ wfl.setModifiedBy(workflow.getModifiedBy() == null ? ""
+ : workflow.getModifiedBy().getFirstName() + " " + workflow.getCreatedBy().getLastName());
+ wfl.setLastUpdated(workflow.getLastUpdated() == null ? "" : workflow.getLastUpdated().toString());
+ wfl.setWorkflowKey(workflow.getWorkflowKey());
+ wfl.setRunLink(workflow.getRunLink());
+ wfl.setSuspendLink(workflow.getSuspendLink());
+
+ workflowLites.add(wfl);
+ }
+
+ return mapper.writeValueAsString(workflowLites);
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return "";
+ }
+
+ @RequestMapping(value = "workflows/addWorkflow", method = RequestMethod.POST, consumes = "application/json")
+ public @ResponseBody Workflow addWorkflow(@RequestBody Workflow workflow, HttpServletRequest request,
+ HttpServletResponse response) {
+ String loginId = ((User) (request.getSession().getAttribute("user"))).getLoginId();
+ return workflowService.addWorkflow(workflow, loginId);
+ }
+
+ @RequestMapping(value = "workflows/editWorkflow", method = RequestMethod.POST, consumes = "application/json")
+ public @ResponseBody Workflow editWorkflow(@RequestBody WorkflowLite workflow, HttpServletRequest request,
+ HttpServletResponse response) {
+ String loginId = ((User) (request.getSession().getAttribute("user"))).getLoginId();
+ return workflowService.editWorkflow(workflow, loginId);
+ }
+
+ // @RequestMapping(value = "workflows/removeWorkflow", method =
+ // RequestMethod.DELETE)
+ @RequestMapping(value = { "workflows/removeWorkflow" }, method = RequestMethod.POST, consumes = "application/json")
+ public @ResponseBody void removeWorkflow(@RequestBody Long workflowId, HttpServletRequest request,
+ HttpServletResponse response) {
+
+ // System.out.println("Removing ... " + workflowId);
+
+ workflowService.deleteWorkflow(workflowId);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ PrintWriter out = null;
+ try {
+ request.setCharacterEncoding("UTF-8");
+ out = response.getWriter();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "removeWorkflow failed", e);
+ }
+
+ JSONObject j = new JSONObject("{removed: 123}");
+ out.write(j.toString());
+
+ }
+
+ @RequestMapping(value = "workflows/removeAllWorkflows", method = RequestMethod.DELETE)
+ public @ResponseBody void removeAllWorkflows() {
+ // workflowService.deleteAll();
+ }
+
+ @RequestMapping(value = { "/workflows" }, method = RequestMethod.GET)
+ public ModelAndView getWorkflowPartialPage() {
+ Map<String, Object> model = new HashMap<String, Object>();
+ return new ModelAndView(getViewName(), "workflows", model);
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.dao;
+
+import java.util.List;
+
+import org.onap.portalsdk.workflow.models.Workflow;
+import org.onap.portalsdk.workflow.models.WorkflowLite;
+
+public interface WorkflowDAO {
+ public List<Workflow> getWorkflows();
+ public Workflow save(Workflow workflow, String creatorId);
+ public Workflow edit(WorkflowLite workflow, String creatorId);
+ public void delete(Long workflow);
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.dao;
+
+import java.util.Date;
+import java.util.List;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.workflow.models.Workflow;
+import org.onap.portalsdk.workflow.models.WorkflowLite;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+@Repository
+public class WorkflowDAOImpl implements WorkflowDAO{
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ public Workflow save(Workflow workflow, String creatorId){
+ Session session = this.sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
+
+ try{
+ Query query = session.createQuery("from User where loginId =:loginId");
+ query.setParameter("loginId", creatorId);
+ User creator = (User)(query.list().get(0));
+
+ workflow.setCreatedBy(creator);
+ workflow.setCreated(new Date());
+ }
+ catch(Exception e){
+ e.printStackTrace();
+ }
+
+ long id = (Long) session.save(workflow);
+ Workflow savedWorkflow = (Workflow) session.get(Workflow.class, id);
+ tx.commit();
+ session.close();
+ return savedWorkflow;
+ }
+
+ public List<Workflow> getWorkflows(){
+ Session session = this.sessionFactory.openSession();
+ @SuppressWarnings("unchecked")
+ List<Workflow> workflows = session.createQuery("from Workflow").list();
+ session.close();
+ return workflows;
+ }
+
+ @Override
+ public void delete(Long workflowId) {
+ Session session = this.sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
+ Query query = session.createQuery("delete from Workflow where id =:id");
+ query.setParameter("id", workflowId);
+ query.executeUpdate();
+ tx.commit();
+ session.close();
+ }
+
+ @Override
+ public Workflow edit(WorkflowLite workflowLight, String creatorId) {
+ Session session = this.sessionFactory.openSession();
+ Transaction tx = session.beginTransaction();
+
+ Query query = session.createQuery("from User where loginId =:loginId");
+ query.setParameter("loginId", creatorId);
+ User creator = (User)(query.list().get(0));
+
+ Workflow workflowToModify = (Workflow) session.get(Workflow.class, workflowLight.getId());
+
+ workflowToModify.setActive(workflowLight.getActive().equalsIgnoreCase("true") ? true : false );
+ workflowToModify.setSuspendLink(workflowLight.getSuspendLink());
+ workflowToModify.setRunLink(workflowLight.getRunLink());
+ workflowToModify.setDescription(workflowLight.getDescription());
+ workflowToModify.setWorkflowKey(workflowLight.getWorkflowKey());
+ workflowToModify.setName(workflowLight.getName());
+
+ workflowToModify.setModifiedBy(creator);
+ workflowToModify.setLastUpdated(new Date());
+
+ session.update(workflowToModify);
+ Workflow savedWorkflow = (Workflow) session.get(Workflow.class, workflowLight.getId());
+ tx.commit();
+ session.close();
+ return savedWorkflow;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.domain;
+import java.util.Date;
+
+import org.onap.portalsdk.core.domain.support.DomainVo;
+public class WorkflowSchedule extends DomainVo{
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private Long id;
+ private String serverUrl;
+ private String workflowKey;
+ private String arguments;
+ private String cronDetails;
+ private Date endDateTime;
+ private Date startDateTime;
+ private String recurrence;
+
+ public Long getId() {
+ return id;
+ }
+ public void setId(Long id) {
+ this.id = id;
+ }
+ public String getServerUrl() {
+ return serverUrl;
+ }
+ public void setServerUrl(String serverUrl) {
+ this.serverUrl = serverUrl;
+ }
+ public String getWorkflowKey() {
+ return workflowKey;
+ }
+ public void setWorkflowKey(String workflowKey) {
+ this.workflowKey = workflowKey;
+ }
+ public String getArguments() {
+ return arguments;
+ }
+ public void setArguments(String arguments) {
+ this.arguments = arguments;
+ }
+ public String getCronDetails() {
+ return cronDetails;
+ }
+ public void setCronDetails(String cronDetails) {
+ this.cronDetails = cronDetails;
+ }
+ public Date getEndDateTime() {
+ return endDateTime;
+ }
+ public void setEndDateTime(Date endDateTime) {
+ this.endDateTime = endDateTime;
+ }
+ public Date getStartDateTime() {
+ return startDateTime;
+ }
+ public void setStartDateTime(Date startDateTime) {
+ this.startDateTime = startDateTime;
+ }
+ public String getRecurrence() {
+ return recurrence;
+ }
+ public void setRecurrence(String recurrence) {
+ this.recurrence = recurrence;
+ }
+ public static long getSerialversionuid() {
+ return serialVersionUID;
+ }
+
+
+}
--- /dev/null
+
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.models;
+
+import java.io.Serializable;
+import java.util.Date;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.OneToOne;
+import javax.persistence.Table;
+
+import org.onap.portalsdk.core.domain.User;
+
+@Entity
+@Table(name = "fn_workflow")
+public class Workflow implements Serializable{
+
+ private static final long serialVersionUID = -3155065449938005856L;
+
+ @Id
+ @Column(name = "id")
+ @GeneratedValue
+ private Long id;
+
+ @Column
+ private String name;
+
+ @Column (name = "workflow_key")
+ private String workflowKey;
+
+ @Column
+ private String description;
+
+ @Column(name = "created")
+ private Date created;
+
+ @OneToOne(fetch = FetchType.EAGER)//, cascade = CascadeType.ALL)
+ @JoinColumn(name = "created_by")
+ private User createdBy;
+
+ @Column(name = "modified")
+ private Date lastUpdated;
+
+ @OneToOne(fetch = FetchType.EAGER)//, cascade = CascadeType.ALL)
+ @JoinColumn(name = "modified_by")
+ private User modifiedBy;
+
+ @Column(name = "active_yn")
+ private Boolean active;
+
+ @Column(name = "run_link")
+ private String runLink;
+
+ @Column(name = "suspend_link")
+ private String suspendLink;
+
+ @Column(name = "modified_link")
+ private String modifiedLink;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getRunLink() {
+ return runLink;
+ }
+
+ public void setRunLink(String runLink) {
+ this.runLink = runLink;
+ }
+
+ public String getSuspendLink() {
+ return suspendLink;
+ }
+
+ public void setSuspendLink(String suspendLink) {
+ this.suspendLink = suspendLink;
+ }
+
+ public String getModifiedLink() {
+ return modifiedLink;
+ }
+
+ public void setModifiedLink(String modifiedLink) {
+ this.modifiedLink = modifiedLink;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Date getCreated() {
+ return created;
+ }
+
+ public void setCreated(Date created) {
+ this.created = created;
+ }
+
+ public User getCreatedBy() {
+ return createdBy;
+ }
+
+ public void setCreatedBy(User createdBy) {
+ this.createdBy = createdBy;
+ }
+
+ public Date getLastUpdated() {
+ return lastUpdated;
+ }
+
+ public void setLastUpdated(Date lastUpdated) {
+ this.lastUpdated = lastUpdated;
+ }
+
+ public User getModifiedBy() {
+ return modifiedBy;
+ }
+
+ public void setModifiedBy(User modifiedBy) {
+ this.modifiedBy = modifiedBy;
+ }
+
+ public String getWorkflowKey() {
+ return workflowKey;
+ }
+
+ public void setWorkflowKey(String workflowKey) {
+ this.workflowKey = workflowKey;
+ }
+
+ public Boolean getActive() {
+ return active;
+ }
+
+ public void setActive(Boolean active) {
+ this.active = active;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Workflow other = (Workflow) obj;
+ if (id == null) {
+ if (other.id != null)
+ return false;
+ } else if (!id.equals(other.id))
+ return false;
+ return true;
+ }
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.models;
+
+
+import java.io.Serializable;
+
+public class WorkflowLite implements Serializable{
+
+ private static final long serialVersionUID = -3155065449938005856L;
+
+ private Long id;
+
+ private String name;
+
+ private String workflowKey;
+
+ private String description;
+
+ private String created;
+
+ private String createdBy;
+
+ private String lastUpdated;
+
+ private String modifiedBy;
+
+ private String active;
+
+ private String runLink;
+
+ private String suspendLink;
+
+ private String modifiedLink;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getWorkflowKey() {
+ return workflowKey;
+ }
+
+ public void setWorkflowKey(String workflowKey) {
+ this.workflowKey = workflowKey;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getCreated() {
+ return created;
+ }
+
+ public void setCreated(String created) {
+ this.created = created;
+ }
+
+ public String getCreatedBy() {
+ return createdBy;
+ }
+
+ public void setCreatedBy(String createdBy) {
+ this.createdBy = createdBy;
+ }
+
+ public String getLastUpdated() {
+ return lastUpdated;
+ }
+
+ public void setLastUpdated(String lastUpdated) {
+ this.lastUpdated = lastUpdated;
+ }
+
+ public String getModifiedBy() {
+ return modifiedBy;
+ }
+
+ public void setModifiedBy(String modifiedBy) {
+ this.modifiedBy = modifiedBy;
+ }
+
+ public String getActive() {
+ return active;
+ }
+
+ public void setActive(String active) {
+ this.active = active;
+ }
+
+ public String getRunLink() {
+ return runLink;
+ }
+
+ public void setRunLink(String runLink) {
+ this.runLink = runLink;
+ }
+
+ public String getSuspendLink() {
+ return suspendLink;
+ }
+
+ public void setSuspendLink(String suspendLink) {
+ this.suspendLink = suspendLink;
+ }
+
+ public String getModifiedLink() {
+ return modifiedLink;
+ }
+
+ public void setModifiedLink(String modifiedLink) {
+ this.modifiedLink = modifiedLink;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ WorkflowLite other = (WorkflowLite) obj;
+ if (id == null) {
+ if (other.id != null)
+ return false;
+ } else if (!id.equals(other.id))
+ return false;
+ return true;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.scheduler;
+
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.workflow.services.WorkflowScheduleExecutor;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import org.springframework.scheduling.quartz.QuartzJobBean;
+
+public class WorkFlowScheduleJob extends QuartzJobBean{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WorkFlowScheduleJob.class);
+
+ @Override
+ protected void executeInternal(JobExecutionContext context)
+ throws JobExecutionException {
+
+ String serverUrl = (String)context.getMergedJobDataMap().get("serverUrl");
+ String workflowKey = (String)context.getMergedJobDataMap().get("workflowKey");
+ //String arguments = (String)context.getMergedJobDataMap().get("arguments");
+ logger.info(EELFLoggerDelegate.debugLogger, ("Executing the job for the workflow " + workflowKey));
+ WorkflowScheduleExecutor executor = new WorkflowScheduleExecutor(serverUrl, workflowKey);
+ executor.execute();
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.scheduler;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.quartz.impl.triggers.CronTriggerImpl;
+import org.springframework.context.annotation.DependsOn;
+import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
+import org.springframework.scheduling.quartz.JobDetailFactoryBean;
+import org.springframework.stereotype.Component;
+
+@Component
+@DependsOn({"systemProperties"})
+public class WorkFlowScheduleRegistry{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WorkFlowScheduleRegistry.class);
+
+ public WorkFlowScheduleRegistry() {
+
+ }
+
+ private static final String groupName = "AppGroup";
+ private static final String jobName = "WorkflowScheduleJob";
+ private static final String triggerName = "WorkflowScheduleTrigger";
+
+ // @Autowired
+ // private SystemProperties systemProperties;
+
+ // @Bean
+ public JobDetailFactoryBean jobDetailFactoryBean(Map<String, ?> contextInfoMap) {
+
+ JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
+ jobDetailFactory.setJobClass(WorkFlowScheduleJob.class);
+ jobDetailFactory.setJobDataAsMap(contextInfoMap);
+ jobDetailFactory.setGroup(groupName);
+ jobDetailFactory.setName(jobName + "_" + UUID.randomUUID());
+ jobDetailFactory.afterPropertiesSet();
+ return jobDetailFactory;
+ }
+
+ // @Bean
+ public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetailFactory, Long id,
+ String cronExpression, Date startDateTime, Date enddatetime) throws Exception {
+ CronTriggerFactoryBean cronTriggerFactory = new CronTriggerFactoryBean();
+ cronTriggerFactory.setJobDetail(jobDetailFactory.getObject());
+ cronTriggerFactory.setStartDelay(3000);
+ cronTriggerFactory.setName(triggerName + "_" + id);
+ cronTriggerFactory.setGroup(groupName);
+ logger.debug(EELFLoggerDelegate.debugLogger, (triggerName + " Scheduled: " + cronExpression));
+ cronTriggerFactory.setCronExpression( cronExpression); //"0 * * * * ? *"
+ cronTriggerFactory.afterPropertiesSet();
+
+ final CronTriggerImpl cronTrigger = (CronTriggerImpl) cronTriggerFactory.getObject();
+ cronTrigger.setStartTime(startDateTime == null ? Calendar.getInstance().getTime() : startDateTime);
+ cronTrigger.setEndTime(enddatetime);
+ Date fireAgainTime = cronTrigger.getFireTimeAfter(cronTrigger.getStartTime());
+ if (fireAgainTime == null)
+ throw new Exception("Cron not added as it may not fire again " + " Expr: " + cronExpression + " End Time: "
+ + cronTrigger.getEndTime());
+ return cronTriggerFactory;
+
+ }
+
+ public CronTriggerFactoryBean setUpTrigger(Long wfId, String serverUrl, String workflowKey, String arguments,
+ String startdatetimecron, Date startDateTime, Date enddatetime) throws Exception {
+
+ Map<String, String> contextInfo = new HashMap<String, String>();
+ contextInfo.put("serverUrl", serverUrl);
+ contextInfo.put("workflowKey", workflowKey);
+ contextInfo.put("arguments", arguments);
+ JobDetailFactoryBean jobDetailFactory = jobDetailFactoryBean(contextInfo);
+
+ CronTriggerFactoryBean cronTriggerFactory = cronTriggerFactoryBean(jobDetailFactory, wfId, startdatetimecron, startDateTime, enddatetime);
+
+ logger.debug(EELFLoggerDelegate.debugLogger, (" Job to be Scheduled: " + contextInfo.get("workflowKey")));
+
+ //cronTriggerFactory.
+
+ return cronTriggerFactory;
+ }
+
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.services;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
+import java.nio.charset.Charset;
+
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public class WorkflowScheduleExecutor {
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WorkflowScheduleExecutor.class);
+
+ private String serverURL;
+ private String workflowKey;
+ private String myUrl;
+ private String payload;
+
+ //constructor
+ public WorkflowScheduleExecutor(String serverURL,String workflowKey){
+ this.serverURL = serverURL;
+ this.workflowKey = workflowKey;
+ this.myUrl = this.serverURL + "/engine-rest/process-definition/key/" + this.workflowKey + "/submit-form";;
+ this.payload="{\"variables\":{}}";
+ }
+
+ public static void main(String [] args) throws Exception {
+
+ }
+
+ public void execute() {
+ POST_fromURL(myUrl,payload);
+ }
+
+ public static String get_fromURL(String myURL) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "get_fromURL: Requested URL {}", myURL);
+ StringBuilder sb = new StringBuilder();
+ URLConnection urlConn = null;
+ InputStreamReader in = null;
+ try {
+ URL url = new URL(myURL);
+ urlConn = url.openConnection();
+ if (urlConn != null)
+ urlConn.setReadTimeout(60 * 1000);
+ if (urlConn != null && urlConn.getInputStream() != null) {
+ in = new InputStreamReader(urlConn.getInputStream(),
+ Charset.defaultCharset());
+ BufferedReader bufferedReader = new BufferedReader(in);
+ int cp;
+ while ((cp = bufferedReader.read()) != -1)
+ sb.append((char) cp);
+ bufferedReader.close();
+ in.close();
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "get_fromURL failed", e);
+ throw new RuntimeException("Exception while calling URL:"+ myURL, e);
+ }
+ finally {
+ try {
+ if (in != null)
+ in.close();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "get_fromURL close failed", e);
+ }
+ }
+ return sb.toString();
+ }
+
+
+ public static String POST_fromURL(String myURL, String payload) {
+ String line;
+ StringBuffer jsonString = new StringBuffer();
+ try {
+ URL url = new URL(myURL);
+
+ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+ connection.setDoInput(true);
+ connection.setDoOutput(true);
+ connection.setRequestMethod("POST");
+ connection.setRequestProperty("Accept", "application/json");
+ connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
+ OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
+ writer.write(payload);
+ writer.close();
+ BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
+ while ((line = br.readLine()) != null) {
+ jsonString.append(line);
+ }
+ br.close();
+ connection.disconnect();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "POST_fromURL failed", e);
+ throw new RuntimeException(e.getMessage());
+ }
+ return jsonString.toString();
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.services;
+
+import java.util.List;
+
+import org.onap.portalsdk.workflow.domain.WorkflowSchedule;
+import org.quartz.Trigger;
+import org.springframework.scheduling.quartz.SchedulerFactoryBean;
+
+public interface WorkflowScheduleService {
+ List<WorkflowSchedule> findAll();
+ WorkflowSchedule getWorkflowScheduleByKey(Long key);
+ void saveWorkflowSchedule(WorkflowSchedule ws);
+ public void triggerWorkflowScheduling(SchedulerFactoryBean schedulerBean, WorkflowSchedule ws);
+ public List<Trigger> triggerWorkflowScheduling();
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.services;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.workflow.domain.WorkflowSchedule;
+import org.onap.portalsdk.workflow.scheduler.WorkFlowScheduleRegistry;
+import org.quartz.JobDetail;
+import org.quartz.Trigger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
+import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
+import org.springframework.scheduling.quartz.SchedulerFactoryBean;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+
+
+@Service("workflowScheduleService")
+@Transactional
+
+public class WorkflowScheduleServiceImpl implements WorkflowScheduleService{
+
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WorkflowScheduleServiceImpl.class);
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @Autowired
+ private WorkFlowScheduleRegistry workflowRegistry;
+
+ @Autowired
+ private ApplicationContext appContext;
+
+
+ public List<WorkflowSchedule> findAll() {
+
+ /* List<WorkflowSchedule> allworkflows = getDataAccessService().getList(WorkflowSchedule.class, null);
+ for (WorkflowSchedule ws : allworkflows) {
+
+ System.out.println("Key:"+ws.getWorkflowKey()+" "+"CronDetails:"+ws.getStartdatetimecron());
+ } */
+ @SuppressWarnings("unchecked")
+ List<WorkflowSchedule> list = getDataAccessService().getList(WorkflowSchedule.class, null);
+ return list;
+ }
+
+
+ public void saveWorkflowSchedule(WorkflowSchedule ws){
+
+ getDataAccessService().saveDomainObject(ws, null);
+ logger.info(EELFLoggerDelegate.debugLogger, ("Workflow Scheduled " + ws.getId() + " " + ws.getEndDateTime()));
+ triggerWorkflowScheduling((SchedulerFactoryBean)appContext.getBean(SchedulerFactoryBean.class),ws);
+
+ }
+
+ public void triggerWorkflowScheduling(SchedulerFactoryBean schedulerBean, WorkflowSchedule ws) {
+
+ try {
+ final CronTriggerFactoryBean triggerBean = workflowRegistry.setUpTrigger(ws.getId(), ws.getServerUrl(), ws.getWorkflowKey(),ws.getArguments(),ws.getCronDetails(), ws.getStartDateTime(),ws.getEndDateTime());
+ schedulerBean.getScheduler().scheduleJob((JobDetail)triggerBean.getJobDataMap().get("jobDetail"),triggerBean.getObject());
+ } catch (Exception e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, ("Error scheduling work flow with Id" + ws.getId() + e.getMessage()));
+ }
+
+ }
+
+ public List<Trigger> triggerWorkflowScheduling() {
+
+ Date date = new Date();
+ List<Trigger> triggers = new ArrayList<Trigger>();
+
+ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+
+ if (getDataAccessService() != null) {
+ @SuppressWarnings("unchecked")
+ List<WorkflowSchedule> allWorkflows = getDataAccessService()
+ .executeQuery("From WorkflowSchedule where endDateTime > '" + dateFormat.format(date) + "'", null);
+
+ for (WorkflowSchedule ws : allWorkflows) {
+ logger.info(EELFLoggerDelegate.debugLogger, ("Workflow Scheduled " + ws.getId() + "/ End Time: " + ws.getEndDateTime()));
+
+ try {
+
+ final CronTriggerFactoryBean triggerBean = workflowRegistry.setUpTrigger(ws.getId(), ws.getServerUrl(), ws.getWorkflowKey(),ws.getArguments(), ws.getCronDetails(), ws.getStartDateTime(),ws.getEndDateTime());
+
+ triggers.add(triggerBean.getObject());
+
+ //schedulerBean.getScheduler().scheduleJob(trigger);
+
+
+ } catch (Exception e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, ("Error scheduling work flow with Id" + ws.getId() + e.getMessage()));
+ }
+
+
+ }
+ }
+
+ return triggers;
+ }
+
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ @Override
+ public WorkflowSchedule getWorkflowScheduleByKey(Long key) {
+ return (WorkflowSchedule)(getDataAccessService().getDomainObject(WorkflowSchedule.class, key, null));
+ }
+}
+
+
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.services;
+
+import java.util.List;
+
+import org.onap.portalsdk.workflow.domain.WorkflowSchedule;
+import org.onap.portalsdk.workflow.models.Workflow;
+import org.onap.portalsdk.workflow.models.WorkflowLite;
+
+public interface WorkflowService {
+ public void saveCronJob(WorkflowSchedule domainCronJobData);
+
+ public Workflow addWorkflow(Workflow workflow, String creatorId);
+
+ public Workflow editWorkflow(WorkflowLite worklow, String creatorId);
+
+ public void deleteWorkflow(Long worklow);
+
+ public List<Workflow> getAllWorkflows();
+}
--- /dev/null
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal SDK
+ * ===================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the “License”);
+ * you may not use this software 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.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * 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.
+ *
+ * ============LICENSE_END============================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+package org.onap.portalsdk.workflow.services;
+
+import java.util.List;
+
+import org.onap.portalsdk.workflow.dao.WorkflowDAO;
+import org.onap.portalsdk.workflow.domain.WorkflowSchedule;
+import org.onap.portalsdk.workflow.models.Workflow;
+import org.onap.portalsdk.workflow.models.WorkflowLite;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+
+@Service("workflowService")
+public class WorkflowServiceImpl implements WorkflowService {
+
+ @Autowired
+ private WorkflowDAO workflowDAO;
+
+ //@Autowired
+ //private DataAccessService dataAccessService;
+
+ @Autowired
+ private WorkflowScheduleService workflowScheduleService;
+
+ @Override
+ public void saveCronJob(WorkflowSchedule domainCronJobData) {
+ // TODO Auto-generated method stub
+ workflowScheduleService.saveWorkflowSchedule(domainCronJobData);
+/* triggerWorkflowScheduling((SchedulerFactoryBean)appContext.getBean(SchedulerFactoryBean.class),domainCronJobData);
+*/ }
+
+ /*
+ private DataAccessService getDataAccessService() {
+ // TODO Auto-generated method stub
+ return dataAccessService;
+ }
+ */
+
+ @Override
+ public Workflow addWorkflow(Workflow workflow, String creatorId) {
+ return workflowDAO.save(workflow, creatorId);
+ }
+
+ @Override
+ public Workflow editWorkflow(WorkflowLite workflow, String creatorId) {
+ return workflowDAO.edit(workflow, creatorId);
+ }
+
+ @Override
+ public void deleteWorkflow(Long workflowId) {
+ workflowDAO.delete(workflowId);
+ }
+
+ @Override
+ public List<Workflow> getAllWorkflows() {
+ return workflowDAO.getWorkflows();
+ }
+}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.rnotebookintegration.controller;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.UserProfileService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-@Controller
-@RequestMapping("/")
-public class NotebookController extends RestrictedBaseController{
- @Autowired
- UserProfileService service;
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(NotebookController.class);
-
- @RequestMapping(value = {"/notebook" }, method = RequestMethod.GET)
- public ModelAndView noteBook(HttpServletRequest request) {
-
- try {
-
- } catch (Exception e) {
-
-
- }
- return new ModelAndView(getViewName());
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.rnotebookintegration.controller;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.UserProfileService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.servlet.ModelAndView;
-
-@Controller
-@RequestMapping("/")
-public class NotebookTestController extends RestrictedBaseController{
- @Autowired
- UserProfileService service;
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(NotebookTestController.class);
-
- @RequestMapping(value = {"/nbooktest" }, method = RequestMethod.GET)
- public ModelAndView noteBook(HttpServletRequest request) {
-
- try {
-
- } catch (Exception e) {
-
-
- }
- return new ModelAndView(getViewName());
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.rnotebookintegration.controller;
-
-import java.util.HashMap;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.hibernate.validator.internal.util.privilegedactions.GetMethodFromPropertyName;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.controller.RestrictedRESTfulBaseController;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.JsonMessage;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.openecomp.portalsdk.rnotebookintegration.exception.RNotebookIntegrationException;
-import org.openecomp.portalsdk.rnotebookintegration.service.RNoteBookIntegrationService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Controller
-@RequestMapping("/rNotebook/")
-
-public class RNoteBookController extends RestrictedRESTfulBaseController {
-
- @Autowired
- private RNoteBookIntegrationService rNoteBookIntegrationService;
-
-
-
- public RNoteBookIntegrationService getrNoteBookIntegrationService() {
- return rNoteBookIntegrationService;
- }
-
-
-
- public void setrNoteBookIntegrationService(
- RNoteBookIntegrationService rNoteBookIntegrationService) {
- this.rNoteBookIntegrationService = rNoteBookIntegrationService;
- }
-
-
-
- @RequestMapping(value = { "authCr" }, method = RequestMethod.GET, produces = "application/json")
- public @ResponseBody ResponseEntity<String> getRNotebookCredentials (String token) throws Exception {
- //ObjectMapper mapper = new ObjectMapper();
- //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- //JsonNode root = mapper.readTree(request.getReader());
- //String token = root.get("authenticationToken").textValue();
-
- String returnJSON = "";
- try{
- returnJSON = this.getrNoteBookIntegrationService().getRNotebookCredentials(token);
- } catch(RNotebookIntegrationException re){
- if (re.getErrorCode().equals(RNotebookIntegrationException.ERROR_CODE_TOKEN_EXPIRED)){
- return new ResponseEntity<String>(JsonMessage.buildJsonResponse(false, re.getMessage()), HttpStatus.BAD_REQUEST);
- }
- else {
- return new ResponseEntity<String>(JsonMessage.buildJsonResponse(false, re.getMessage()), HttpStatus.BAD_REQUEST);
- }
- }
- catch (Exception e){
- return new ResponseEntity<String>(JsonMessage.buildJsonResponse(false, e.getMessage()), HttpStatus.BAD_REQUEST);
- }
-
- return new ResponseEntity<String>(returnJSON, HttpStatus.OK);
-
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.rnotebookintegration.controller;
-
-import java.util.HashMap;
-import java.util.Iterator;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.openecomp.portalsdk.rnotebookintegration.exception.RNotebookIntegrationException;
-import org.openecomp.portalsdk.rnotebookintegration.service.RNoteBookIntegrationService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-@Controller
-@RequestMapping("/rNotebookFE/")
-public class RNoteBookFEController extends RestrictedBaseController {
- @Autowired
- private RNoteBookIntegrationService rNoteBookIntegrationService;
-
-
-
- public RNoteBookIntegrationService getrNoteBookIntegrationService() {
- return rNoteBookIntegrationService;
- }
-
-
-
- public void setrNoteBookIntegrationService(
- RNoteBookIntegrationService rNoteBookIntegrationService) {
- this.rNoteBookIntegrationService = rNoteBookIntegrationService;
- }
-
- @RequestMapping(value = { "authCr" }, method = RequestMethod.POST, produces = "application/json")
- public @ResponseBody ResponseEntity<String> saveRNotebookCredentials (@RequestBody String notebookId, HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- //ObjectMapper mapper = new ObjectMapper();
- //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- //JsonNode root = mapper.readTree(request.getReader());
- //String token = root.get("authenticationToken").textValue();
- System.out.println("Notebook id "+notebookId);
- System.out.println("Query parameters "+request.getParameter("qparams"));
- String retUrl = "";
- try{
-
- User user = UserUtils.getUserSession(request);
- user = (User) this.getDataAccessService().getDomainObject(User.class, user.getId(), null);
-
- EcompUser ecUser =UserUtils.convertToEcompUser(user);
-
- HashMap<String, String> map = new HashMap<String, String>();
- JSONObject jObject = new JSONObject(request.getParameter("qparams"));
- Iterator<?> keys = jObject.keys();
-
- while( keys.hasNext() ){
- String key = (String)keys.next();
- String value = jObject.getString(key);
- map.put(key, value);
-
- }
-
- System.out.println("json : "+jObject);
- System.out.println("map : "+map);
-
- // String token = this.getrNoteBookIntegrationService().saveRNotebookCredentials(notebookId, ecUser, new HashMap<String, String>());
- String token = this.getrNoteBookIntegrationService().saveRNotebookCredentials(notebookId, ecUser, map);
-
- String guard = SystemProperties.getProperty("guard_notebook_url");
-
- retUrl = guard + "id=" + token;
-
-
- } catch (RNotebookIntegrationException re){
- return new ResponseEntity<String>(re.getMessage(), HttpStatus.BAD_REQUEST);
- } catch (Exception e){
- return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
- }
-
- return new ResponseEntity<String>(retUrl, HttpStatus.OK);
-
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.rnotebookintegration.domain;
-
-import java.util.Date;
-import java.util.Map;
-
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-
-import com.fasterxml.jackson.annotation.JsonIgnore;
-
-public class RNoteBookCredentials extends DomainVo {
- private EcompUser userInfo;
- private String token;
- private Date createdDate;
- private String notebookID;
- private Map<String, String> parameters;
- private Date tokenReadDate;
- @JsonIgnore
- private String userString;
- @JsonIgnore
- private String parametersString;
-
- public String getToken() {
- return token;
- }
- public void setToken(String token) {
- this.token = token;
- }
- public Date getCreatedDate() {
- return createdDate;
- }
- public void setCreatedDate(Date createdDate) {
- this.createdDate = createdDate;
- }
- public String getNotebookID() {
- return notebookID;
- }
- public EcompUser getUserInfo() {
- return userInfo;
- }
- public void setUserInfo(EcompUser userInfo) {
- this.userInfo = userInfo;
- }
- public void setNotebookID(String notebookID) {
- this.notebookID = notebookID;
- }
- public String getUserString() {
- return userString;
- }
- public void setUserString(String userString) {
- this.userString = userString;
- }
- public Map<String, String> getParameters() {
- return parameters;
- }
- public void setParameters(Map<String, String> parameters) {
- this.parameters = parameters;
- }
- public String getParametersString() {
- return parametersString;
- }
- public void setParametersString(String parametersString) {
- this.parametersString = parametersString;
- }
- public Date getTokenReadDate() {
- return tokenReadDate;
- }
- public void setTokenReadDate(Date tokenReadDate) {
- this.tokenReadDate = tokenReadDate;
- }
-
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.rnotebookintegration.exception;
-
-public class RNotebookIntegrationException extends Exception {
- public static final String ERROR_CODE_TOKEN_EXPIRED = "ERROR_CODE_TOKEN_EXPIRED";
- public static final String ERROR_CODE_TOKEN_INVALID = "ERROR_CODE_TOKEN_INVALID";
-
- String errorCode;
-
- public RNotebookIntegrationException(String errorCodeStr){
- super(errorCodeStr);
- this.errorCode = errorCodeStr;
- }
-
- public String getErrorCode() {
- return errorCode;
- }
-
- public void setErrorCode(String errorCode) {
- this.errorCode = errorCode;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.rnotebookintegration.service;
-
-import java.util.Map;
-
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-import org.openecomp.portalsdk.rnotebookintegration.exception.RNotebookIntegrationException;
-
-public interface RNoteBookIntegrationService {
- public String getRNotebookCredentials(String token) throws RNotebookIntegrationException, Exception;
-
- public String saveRNotebookCredentials(String notebookId, EcompUser user, Map<String, String> params) throws RNotebookIntegrationException, Exception;
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.rnotebookintegration.service;
-
-import java.security.SecureRandom;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.restful.domain.EcompUser;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.openecomp.portalsdk.rnotebookintegration.domain.RNoteBookCredentials;
-import org.openecomp.portalsdk.rnotebookintegration.exception.RNotebookIntegrationException;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Service("RNoteBookIntegrationService")
-@Transactional
-public class RNoteBookIntegrationServiceImpl implements RNoteBookIntegrationService {
-
- private final long tokenTTL = 50000L;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RNoteBookIntegrationServiceImpl.class);
-
-
- @Autowired
- private DataAccessService dataAccessService;
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- @Override
- public String getRNotebookCredentials(String token) throws RNotebookIntegrationException, Exception {
- String retString = "";
-
- try{
- RNoteBookCredentials notebookCredentials = (RNoteBookCredentials) this.getDataAccessService().getDomainObject(RNoteBookCredentials.class, token, new HashMap<String, String>());
- if (notebookCredentials.getToken() == null || notebookCredentials.getToken().equals("")){
- throw new RNotebookIntegrationException(RNotebookIntegrationException.ERROR_CODE_TOKEN_INVALID);
- }
- Date currDate = new Date();
- if ((currDate.getTime() - notebookCredentials.getCreatedDate().getTime() > tokenTTL) || (notebookCredentials.getTokenReadDate() != null)){
- throw new RNotebookIntegrationException(RNotebookIntegrationException.ERROR_CODE_TOKEN_EXPIRED);
- }
- ObjectMapper mapper = new ObjectMapper();
-
- try{
- EcompUser userInfo = mapper.readValue(notebookCredentials.getUserString(), EcompUser.class);
- notebookCredentials.setUserInfo(userInfo);
- } catch(JsonMappingException me){
- logger.error("error converting string to user. from JSON" + me.getMessage());
- } catch(JsonParseException pe){
- logger.error("error converting string to user. from JSON" + pe.getMessage());
- }
-
- try{
- Map<String, String> params = mapper.readValue(notebookCredentials.getParametersString(), HashMap.class);
- notebookCredentials.setParameters(params);
- } catch(JsonMappingException me){
- logger.error("error converting string to parameters. from JSON" + me.getMessage());
- } catch(JsonParseException pe){
- logger.error("error converting string to parameters. from JSON" + pe.getMessage());
- }
-
- //expiring the token
- try{
- notebookCredentials.setTokenReadDate(new Date());
- this.getDataAccessService().saveDomainObject(notebookCredentials, null);
- } catch(Exception e){
- logger.info("Error while expiring the token");
- logger.error(e.getMessage());
- throw new Exception();
- }
- //notebookCredentials.setUserString(null);
- retString = mapper.writeValueAsString(notebookCredentials);
- } catch(RNotebookIntegrationException re){
- logger.error(re.getMessage());
- throw re;
- } catch(Exception e){
- logger.info("Error while parsing the rcloud notebook credentials");
- logger.error(e.getMessage());
- throw new Exception();
- }
-
- return retString;
- }
-
- @Override
- public String saveRNotebookCredentials(String notebookId, EcompUser user, Map<String, String> params) throws RNotebookIntegrationException, Exception {
-
- String token = "";
- try{
- token = UUID.randomUUID().toString();
-
- ObjectMapper mapper = new ObjectMapper();
- ;
- RNoteBookCredentials rc = new RNoteBookCredentials();
- rc.setToken(token);
- rc.setCreatedDate(new Date());
- rc.setNotebookID(notebookId);
- rc.setParametersString(mapper.writeValueAsString(params));
- rc.setUserString(mapper.writeValueAsString(user));
-
- this.getDataAccessService().saveDomainObject(rc, null);
-
- } catch(Exception e){
- logger.info("Error while parsing the rcloud notebook credentials");
- logger.error(e.getMessage());
- throw new Exception();
- }
-
- return token;
- }
-
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.workflow.controllers;
-
-import java.io.PrintWriter;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.json.JSONObject;
-import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.workflow.domain.WorkflowSchedule;
-import org.openecomp.portalsdk.workflow.models.Workflow;
-import org.openecomp.portalsdk.workflow.models.WorkflowLite;
-import org.openecomp.portalsdk.workflow.services.WorkflowService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-import org.springframework.web.servlet.ModelAndView;
-
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-/**
- * Created by Ikram on 02/15/2016.
- */
-@Controller
-@RequestMapping("/")
-public class WorkflowController extends RestrictedBaseController {
-
- @Autowired
- private WorkflowService workflowService;
- // @Autowired
- // private CronJobService cronJobService;
-
- @RequestMapping(value = { "workflows/saveCronJob" }, method = RequestMethod.POST)
- public void saveCronJob(HttpServletRequest request, HttpServletResponse response) throws Exception {
-
- try {
- // System.out.println("inside save cron job...");
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
-
- WorkflowSchedule domainCronJobData = new WorkflowSchedule();
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
-
- domainCronJobData.setCronDetails(root.get("cronJobDataObj").get("startDateTime_CRON").textValue());
- domainCronJobData.setWorkflowKey(root.get("cronJobDataObj").get("workflowKey").textValue());
- domainCronJobData.setArguments(root.get("cronJobDataObj").get("workflow_arguments").textValue());
- domainCronJobData.setServerUrl(root.get("cronJobDataObj").get("workflow_server_url").textValue());
- domainCronJobData
- .setStartDateTime(dateFormat.parse(root.get("cronJobDataObj").get("startDateTime").textValue()));
- domainCronJobData
- .setEndDateTime(dateFormat.parse(root.get("cronJobDataObj").get("endDateTime").textValue()));
- domainCronJobData.setRecurrence(root.get("cronJobDataObj").get("recurrence").textValue());
-
- workflowService.saveCronJob(domainCronJobData);
-
- // response.getWriter().write("hello".toString());
-
- } catch (Exception e) {
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
-
- }
-
- }
-
- @RequestMapping(value = { "workflows/list" }, method = RequestMethod.GET, produces = "application/json")
- public @ResponseBody String getWorkflowList() {
- ObjectMapper mapper = new ObjectMapper();
- List<Workflow> workflows = workflowService.getAllWorkflows();
- List<WorkflowLite> workflowLites = new ArrayList<WorkflowLite>();
-
- try {
-
- for (Workflow workflow : workflows) {
- WorkflowLite wfl = new WorkflowLite();
- wfl.setId(workflow.getId());
- wfl.setName(workflow.getName());
- wfl.setDescription(workflow.getDescription());
- wfl.setActive(workflow.getActive() == null ? "" : workflow.getActive().toString());
- wfl.setCreated(workflow.getCreated() == null ? "" : workflow.getCreated().toString());
- wfl.setCreatedBy(workflow.getCreatedBy() == null ? ""
- : workflow.getCreatedBy().getFirstName() + " " + workflow.getCreatedBy().getLastName());
- wfl.setModifiedBy(workflow.getModifiedBy() == null ? ""
- : workflow.getModifiedBy().getFirstName() + " " + workflow.getCreatedBy().getLastName());
- wfl.setLastUpdated(workflow.getLastUpdated() == null ? "" : workflow.getLastUpdated().toString());
- wfl.setWorkflowKey(workflow.getWorkflowKey());
- wfl.setRunLink(workflow.getRunLink());
- wfl.setSuspendLink(workflow.getSuspendLink());
-
- workflowLites.add(wfl);
- }
-
- return mapper.writeValueAsString(workflowLites);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return "";
- }
-
- @RequestMapping(value = "workflows/addWorkflow", method = RequestMethod.POST, consumes = "application/json")
- public @ResponseBody Workflow addWorkflow(@RequestBody Workflow workflow, HttpServletRequest request,
- HttpServletResponse response) {
- String loginId = ((User) (request.getSession().getAttribute("user"))).getLoginId();
- return workflowService.addWorkflow(workflow, loginId);
- }
-
- @RequestMapping(value = "workflows/editWorkflow", method = RequestMethod.POST, consumes = "application/json")
- public @ResponseBody Workflow editWorkflow(@RequestBody WorkflowLite workflow, HttpServletRequest request,
- HttpServletResponse response) {
- String loginId = ((User) (request.getSession().getAttribute("user"))).getLoginId();
- return workflowService.editWorkflow(workflow, loginId);
- }
-
- // @RequestMapping(value = "workflows/removeWorkflow", method =
- // RequestMethod.DELETE)
- @RequestMapping(value = { "workflows/removeWorkflow" }, method = RequestMethod.POST, consumes = "application/json")
- public @ResponseBody void removeWorkflow(@RequestBody Long workflowId, HttpServletRequest request,
- HttpServletResponse response) {
-
- // System.out.println("Removing ... " + workflowId);
-
- workflowService.deleteWorkflow(workflowId);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- PrintWriter out = null;
- try {
- request.setCharacterEncoding("UTF-8");
- out = response.getWriter();
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- JSONObject j = new JSONObject("{removed: 123}");
- out.write(j.toString());
-
- }
-
- @RequestMapping(value = "workflows/removeAllWorkflows", method = RequestMethod.DELETE)
- public @ResponseBody void removeAllWorkflows() {
- // workflowService.deleteAll();
- }
-
- @RequestMapping(value = { "/workflows" }, method = RequestMethod.GET)
- public ModelAndView getWorkflowPartialPage() {
- Map<String, Object> model = new HashMap<String, Object>();
- return new ModelAndView(getViewName(), "workflows", model);
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.workflow.dao;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.workflow.models.Workflow;
-import org.openecomp.portalsdk.workflow.models.WorkflowLite;
-
-public interface WorkflowDAO {
- public List<Workflow> getWorkflows();
- public Workflow save(Workflow workflow, String creatorId);
- public Workflow edit(WorkflowLite workflow, String creatorId);
- public void delete(Long workflow);
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.workflow.dao;
-
-import java.util.Date;
-import java.util.List;
-
-import org.hibernate.Query;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.Transaction;
-import org.openecomp.portalsdk.core.domain.User;
-import org.openecomp.portalsdk.workflow.models.Workflow;
-import org.openecomp.portalsdk.workflow.models.WorkflowLite;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Repository;
-@Repository
-public class WorkflowDAOImpl implements WorkflowDAO{
-
- @Autowired
- private SessionFactory sessionFactory;
-
- public Workflow save(Workflow workflow, String creatorId){
- Session session = this.sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
-
- try{
- Query query = session.createQuery("from User where loginId =:loginId");
- query.setParameter("loginId", creatorId);
- User creator = (User)(query.list().get(0));
-
- workflow.setCreatedBy(creator);
- workflow.setCreated(new Date());
- }
- catch(Exception e){
- e.printStackTrace();
- }
-
- long id = (Long) session.save(workflow);
- Workflow savedWorkflow = (Workflow) session.get(Workflow.class, id);
- tx.commit();
- session.close();
- return savedWorkflow;
- }
-
- public List<Workflow> getWorkflows(){
- Session session = this.sessionFactory.openSession();
- @SuppressWarnings("unchecked")
- List<Workflow> workflows = session.createQuery("from Workflow").list();
- session.close();
- return workflows;
- }
-
- @Override
- public void delete(Long workflowId) {
- Session session = this.sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- Query query = session.createQuery("delete from Workflow where id =:id");
- query.setParameter("id", workflowId);
- query.executeUpdate();
- tx.commit();
- session.close();
- }
-
- @Override
- public Workflow edit(WorkflowLite workflowLight, String creatorId) {
- Session session = this.sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
-
- Query query = session.createQuery("from User where loginId =:loginId");
- query.setParameter("loginId", creatorId);
- User creator = (User)(query.list().get(0));
-
- Workflow workflowToModify = (Workflow) session.get(Workflow.class, workflowLight.getId());
-
- workflowToModify.setActive(workflowLight.getActive().equalsIgnoreCase("true") ? true : false );
- workflowToModify.setSuspendLink(workflowLight.getSuspendLink());
- workflowToModify.setRunLink(workflowLight.getRunLink());
- workflowToModify.setDescription(workflowLight.getDescription());
- workflowToModify.setWorkflowKey(workflowLight.getWorkflowKey());
- workflowToModify.setName(workflowLight.getName());
-
- workflowToModify.setModifiedBy(creator);
- workflowToModify.setLastUpdated(new Date());
-
- session.update(workflowToModify);
- Workflow savedWorkflow = (Workflow) session.get(Workflow.class, workflowLight.getId());
- tx.commit();
- session.close();
- return savedWorkflow;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.workflow.domain;
-import java.util.Date;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-public class WorkflowSchedule extends DomainVo{
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private Long id;
- private String serverUrl;
- private String workflowKey;
- private String arguments;
- private String cronDetails;
- private Date endDateTime;
- private Date startDateTime;
- private String recurrence;
-
- public Long getId() {
- return id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- public String getServerUrl() {
- return serverUrl;
- }
- public void setServerUrl(String serverUrl) {
- this.serverUrl = serverUrl;
- }
- public String getWorkflowKey() {
- return workflowKey;
- }
- public void setWorkflowKey(String workflowKey) {
- this.workflowKey = workflowKey;
- }
- public String getArguments() {
- return arguments;
- }
- public void setArguments(String arguments) {
- this.arguments = arguments;
- }
- public String getCronDetails() {
- return cronDetails;
- }
- public void setCronDetails(String cronDetails) {
- this.cronDetails = cronDetails;
- }
- public Date getEndDateTime() {
- return endDateTime;
- }
- public void setEndDateTime(Date endDateTime) {
- this.endDateTime = endDateTime;
- }
- public Date getStartDateTime() {
- return startDateTime;
- }
- public void setStartDateTime(Date startDateTime) {
- this.startDateTime = startDateTime;
- }
- public String getRecurrence() {
- return recurrence;
- }
- public void setRecurrence(String recurrence) {
- this.recurrence = recurrence;
- }
- public static long getSerialversionuid() {
- return serialVersionUID;
- }
-
-
-}
+++ /dev/null
-
-/*-
- * ================================================================================
- * 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.workflow.models;
-
-import java.io.Serializable;
-import java.util.Date;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.OneToOne;
-import javax.persistence.Table;
-
-import org.openecomp.portalsdk.core.domain.User;
-
-@Entity
-@Table(name = "fn_workflow")
-public class Workflow implements Serializable{
-
- private static final long serialVersionUID = -3155065449938005856L;
-
- @Id
- @Column(name = "id")
- @GeneratedValue
- private Long id;
-
- @Column
- private String name;
-
- @Column (name = "workflow_key")
- private String workflowKey;
-
- @Column
- private String description;
-
- @Column(name = "created")
- private Date created;
-
- @OneToOne(fetch = FetchType.EAGER)//, cascade = CascadeType.ALL)
- @JoinColumn(name = "created_by")
- private User createdBy;
-
- @Column(name = "modified")
- private Date lastUpdated;
-
- @OneToOne(fetch = FetchType.EAGER)//, cascade = CascadeType.ALL)
- @JoinColumn(name = "modified_by")
- private User modifiedBy;
-
- @Column(name = "active_yn")
- private Boolean active;
-
- @Column(name = "run_link")
- private String runLink;
-
- @Column(name = "suspend_link")
- private String suspendLink;
-
- @Column(name = "modified_link")
- private String modifiedLink;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getRunLink() {
- return runLink;
- }
-
- public void setRunLink(String runLink) {
- this.runLink = runLink;
- }
-
- public String getSuspendLink() {
- return suspendLink;
- }
-
- public void setSuspendLink(String suspendLink) {
- this.suspendLink = suspendLink;
- }
-
- public String getModifiedLink() {
- return modifiedLink;
- }
-
- public void setModifiedLink(String modifiedLink) {
- this.modifiedLink = modifiedLink;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Date getCreated() {
- return created;
- }
-
- public void setCreated(Date created) {
- this.created = created;
- }
-
- public User getCreatedBy() {
- return createdBy;
- }
-
- public void setCreatedBy(User createdBy) {
- this.createdBy = createdBy;
- }
-
- public Date getLastUpdated() {
- return lastUpdated;
- }
-
- public void setLastUpdated(Date lastUpdated) {
- this.lastUpdated = lastUpdated;
- }
-
- public User getModifiedBy() {
- return modifiedBy;
- }
-
- public void setModifiedBy(User modifiedBy) {
- this.modifiedBy = modifiedBy;
- }
-
- public String getWorkflowKey() {
- return workflowKey;
- }
-
- public void setWorkflowKey(String workflowKey) {
- this.workflowKey = workflowKey;
- }
-
- public Boolean getActive() {
- return active;
- }
-
- public void setActive(Boolean active) {
- this.active = active;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((id == null) ? 0 : id.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Workflow other = (Workflow) obj;
- if (id == null) {
- if (other.id != null)
- return false;
- } else if (!id.equals(other.id))
- return false;
- return true;
- }
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.workflow.models;
-
-
-import java.io.Serializable;
-
-public class WorkflowLite implements Serializable{
-
- private static final long serialVersionUID = -3155065449938005856L;
-
- private Long id;
-
- private String name;
-
- private String workflowKey;
-
- private String description;
-
- private String created;
-
- private String createdBy;
-
- private String lastUpdated;
-
- private String modifiedBy;
-
- private String active;
-
- private String runLink;
-
- private String suspendLink;
-
- private String modifiedLink;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getWorkflowKey() {
- return workflowKey;
- }
-
- public void setWorkflowKey(String workflowKey) {
- this.workflowKey = workflowKey;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getCreated() {
- return created;
- }
-
- public void setCreated(String created) {
- this.created = created;
- }
-
- public String getCreatedBy() {
- return createdBy;
- }
-
- public void setCreatedBy(String createdBy) {
- this.createdBy = createdBy;
- }
-
- public String getLastUpdated() {
- return lastUpdated;
- }
-
- public void setLastUpdated(String lastUpdated) {
- this.lastUpdated = lastUpdated;
- }
-
- public String getModifiedBy() {
- return modifiedBy;
- }
-
- public void setModifiedBy(String modifiedBy) {
- this.modifiedBy = modifiedBy;
- }
-
- public String getActive() {
- return active;
- }
-
- public void setActive(String active) {
- this.active = active;
- }
-
- public String getRunLink() {
- return runLink;
- }
-
- public void setRunLink(String runLink) {
- this.runLink = runLink;
- }
-
- public String getSuspendLink() {
- return suspendLink;
- }
-
- public void setSuspendLink(String suspendLink) {
- this.suspendLink = suspendLink;
- }
-
- public String getModifiedLink() {
- return modifiedLink;
- }
-
- public void setModifiedLink(String modifiedLink) {
- this.modifiedLink = modifiedLink;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((id == null) ? 0 : id.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- WorkflowLite other = (WorkflowLite) obj;
- if (id == null) {
- if (other.id != null)
- return false;
- } else if (!id.equals(other.id))
- return false;
- return true;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.workflow.scheduler;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.workflow.services.WorkflowScheduleExecutor;
-import org.quartz.JobExecutionContext;
-import org.quartz.JobExecutionException;
-import org.springframework.scheduling.quartz.QuartzJobBean;
-
-public class WorkFlowScheduleJob extends QuartzJobBean{
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WorkFlowScheduleJob.class);
-
-
- @Override
- protected void executeInternal(JobExecutionContext context)
- throws JobExecutionException {
-
- String serverUrl = (String)context.getMergedJobDataMap().get("serverUrl");
- String workflowKey = (String)context.getMergedJobDataMap().get("workflowKey");
- //String arguments = (String)context.getMergedJobDataMap().get("arguments");
- logger.info(EELFLoggerDelegate.debugLogger, ("Executing the job for the workflow " + workflowKey));
- WorkflowScheduleExecutor executor = new WorkflowScheduleExecutor(serverUrl, workflowKey);
- executor.execute();
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.workflow.scheduler;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.quartz.impl.triggers.CronTriggerImpl;
-import org.springframework.context.annotation.DependsOn;
-import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
-import org.springframework.scheduling.quartz.JobDetailFactoryBean;
-import org.springframework.stereotype.Component;
-
-@Component
-@DependsOn({"systemProperties"})
-public class WorkFlowScheduleRegistry{
-
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WorkFlowScheduleRegistry.class);
-
-
- public WorkFlowScheduleRegistry() {
-
- }
-
- private static final String groupName = "AppGroup";
- private static final String jobName = "WorkflowScheduleJob";
- private static final String triggerName = "WorkflowScheduleTrigger";
-
- // @Autowired
- // private SystemProperties systemProperties;
-
- // @Bean
- public JobDetailFactoryBean jobDetailFactoryBean(Map<String, ?> contextInfoMap) {
-
- JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
- jobDetailFactory.setJobClass(WorkFlowScheduleJob.class);
- jobDetailFactory.setJobDataAsMap(contextInfoMap);
- jobDetailFactory.setGroup(groupName);
- jobDetailFactory.setName(jobName + "_" + UUID.randomUUID());
- jobDetailFactory.afterPropertiesSet();
- return jobDetailFactory;
- }
-
- // @Bean
- public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetailFactory, Long id,
- String cronExpression, Date startDateTime, Date enddatetime) throws Exception {
- CronTriggerFactoryBean cronTriggerFactory = new CronTriggerFactoryBean();
- cronTriggerFactory.setJobDetail(jobDetailFactory.getObject());
- cronTriggerFactory.setStartDelay(3000);
- cronTriggerFactory.setName(triggerName + "_" + id);
- cronTriggerFactory.setGroup(groupName);
- logger.debug(EELFLoggerDelegate.debugLogger, (triggerName + " Scheduled: " + cronExpression));
- cronTriggerFactory.setCronExpression( cronExpression); //"0 * * * * ? *"
- cronTriggerFactory.afterPropertiesSet();
-
- final CronTriggerImpl cronTrigger = (CronTriggerImpl) cronTriggerFactory.getObject();
- cronTrigger.setStartTime(startDateTime == null ? Calendar.getInstance().getTime() : startDateTime);
- cronTrigger.setEndTime(enddatetime);
- Date fireAgainTime = cronTrigger.getFireTimeAfter(cronTrigger.getStartTime());
- if (fireAgainTime == null)
- throw new Exception("Cron not added as it may not fire again " + " Expr: " + cronExpression + " End Time: "
- + cronTrigger.getEndTime());
- return cronTriggerFactory;
-
- }
-
- public CronTriggerFactoryBean setUpTrigger(Long wfId, String serverUrl, String workflowKey, String arguments,
- String startdatetimecron, Date startDateTime, Date enddatetime) throws Exception {
-
- Map<String, String> contextInfo = new HashMap<String, String>();
- contextInfo.put("serverUrl", serverUrl);
- contextInfo.put("workflowKey", workflowKey);
- contextInfo.put("arguments", arguments);
- JobDetailFactoryBean jobDetailFactory = jobDetailFactoryBean(contextInfo);
-
- CronTriggerFactoryBean cronTriggerFactory = cronTriggerFactoryBean(jobDetailFactory, wfId, startdatetimecron, startDateTime, enddatetime);
-
- logger.debug(EELFLoggerDelegate.debugLogger, (" Job to be Scheduled: " + contextInfo.get("workflowKey")));
-
- //cronTriggerFactory.
-
- return cronTriggerFactory;
- }
-
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.workflow.services;
-
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.net.URLConnection;
-import java.nio.charset.Charset;
-
-public class WorkflowScheduleExecutor {
- private String serverURL;
- private String workflowKey;
- private String myUrl;
- private String payload;
-
- //constructor
- public WorkflowScheduleExecutor(String serverURL,String workflowKey){
- this.serverURL = serverURL;
- this.workflowKey = workflowKey;
- this.myUrl = this.serverURL + "/engine-rest/process-definition/key/" + this.workflowKey + "/submit-form";;
- this.payload="{\"variables\":{}}";
- }
-
- public static void main(String [] args) throws Exception {
-
- }
-
- public void execute() {
- POST_fromURL(myUrl,payload);
- }
-
- public static String get_fromURL(String myURL) {
- System.out.println("Requeted URL:" + myURL);
- StringBuilder sb = new StringBuilder();
- URLConnection urlConn = null;
- InputStreamReader in = null;
- try {
- URL url = new URL(myURL);
- urlConn = url.openConnection();
- if (urlConn != null)
- urlConn.setReadTimeout(60 * 1000);
- if (urlConn != null && urlConn.getInputStream() != null) {
- in = new InputStreamReader(urlConn.getInputStream(),
- Charset.defaultCharset());
- BufferedReader bufferedReader = new BufferedReader(in);
- if (bufferedReader != null) {
- int cp;
- while ((cp = bufferedReader.read()) != -1) {
- sb.append((char) cp);
- }
- bufferedReader.close();
- }
- }
- in.close();
- } catch (Exception e) {
- throw new RuntimeException("Exception while calling URL:"+ myURL, e);
- }
- return sb.toString();
- }
-
-
- public static String POST_fromURL(String myURL, String payload) {
- String line;
- StringBuffer jsonString = new StringBuffer();
- try {
- URL url = new URL(myURL);
-
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setDoInput(true);
- connection.setDoOutput(true);
- connection.setRequestMethod("POST");
- connection.setRequestProperty("Accept", "application/json");
- connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
- OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
- writer.write(payload);
- writer.close();
- BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- while ((line = br.readLine()) != null) {
- jsonString.append(line);
- }
- br.close();
- connection.disconnect();
- } catch (Exception e) {
- throw new RuntimeException(e.getMessage());
- }
- return jsonString.toString();
- }
-}
\ No newline at end of file
+++ /dev/null
-/*-
- * ================================================================================
- * 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.workflow.services;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.workflow.domain.WorkflowSchedule;
-import org.quartz.Trigger;
-import org.springframework.scheduling.quartz.SchedulerFactoryBean;
-
-public interface WorkflowScheduleService {
- List<WorkflowSchedule> findAll();
- WorkflowSchedule getWorkflowScheduleByKey(Long key);
- void saveWorkflowSchedule(WorkflowSchedule ws);
- public void triggerWorkflowScheduling(SchedulerFactoryBean schedulerBean, WorkflowSchedule ws);
- public List<Trigger> triggerWorkflowScheduling();
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.workflow.services;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.workflow.domain.WorkflowSchedule;
-import org.openecomp.portalsdk.workflow.scheduler.WorkFlowScheduleRegistry;
-import org.quartz.JobDetail;
-import org.quartz.Trigger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.ApplicationContext;
-import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
-import org.springframework.scheduling.quartz.SchedulerFactoryBean;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-
-
-@Service("workflowScheduleService")
-@Transactional
-
-public class WorkflowScheduleServiceImpl implements WorkflowScheduleService{
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WorkflowScheduleServiceImpl.class);
-
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @Autowired
- private WorkFlowScheduleRegistry workflowRegistry;
-
- @Autowired
- private ApplicationContext appContext;
-
-
- public List<WorkflowSchedule> findAll() {
-
- /* List<WorkflowSchedule> allworkflows = getDataAccessService().getList(WorkflowSchedule.class, null);
- for (WorkflowSchedule ws : allworkflows) {
-
- System.out.println("Key:"+ws.getWorkflowKey()+" "+"CronDetails:"+ws.getStartdatetimecron());
- } */
- @SuppressWarnings("unchecked")
- List<WorkflowSchedule> list = getDataAccessService().getList(WorkflowSchedule.class, null);
- return list;
- }
-
-
- public void saveWorkflowSchedule(WorkflowSchedule ws){
-
- getDataAccessService().saveDomainObject(ws, null);
- logger.info(EELFLoggerDelegate.debugLogger, ("Workflow Scheduled " + ws.getId() + " " + ws.getEndDateTime()));
- triggerWorkflowScheduling((SchedulerFactoryBean)appContext.getBean(SchedulerFactoryBean.class),ws);
-
- }
-
- public void triggerWorkflowScheduling(SchedulerFactoryBean schedulerBean, WorkflowSchedule ws) {
-
- try {
- final CronTriggerFactoryBean triggerBean = workflowRegistry.setUpTrigger(ws.getId(), ws.getServerUrl(), ws.getWorkflowKey(),ws.getArguments(),ws.getCronDetails(), ws.getStartDateTime(),ws.getEndDateTime());
- schedulerBean.getScheduler().scheduleJob((JobDetail)triggerBean.getJobDataMap().get("jobDetail"),triggerBean.getObject());
- } catch (Exception e) {
- logger.debug(EELFLoggerDelegate.debugLogger, ("Error scheduling work flow with Id" + ws.getId() + e.getMessage()));
- }
-
- }
-
- public List<Trigger> triggerWorkflowScheduling() {
-
- Date date = new Date();
- List<Trigger> triggers = new ArrayList<Trigger>();
-
- DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-
- if (getDataAccessService() != null) {
- @SuppressWarnings("unchecked")
- List<WorkflowSchedule> allWorkflows = getDataAccessService()
- .executeQuery("From WorkflowSchedule where endDateTime > '" + dateFormat.format(date) + "'", null);
-
- for (WorkflowSchedule ws : allWorkflows) {
- logger.info(EELFLoggerDelegate.debugLogger, ("Workflow Scheduled " + ws.getId() + "/ End Time: " + ws.getEndDateTime()));
-
- try {
-
- final CronTriggerFactoryBean triggerBean = workflowRegistry.setUpTrigger(ws.getId(), ws.getServerUrl(), ws.getWorkflowKey(),ws.getArguments(), ws.getCronDetails(), ws.getStartDateTime(),ws.getEndDateTime());
-
- triggers.add(triggerBean.getObject());
-
- //schedulerBean.getScheduler().scheduleJob(trigger);
-
-
- } catch (Exception e) {
- logger.debug(EELFLoggerDelegate.debugLogger, ("Error scheduling work flow with Id" + ws.getId() + e.getMessage()));
- }
-
-
- }
- }
-
- return triggers;
- }
-
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- @Override
- public WorkflowSchedule getWorkflowScheduleByKey(Long key) {
- return (WorkflowSchedule)(getDataAccessService().getDomainObject(WorkflowSchedule.class, key, null));
- }
-}
-
-
+++ /dev/null
-package org.openecomp.portalsdk.workflow.services;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.workflow.domain.WorkflowSchedule;
-import org.openecomp.portalsdk.workflow.models.Workflow;
-import org.openecomp.portalsdk.workflow.models.WorkflowLite;
-
-
-public interface WorkflowService {
- public void saveCronJob(WorkflowSchedule domainCronJobData);
- public Workflow addWorkflow(Workflow workflow, String creatorId);
- public Workflow editWorkflow(WorkflowLite worklow, String creatorId);
- public void deleteWorkflow(Long worklow);
- public List<Workflow> getAllWorkflows();
-}
+++ /dev/null
-/*-
- * ================================================================================
- * 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.workflow.services;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.workflow.dao.WorkflowDAO;
-import org.openecomp.portalsdk.workflow.domain.WorkflowSchedule;
-import org.openecomp.portalsdk.workflow.models.Workflow;
-import org.openecomp.portalsdk.workflow.models.WorkflowLite;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-
-@Service("workflowService")
-public class WorkflowServiceImpl implements WorkflowService {
-
- @Autowired
- private WorkflowDAO workflowDAO;
-
- //@Autowired
- //private DataAccessService dataAccessService;
-
- @Autowired
- private WorkflowScheduleService workflowScheduleService;
-
- @Override
- public void saveCronJob(WorkflowSchedule domainCronJobData) {
- // TODO Auto-generated method stub
- workflowScheduleService.saveWorkflowSchedule(domainCronJobData);
-/* triggerWorkflowScheduling((SchedulerFactoryBean)appContext.getBean(SchedulerFactoryBean.class),domainCronJobData);
-*/ }
-
- /*
- private DataAccessService getDataAccessService() {
- // TODO Auto-generated method stub
- return dataAccessService;
- }
- */
-
- @Override
- public Workflow addWorkflow(Workflow workflow, String creatorId) {
- return workflowDAO.save(workflow, creatorId);
- }
-
- @Override
- public Workflow editWorkflow(WorkflowLite workflow, String creatorId) {
- return workflowDAO.edit(workflow, creatorId);
- }
-
- @Override
- public void deleteWorkflow(Long workflowId) {
- workflowDAO.delete(workflowId);
- }
-
- @Override
- public List<Workflow> getAllWorkflows() {
- return workflowDAO.getWorkflows();
- }
-}
<?xml version="1.0"?>
<!--
- ================================================================================
- 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.
+ ============LICENSE_START==========================================
+ ONAP Portal SDK
+ ===================================================================
+ Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ ===================================================================
+
+ Unless otherwise specified, all software contained herein is licensed
+ under the Apache License, Version 2.0 (the “License”);
+ you may not use this software except in compliance with the License.
You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
+
+ 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.
- ================================================================================
+
+ Unless otherwise specified, all documentation contained herein is licensed
+ under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
+ you may not use this documentation except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://creativecommons.org/licenses/by/4.0/
+
+ Unless required by applicable law or agreed to in writing, documentation
+ 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.
+
+ ============LICENSE_END============================================
+
+ ECOMP is a trademark and service mark of AT&T Intellectual Property.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
-<hibernate-mapping package="org.openecomp.portalsdk.rnotebookintegration.domain">
+<hibernate-mapping package="org.onap.portalsdk.rnotebookintegration.domain">
<!-- WorkflowSchedule mapping details -->
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
- <!-- ECOMP Portal SDK Maven parent project -->
+ <!-- Portal SDK Maven parent project -->
<groupId>org.onap.portal.sdk</groupId>
<artifactId>epsdk-project</artifactId>
- <version>1.3.0-SNAPSHOT</version>
+ <version>1.4.0-SNAPSHOT</version>
<packaging>pom</packaging>
- <name>ECOMP Portal SDK Project (parent)</name>
+ <name>ONAP Portal SDK Project (parent)</name>
<url>https://wiki.onap.org/display/DW/Portal</url>
+ <!-- OParent provides license audit, code audit, distribution management,
+ etc.
+ But jenkins build fails, so comment out for now.
+ <parent>
+ <groupId>org.onap.oparent</groupId>
+ <artifactId>oparent</artifactId>
+ <version>0.1.0</version>
+ </parent>
+ -->
+
<modules>
<module>epsdk-fw</module>
<module>epsdk-core</module>
<encoding>UTF-8</encoding>
<springframework.version>4.2.0.RELEASE</springframework.version>
<hibernate.version>4.3.11.Final</hibernate.version>
+ <skiptests>true</skiptests>
<nexusproxy>https://nexus.onap.org</nexusproxy>
<snapshotNexusPath>content/repositories/snapshots/</snapshotNexusPath>
+ <stagingNexusPath>content/repositories/staging/</stagingNexusPath>
<releaseNexusPath>content/repositories/releases/</releaseNexusPath>
</properties>
<repositories>
<repository>
- <!-- Releases repository has ECOMP release artifacts -->
- <id>ecomp-releases</id>
- <name>OpenECOMP - Release Repository</name>
+ <id>releases</id>
+ <name>ONAP - Release Repository</name>
<url>${nexusproxy}/${releaseNexusPath}</url>
</repository>
<repository>
- <!-- Snapshots repository has ECOMP snapshot artifacts -->
- <id>ecomp-snapshots</id>
- <name>OpenECOMP - Snapshot Repository</name>
+ <id>staging</id>
+ <name>ONAP - Staging Repository</name>
+ <url>${nexusproxy}/${stagingNexusPath}</url>
+ </repository>
+ <repository>
+ <id>snapshots</id>
+ <name>ONAP - Snapshot Repository</name>
<url>${nexusproxy}/${snapshotNexusPath}</url>
</repository>
<repository>
- <id>ecomp-public</id>
- <name>ecomp onap public Repository</name>
- <url>https://nexus.onap.org/content/groups/public</url>
+ <id>public</id>
+ <name>ONAP public Repository</name>
+ <url>${nexusproxy}/content/groups/public</url>
</repository>
</repositories>
</profiles>
<build>
+
+ <pluginManagement>
+ <plugins>
+ <!-- Silence Eclipse/m2e complaints about checkstyle plugin brought in by OParent -->
+ <plugin>
+ <groupId>org.eclipse.m2e</groupId>
+ <artifactId>lifecycle-mapping</artifactId>
+ <version>1.0.0</version>
+ <configuration>
+ <lifecycleMappingMetadata>
+ <pluginExecutions>
+ <pluginExecution>
+ <pluginExecutionFilter>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <versionRange>2.17,)</versionRange>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </pluginExecutionFilter>
+ <action>
+ <ignore />
+ </action>
+ </pluginExecution>
+ </pluginExecutions>
+ </lifecycleMappingMetadata>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+
<plugins>
<!-- Compile to Java 1.8 class output format -->
</executions>
</plugin>
+ <plugin>
+ <groupId>org.sonatype.plugins</groupId>
+ <artifactId>nexus-staging-maven-plugin</artifactId>
+ <version>1.6.7</version>
+ <extensions>true</extensions>
+ <configuration>
+ <nexusUrl>${nexusproxy}</nexusUrl>
+ <stagingProfileId>176c31dfe190a</stagingProfileId>
+ <serverId>ecomp-staging</serverId>
+ </configuration>
+ </plugin>
+
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
#
major=1
-minor=1
+minor=4
patch=0
base_version=${major}.${minor}.${patch}