diff options
Diffstat (limited to 'ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion')
22 files changed, 4785 insertions, 0 deletions
diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/AntBuild.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/AntBuild.java new file mode 100644 index 00000000..b5aba1df --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/AntBuild.java @@ -0,0 +1,67 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.analytics.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 diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/AppUtils.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/AppUtils.java new file mode 100644 index 00000000..6ee8e5dc --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/AppUtils.java @@ -0,0 +1,367 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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 diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/DbUtils.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/DbUtils.java new file mode 100644 index 00000000..5232fc74 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/DbUtils.java @@ -0,0 +1,78 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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 diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/RemoteDbUtils.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/RemoteDbUtils.java new file mode 100644 index 00000000..85eda259 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/RemoteDbUtils.java @@ -0,0 +1,57 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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); + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/AdapterSessionFactoryContainer.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/AdapterSessionFactoryContainer.java new file mode 100644 index 00000000..6a70d258 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/AdapterSessionFactoryContainer.java @@ -0,0 +1,39 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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; + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/DateUtils.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/DateUtils.java new file mode 100644 index 00000000..a9ea0979 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/DateUtils.java @@ -0,0 +1,287 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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); + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/FusionAdapter.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/FusionAdapter.java new file mode 100644 index 00000000..4b6c6d78 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/FusionAdapter.java @@ -0,0 +1,121 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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; + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/IdName.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/IdName.java new file mode 100644 index 00000000..c46d6730 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/IdName.java @@ -0,0 +1,67 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.analytics.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 diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/Item.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/Item.java new file mode 100644 index 00000000..71663bc2 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/Item.java @@ -0,0 +1,55 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.analytics.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; + } +} + diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/Lookup.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/Lookup.java new file mode 100644 index 00000000..c77835ed --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/Lookup.java @@ -0,0 +1,85 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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; + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/RaptorAdapter.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/RaptorAdapter.java new file mode 100644 index 00000000..2111935c --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/RaptorAdapter.java @@ -0,0 +1,367 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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; + } + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/SpringContext.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/SpringContext.java new file mode 100644 index 00000000..1d46290a --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/adapter/SpringContext.java @@ -0,0 +1,37 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.analytics.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; + } +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/controller/FileServletController.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/controller/FileServletController.java new file mode 100644 index 00000000..203ee9cc --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/controller/FileServletController.java @@ -0,0 +1,206 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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; + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/CR_Report.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/CR_Report.java new file mode 100644 index 00000000..a35d6ce3 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/CR_Report.java @@ -0,0 +1,307 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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); + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/QuickLink.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/QuickLink.java new file mode 100644 index 00000000..75b2d119 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/QuickLink.java @@ -0,0 +1,61 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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; + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/RaptorSearch.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/RaptorSearch.java new file mode 100644 index 00000000..cb85f368 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/RaptorSearch.java @@ -0,0 +1,188 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.analytics.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; + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/ReportInfo.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/ReportInfo.java new file mode 100644 index 00000000..e11f3bcb --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/domain/ReportInfo.java @@ -0,0 +1,159 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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; + } + + + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/service/RaptorService.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/service/RaptorService.java new file mode 100644 index 00000000..afde57e6 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/service/RaptorService.java @@ -0,0 +1,35 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.analytics.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); +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/service/RaptorServiceImpl.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/service/RaptorServiceImpl.java new file mode 100644 index 00000000..1427a2ea --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/service/RaptorServiceImpl.java @@ -0,0 +1,183 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.analytics.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; + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/web/RaptorController.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/web/RaptorController.java new file mode 100644 index 00000000..4b425ab3 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/web/RaptorController.java @@ -0,0 +1,190 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.analytics.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(); + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/web/RaptorControllerAsync.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/web/RaptorControllerAsync.java new file mode 100644 index 00000000..3afe3522 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/web/RaptorControllerAsync.java @@ -0,0 +1,1752 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.Iterator; +import java.util.List; +import java.util.Map; + +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.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.ReportHandler; +import org.openecomp.portalsdk.analytics.model.definition.ReportDefinition; +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.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.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.FormFieldList; +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.UnRestrictedBaseController; +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 com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.databind.node.ObjectNode; + +@Controller +@RequestMapping("/") +public class RaptorControllerAsync extends UnRestrictedBaseController { + String viewName; + + @RequestMapping(value = { "/raptor.htm" }, method = RequestMethod.GET) + public void RaptorSearch(HttpServletRequest request, HttpServletResponse response) + throws IOException, RaptorException { + // System.out.println("Inside RAPTOR run "); + /* + * 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); + * + * return new ModelAndView(getViewName(), "model", null); + * + * //return new ModelAndView(getViewName(), "model", null); + * //System.out.println("Fill with proper code"); //return null; + */ + 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) { + e.printStackTrace(); + // Log.write("Fatal error [report_download_xlsx.jsp]: + // "+e.getMessage()); + } + } 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.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); + + 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); + // ObjectMapper mapper = new ObjectMapper(); + 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) { + e.printStackTrace(); + 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); + // System.out.println("******Viewname******"+viewName); + } + // return new ModelAndView(getViewName(), "model", null); + } 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 { + //PrintWriter out = response.getWriter(); + 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); + } +/* String jsonInString = ""; + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(listJSON); + } catch (Exception ex) { + ex.printStackTrace(); + } +*/ + 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 { + //PrintWriter out = response.getWriter(); + 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); + } + } + +/* String jsonInString = ""; + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(listJSON); + } catch (Exception ex) { + ex.printStackTrace(); + } + + out.write(jsonInString); +*/ + 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 { + //PrintWriter out = response.getWriter(); + 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); + } + } + } +/* String jsonInString = ""; + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(listJSON); + } catch (Exception ex) { + ex.printStackTrace(); + } + + out.write(jsonInString); +*/ + 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 { + //PrintWriter out = response.getWriter(); + //String jsonInString = ""; + 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."); + +/* 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(messageJSON); + } catch (Exception ex1) { + ex1.printStackTrace(); + } +*/ + } catch (RaptorException e) { + request.setAttribute("error_extra_msg", "While copying report " + reportID); + messageJSON.setMessage("Failed - While copying report " + reportID); + messageJSON.setAnyStacktrace(getStackTrace(e)); +// ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime(); +// errorJSONRuntime.setErrormessage("While copying report " + reportID); +// 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex1) { + ex1.printStackTrace(); + } +*/ + return messageJSON; + } + + return messageJSON; + } + + + @RequestMapping(value = "report/wizard/import_report", method = RequestMethod.POST, consumes="application/json") + public MessageJSON importReport(@RequestBody ImportJSON importJSON, HttpServletRequest request, + HttpServletResponse response) throws IOException, RaptorException { + //PrintWriter out = response.getWriter(); + //String jsonInString = ""; + 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."); + +/* 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(messageJSON); + } catch (Exception ex1) { + ex1.printStackTrace(); + } +*/ + + } 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)); +/* ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime(); + errorJSONRuntime.setErrormessage("Unable to parse XML. Nested error: "); + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex1) { + ex1.printStackTrace(); + } +*/ + return messageJSON; + } + + return messageJSON; + + } + + @RequestMapping(value = "report/wizard/save_formfield_tab_data", method = RequestMethod.POST) + public MessageJSON saveFFTabWiseData(@RequestBody FormEditJSON formEditJSON, HttpServletRequest request, + HttpServletResponse response) throws IOException, RaptorException { + ReportDefinition rdef = null; + rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION); + + String tabId = formEditJSON.getTabId(); + //String errorString = ""; + MessageJSON messageJSON = new MessageJSON(); + + //PrintWriter out = response.getWriter(); + //String jsonInString = ""; + 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 iter = fft.getPredefinedValueList().getPredefinedValue() + .iterator(); iter.hasNext();) + iter.remove(); + } + + List<IdNameBooleanJSON> predefList = formEditJSON.getPredefinedValueList(); + 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."); + +/* 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(messageJSON); + } catch (Exception ex1) { + ex1.printStackTrace(); + } +*/ } else { + messageJSON.setMessage("Report Definition is not in session"); + messageJSON.setAnyStacktrace("Report Definition is not in session"); + +/* 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex1) { + ex1.printStackTrace(); + } +*/ } + } catch (Exception ex) { + + messageJSON.setMessage("Error occured while formfield details Tab"); + messageJSON.setAnyStacktrace(getStackTrace(ex)); + +/* ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime(); + errorJSONRuntime.setErrormessage("Error occured while formfield column details Tab"); + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex1) { + ex1.printStackTrace(); + } +*/ + return messageJSON; + } + + return messageJSON; + } + + @RequestMapping(value = "report/wizard/save_col_tab_data", method = RequestMethod.POST) + public MessageJSON saveColTabWiseData(@RequestBody ColumnEditJSON columnEditJSON, HttpServletRequest request, + HttpServletResponse response) throws IOException, RaptorException { + ReportDefinition rdef = null; + rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION); + + //String errorString = ""; + //String jsonInString = ""; + //PrintWriter out = response.getWriter(); + 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."); + +/* 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(messageJSON); + } catch (Exception ex1) { + ex1.printStackTrace(); + } +*/ + } else { + messageJSON.setMessage("Report Definition is not in session"); + messageJSON.setAnyStacktrace(""); + +/* ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime(); + errorJSONRuntime.setErrormessage("Report Definition is not in session;"); + errorJSONRuntime.setStacktrace(""); + + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex1) { + ex1.printStackTrace(); + } +*/ } + } catch (Exception ex) { + messageJSON.setMessage("Error occured while saving column details Tab"); + messageJSON.setAnyStacktrace(getStackTrace(ex)); + +/* ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime(); + errorJSONRuntime.setErrormessage("Error occured while saving column details Tab"); + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex1) { + ex1.printStackTrace(); + } +*/ + return messageJSON; + } + + return messageJSON; + } + + @RequestMapping(value = "report/wizard/save_def_tab_data/{id}", method = RequestMethod.POST) + public MessageJSON saveDefTabWiseData(@PathVariable("id") String id, @RequestBody DefinitionJSON definitionJSON, + HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException { + ReportDefinition rdef = null; + ReportRuntime rr = null; + String tabId = definitionJSON.getTabId(); + String errorString = ""; + boolean newReport = false; + //String jsonInString = ""; + //PrintWriter out = response.getWriter(); + MessageJSON messageJSON = new MessageJSON(); + + + + /* + * rdef = (ReportDefinition) request.getSession().getAttribute( + * AppConstants.SI_REPORT_DEFINITION); if(rdef!=null) { rdef = (new + * ReportHandler()).loadReportDefinition(request, id); } else { + */ + 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(); + 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()); + } + 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.")); + +/* 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(messageJSON); + } catch (Exception ex1) { + ex1.printStackTrace(); + } +*/ } catch (Exception ex) { + messageJSON.setMessage("Error occured while saving definition Tab"); + messageJSON.setAnyStacktrace(getStackTrace(ex)); + +/* ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime(); + errorJSONRuntime.setErrormessage("Error occured while saving definition Tab"); + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex1) { + ex1.printStackTrace(); + } +*/ + return messageJSON; + } + + return messageJSON; + } + +/* @RequestMapping(value = "report/wizard/save_tab_wise_data/{reportID}", method = RequestMethod.POST) + public void saveTabWiseData(@PathVariable("reportID") String reportID, @RequestBody WizardJSON wizardJSON, + HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException { + ReportDefinition rdef = null; + rdef = (ReportDefinition) request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION); + if (rdef != null) { + rdef = (new ReportHandler()).loadReportDefinition(request, reportID); + } + 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 "); + } + // ReportDefinition rdef = (ReportDefinition) + // request.getSession().getAttribute( + // AppConstants.SI_REPORT_DEFINITION); + String tabId = wizardJSON.getTabId(); + String errorString = ""; + if (rdef != null) { + if (tabId.equals("Def")) { + String reportName = ((DefinitionJSON) wizardJSON).getReportName(); + if (AppUtils.nvl(reportName).length() <= 0) + errorString = "ReportName cannot be null;"; + rdef.setReportName(reportName); + + String reportDescr = ((DefinitionJSON) wizardJSON).getReportDescr(); + rdef.setReportDescr(reportDescr); + + String formHelpText = ((DefinitionJSON) wizardJSON).getFormHelpText(); + rdef.setFormHelpText(formHelpText); + + Integer pageSize = ((DefinitionJSON) wizardJSON).getPageSize(); + rdef.setPageSize(pageSize); + + List<IdNameBooleanJSON> menuIds = ((DefinitionJSON) wizardJSON).getDisplayArea(); + for (IdNameBooleanJSON menuId : menuIds) { + if (menuId.isSelected()) { + rdef.setMenuID(menuId.getName()); + } + + } + + Boolean hideFormFieldsAfterRun = ((DefinitionJSON) wizardJSON).getHideFormFieldsAfterRun(); + rdef.setHideFormFieldAfterRun(hideFormFieldsAfterRun); + Integer maxRowsInExcelCSVDownload = ((DefinitionJSON) wizardJSON).getMaxRowsInExcelCSVDownload(); + rdef.setMaxRowsInExcelDownload(maxRowsInExcelCSVDownload); + Integer frozenColumns = ((DefinitionJSON) wizardJSON).getFrozenColumns(); + rdef.setFrozenColumns(frozenColumns); + String dataGridAlign = ((DefinitionJSON) wizardJSON).getDataGridAlign(); + rdef.setDataGridAlign(dataGridAlign); + String emptyMessage = ((DefinitionJSON) wizardJSON).getEmptyMessage(); + rdef.setEmptyMessage(emptyMessage); + String dataContainerHeight = ((DefinitionJSON) wizardJSON).getDataContainerHeight(); + rdef.setDataContainerHeight(dataContainerHeight); + String dataContainerWidth = ((DefinitionJSON) wizardJSON).getDataContainerWidth(); + rdef.setDataContainerWidth(dataContainerWidth); + boolean runtimeColSortDisabled = ((DefinitionJSON) wizardJSON).getRuntimeColSortDisabled(); + rdef.setRuntimeColSortDisabled(runtimeColSortDisabled); + Integer numFormCols = ((DefinitionJSON) wizardJSON).getNumFormCols(); + rdef.setNumFormCols(Integer.toString(numFormCols)); + String reportTitle = ((DefinitionJSON) wizardJSON).getReportTitle(); + rdef.setReportTitle(reportTitle); + String reportSubTitle = ((DefinitionJSON) wizardJSON).getReportSubTitle(); + rdef.setReportSubTitle(reportSubTitle); + + List<NameBooleanJSON> displayOptions = ((DefinitionJSON) wizardJSON).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()); + + } else if (tabId.equals("ColEdit")) { + String colId = ((ColumnEditJSON) wizardJSON).getColId(); + List<DataColumnType> reportColumnList = rdef.getAllColumns(); + + for (DataColumnType reportColumnType : reportColumnList) { + // columnJSON = new ColumnJSON(); + if (reportColumnType.getColId().equals(colId)) { + reportColumnType.setColName(((ColumnEditJSON) wizardJSON).getColName()); + reportColumnType.setDisplayAlignment(((ColumnEditJSON) wizardJSON).getDisplayAlignment()); + reportColumnType + .setDisplayHeaderAlignment(((ColumnEditJSON) wizardJSON).getDisplayHeaderAlignment()); + reportColumnType.setIsSortable(((ColumnEditJSON) wizardJSON).isSortable()); + reportColumnType.setVisible(((ColumnEditJSON) wizardJSON).isVisible()); + reportColumnType.setDrillDownURL(((ColumnEditJSON) wizardJSON).getDrilldownURL()); + reportColumnType.setDrillDownParams(((ColumnEditJSON) wizardJSON).getDrilldownParams()); + reportColumnType.setDrillDownType(((ColumnEditJSON) wizardJSON).getDrilldownType()); + + } + + } + } else if (tabId.equals("FormEdit")) { + String fieldId = ((FormEditJSON) wizardJSON).getFieldId(); + + if (rdef.getFormFieldList() != null) { + for (FormFieldType fft : rdef.getFormFieldList().getFormField()) { + if (fft.getFieldId().equals(fieldId)) { + fft.setFieldName(((FormEditJSON) wizardJSON).getFieldName()); + fft.setFieldType(((FormEditJSON) wizardJSON).getFieldType()); + fft.setVisible(((FormEditJSON) wizardJSON).isVisible() ? "Y" : "N"); + fft.setDefaultValue(((FormEditJSON) wizardJSON).getDefaultValue()); + fft.setFieldDefaultSQL(((FormEditJSON) wizardJSON).getFieldDefaultSQL()); + fft.setValidationType(((FormEditJSON) wizardJSON).getValidationType()); + + // clear predefined value + if (fft.getPredefinedValueList() != null) { + for (Iterator iter = fft.getPredefinedValueList().getPredefinedValue().iterator(); iter + .hasNext();) + iter.remove(); + } + + List<IdNameBooleanJSON> predefList = ((FormEditJSON) wizardJSON).getPredefinedValueList(); + for (IdNameBooleanJSON item : predefList) { + PredefinedValueList predefinedValueList = new ObjectFactory() + .createPredefinedValueList(); + fft.setPredefinedValueList(predefinedValueList); + fft.getPredefinedValueList().getPredefinedValue().add(item.getId()); + } + + } + } + } + } // formedit + persistReportDefinition(request, rdef); + + String jsonInString = ""; + + ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime(); + errorJSONRuntime.setErrormessage("Success"); + errorJSONRuntime.setStacktrace("Report changed"); + PrintWriter out = response.getWriter(); + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex) { + ex.printStackTrace(); + } + + out.write(jsonInString); + + } + }*/ + + @RequestMapping(value = {"/report/wizard/retrieve_tab_wise_data/{tabId}/{id}", "/report/wizard/retrieve_tab_wise_data/{tabId}/{id}/{detailId}"}, method = RequestMethod.GET) + public @ResponseBody String retrieveTabWiseData( @PathVariable Map<String, String> pathVariables, /*@PathVariable("tabId") String tabId, @PathVariable("id") String id, @PathVariable("detailId") String detailId,*/ + HttpServletRequest request, HttpServletResponse response) throws IOException, RaptorException { + ReportDefinition rdef = null; + ReportRuntime rr = null; + boolean newReport = false; + String jsonInString = ""; + String tabId = ""; + String id = ""; + String detailId = ""; + + if (pathVariables.containsKey("tabId")) { + tabId = pathVariables.get("tabId"); + } + 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 (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); + } 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); + } + WizardJSON wizardJSON = null; + if (tabId.equals("Def")) { + wizardJSON = new DefinitionJSON(); + ((DefinitionJSON) wizardJSON).setTabId("Def"); + ((DefinitionJSON) wizardJSON).setTabName("Definition"); + + ((DefinitionJSON) wizardJSON).setReportId((rdef != null) ? rdef.getReportID() + "" : ""); + ((DefinitionJSON) wizardJSON).setReportName((rdef != null) ? rdef.getReportName() : ""); + ((DefinitionJSON) wizardJSON).setReportDescr((rdef != null) ? rdef.getReportDescr() : ""); + ((DefinitionJSON) wizardJSON).setReportType((rdef != null) ? rdef.getReportType() : AppConstants.RT_LINEAR); + ((DefinitionJSON) wizardJSON).setDbInfo((rdef != null) ? rdef.getDBInfo() : ""); + ((DefinitionJSON) wizardJSON).setFormHelpText((rdef != null) ? rdef.getFormHelpText() : ""); + ((DefinitionJSON) 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); + } + ((DefinitionJSON) wizardJSON).setDisplayArea(displayArea); + ((DefinitionJSON) wizardJSON) + .setHideFormFieldsAfterRun((rdef != null) ? rdef.isHideFormFieldAfterRun() : false); + ((DefinitionJSON) wizardJSON) + .setMaxRowsInExcelCSVDownload((rdef != null) ? rdef.getMaxRowsInExcelDownload() : 500); + ((DefinitionJSON) wizardJSON).setFrozenColumns((rdef != null) ? rdef.getFrozenColumns() : 0); + ((DefinitionJSON) wizardJSON).setDataGridAlign((rdef != null) ? rdef.getDataGridAlign() : "left"); + ((DefinitionJSON) wizardJSON).setEmptyMessage((rdef != null) ? rdef.getEmptyMessage() : "No records found"); + ((DefinitionJSON) wizardJSON) + .setDataContainerHeight((rdef != null) ? rdef.getDataContainerHeight() : "600"); + ((DefinitionJSON) 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); + + ((DefinitionJSON) wizardJSON).setDisplayOptions(displayOptions); + + ((DefinitionJSON) wizardJSON) + .setRuntimeColSortDisabled((rdef != null) ? rdef.isRuntimeColSortDisabled() : false); + ((DefinitionJSON) wizardJSON).setNumFormCols((rdef != null) ? rdef.getNumFormColsAsInt() : 1); + ((DefinitionJSON) wizardJSON).setReportTitle((rdef != null) ? rdef.getReportTitle() : ""); + ((DefinitionJSON) wizardJSON).setReportSubTitle((rdef != null) ? rdef.getReportSubTitle() : ""); + + } else if (tabId.equals("Sql")) { + wizardJSON = new QueryJSON(); + ((QueryJSON) wizardJSON).setTabId("Sql"); + ((QueryJSON) wizardJSON).setTabName("Sql"); + ((QueryJSON) wizardJSON).setQuery(rdef.getReportSQL()); + + } else if (tabId.equals("ColEdit") && rdef != null) { + // wizardJSON = new QueryJSON(); + // ((QueryJSON) + // wizardJSON).setQuery((rdef!=null)?rdef.getReportSQL():""); + wizardJSON = new ColumnEditJSON(); + ((ColumnEditJSON) wizardJSON).setTabId("ColEdit"); + ((ColumnEditJSON) wizardJSON).setTabName("Column Edit"); + + List<DataColumnType> reportColumnList = rdef.getAllColumns(); + + for (DataColumnType reportColumnType : reportColumnList) { + // columnJSON = new ColumnJSON(); + if (reportColumnType.getColId().equals(id)) { + ((ColumnEditJSON) wizardJSON).setColId(reportColumnType.getColId()); + ((ColumnEditJSON) wizardJSON).setColName(reportColumnType.getColName()); + ((ColumnEditJSON) wizardJSON).setDisplayAlignment(reportColumnType.getDisplayAlignment()); + ((ColumnEditJSON) wizardJSON) + .setDisplayHeaderAlignment(reportColumnType.getDisplayHeaderAlignment()); + ((ColumnEditJSON) wizardJSON).setSortable( + reportColumnType.isIsSortable() == null ? false : reportColumnType.isIsSortable()); + ((ColumnEditJSON) wizardJSON).setVisible(reportColumnType.isVisible()); + ((ColumnEditJSON) wizardJSON).setDrilldownURL( + reportColumnType.getDrillDownURL() == null ? "" : reportColumnType.getDrillDownURL()); + ((ColumnEditJSON) wizardJSON).setDrilldownParams( + reportColumnType.getDrillDownParams() == null ? "" : reportColumnType.getDrillDownParams()); + ((ColumnEditJSON) wizardJSON).setDrilldownType( + reportColumnType.getDrillDownType() == null ? "" : reportColumnType.getDrillDownType()); + + } + } + + } else if (tabId.equals("FormEdit") && rdef != null) { + wizardJSON = new FormEditJSON(); + ((FormEditJSON) wizardJSON).setTabId("FormEdit"); + ((FormEditJSON) wizardJSON).setTabName("Form Edit"); + FormFieldType currField = null; + try { + if (id.equals("add")) { + + currField = rdef.addFormFieldType(new ObjectFactory(), "", "", "", "", "", "", "", "", null, null, "", + ""); + ((FormEditJSON) wizardJSON).setFieldId(currField.getFieldId()); + ((FormEditJSON) wizardJSON).setFieldName(currField.getFieldName()); + ((FormEditJSON) wizardJSON).setFieldType(currField.getFieldType()); + ((FormEditJSON) wizardJSON).setVisible(currField.getVisible().toUpperCase().startsWith("Y")); + ((FormEditJSON) wizardJSON).setDefaultValue(currField.getDefaultValue()); + ((FormEditJSON) wizardJSON).setFieldDefaultSQL(currField.getFieldDefaultSQL()); + ((FormEditJSON) wizardJSON).setFieldSQL(currField.getFieldSQL()); + ((FormEditJSON) wizardJSON).setValidationType(currField.getValidationType()); + + } else if (id.equals("delete")) { + rdef.deleteFormField(detailId); + persistReportDefinition(request, rdef); + MessageJSON messageJSON = new MessageJSON(); + messageJSON.setMessage("Formfield " + detailId+ " Deleted"); + messageJSON.setAnyStacktrace("Given formfield deleted"); + + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(messageJSON); + } catch (Exception ex1) { + ex1.printStackTrace(); + } + + + } + if (rdef.getFormFieldList() != null) { + for (FormFieldType fft : rdef.getFormFieldList().getFormField()) { + if (fft.getFieldId().equals(id)) { + ((FormEditJSON) wizardJSON).setFieldId(fft.getFieldId()); + ((FormEditJSON) wizardJSON).setFieldName(fft.getFieldName()); + ((FormEditJSON) wizardJSON).setFieldType(fft.getFieldType()); + ((FormEditJSON) wizardJSON).setVisible(fft.getVisible().toUpperCase().startsWith("Y")); + ((FormEditJSON) wizardJSON).setDefaultValue(fft.getDefaultValue()); + ((FormEditJSON) wizardJSON).setFieldDefaultSQL(fft.getFieldDefaultSQL()); + ((FormEditJSON) wizardJSON).setFieldSQL(fft.getFieldSQL()); + ((FormEditJSON) 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); + } + ((FormEditJSON) wizardJSON).setPredefinedValueList(preDefinedList); + } + } + } + } + } catch (Exception ex) { + ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime(); + errorJSONRuntime.setErrormessage("Error occured while retreiving formedit definition Tab"); + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex1) { + ex1.printStackTrace(); + } + + } + + } + + + //PrintWriter out = response.getWriter(); + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(wizardJSON); + } catch (Exception ex) { + ex.printStackTrace(); + } + return jsonInString; + } + + @RequestMapping(value = "/report/wizard/retrieve_data/{validate}", method = RequestMethod.POST) + public String retrieveDataForGivenQuery(@PathVariable("validate") boolean validate, @RequestBody QueryJSON queryJSON, HttpServletRequest request, + HttpServletResponse response) throws IOException, RaptorException { + String sql = queryJSON.getQuery(); + String jsonInString = ""; + //PrintWriter out = response.getWriter(); + + 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.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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex1) { + ex1.printStackTrace(); + } + } 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.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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex) { + ex.printStackTrace(); + + } + } 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++) { + // 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)); + try { + + response.setContentType("application/json"); + ds = ConnectionUtils.getDataSet(sql, "local", true); + /* + * SimpleModule module = new SimpleModule(); + * module.addSerializer(new ResultSetSerializer()); + * + * ObjectMapper objectMapper = new ObjectMapper(); + * objectMapper.registerModule(module); + * + * ObjectNode objectNode = objectMapper.createObjectNode(); + * objectNode.putPOJO("results", ds); + * + * objectMapper.writeValue(writer, objectNode); + */ + + QueryResultJSON queryResultJSON = new QueryResultJSON(); + queryResultJSON.setQuery(queryJSON.getQuery()); + + 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(rd.reportDataRows.resetNext(); + // rd.reportDataRows.hasNext(); count++) { + for (int r = 0; r < Math.min(ds.getRowCount(), 100); r++) { + dvJSON = new HashMap<String, String>(); + for (int c = 0; c < ds.getColumnCount(); c++) { + // jgen.writeFieldName(columnNames[c]); + // jgen.writeString(ds.getString(r, c)); + try { + dvJSON.put(ds.getColumnName(c), ds.getString(r, c)); + } catch (Exception ex) { + ex.printStackTrace(); + + } + } + reportDataRows.add(dvJSON); + + } + } + + } + queryResultJSON.setReportDataRows(reportDataRows); + 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(queryResultJSON); + } catch (Exception ex) { + ex.printStackTrace(); + + } + + // return queryResultJSON; + + } catch (ReportSQLException ex) { + ex.printStackTrace(); + 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"); + } else { + 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); + + try { + jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime); + } catch (Exception ex1) { + ex1.printStackTrace(); + + } + } + if(validate) { + String query = XSSFilter.filterRequestOnlyScript(queryJSON.getQuery()); + request.setAttribute("sqlValidated", "N"); + rdef.parseReportSQL(query); + request.setAttribute("sqlValidated", "Y"); + persistReportDefinition(request, rdef); + + } + + } + } + return jsonInString; + + } + + @RequestMapping(value = "save_chart", method = RequestMethod.POST) + public void reportChartReceive(@RequestBody ChartJSON chartJSON, HttpServletRequest request, + HttpServletResponse response) throws IOException { + ReportRuntime reportRuntime; + // System.out.println("*****Hit RaptorChart******"); + + // System.out.println("chartJSON"+chartJSON.getRangeAxisList()); + // System.out.println("chartJSON"+chartJSON.getCommonChartOptions().getLegendPosition()); + 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) { + ex.printStackTrace(); + + } + } + + 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; + 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)) { + 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) { + ex.printStackTrace(); + logger.error("While SAVING CHART", 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(); + } + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RaptorControllerAsync.class); + + 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); + } + } + } + +} diff --git a/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/web/ReportsSearchListController.java b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/web/ReportsSearchListController.java new file mode 100644 index 00000000..a84d2174 --- /dev/null +++ b/ecomp-sdk/epsdk-analytics/src/main/java/org/openecomp/portalsdk/analytics/system/fusion/web/ReportsSearchListController.java @@ -0,0 +1,77 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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; + } + +} |