From 8cd208ebaa33627daf05d8ffff7b28e53a7067d0 Mon Sep 17 00:00:00 2001 From: "Christopher Lott (cl778h)" Date: Thu, 7 Sep 2017 08:52:41 -0400 Subject: Adjust code for Sonar issues Made non-functional updates to address static code analysis issues. Update license header with simple double-quote characters. Issue: PORTAL-72, PORTAL-90 Change-Id: Ic2c330daea07d721f0e6b350ebf03da97073f7ce Signed-off-by: Christopher Lott (cl778h) --- .../core/service/AccessConfiguration.java | 4 +- .../onap/portalsdk/core/service/AppService.java | 11 +- .../portalsdk/core/service/AppServiceImpl.java | 37 +- .../onap/portalsdk/core/service/AuditService.java | 10 +- .../portalsdk/core/service/AuditServiceImpl.java | 27 +- .../portalsdk/core/service/BroadcastService.java | 20 +- .../core/service/BroadcastServiceImpl.java | 388 +++++++++++---------- .../core/service/CentralAccessCondition.java | 23 +- .../portalsdk/core/service/DataAccessService.java | 111 +++--- .../core/service/DataAccessServiceImpl.java | 154 ++++---- .../portalsdk/core/service/ElementLinkService.java | 119 ++----- .../portalsdk/core/service/ElementMapService.java | 331 ++++++------------ .../onap/portalsdk/core/service/FnMenuService.java | 4 +- .../portalsdk/core/service/FnMenuServiceImpl.java | 10 +- .../core/service/FunctionalMenuListService.java | 6 +- .../FunctionalMenuListServiceCentralizedImpl.java | 6 +- .../service/FunctionalMenuListServiceImpl.java | 10 +- .../onap/portalsdk/core/service/LdapService.java | 12 +- .../portalsdk/core/service/LdapServiceImpl.java | 384 +++++++++----------- .../core/service/LocalAccessCondition.java | 16 +- .../onap/portalsdk/core/service/LoginService.java | 28 +- .../core/service/LoginServiceCentralizedImpl.java | 81 ++--- .../portalsdk/core/service/LoginServiceImpl.java | 262 +++++++------- .../portalsdk/core/service/PostDroolsService.java | 10 +- .../core/service/PostDroolsServiceImpl.java | 93 ++--- .../portalsdk/core/service/PostSearchService.java | 4 +- .../core/service/PostSearchServiceImpl.java | 4 +- .../portalsdk/core/service/ProfileService.java | 32 +- .../service/ProfileServiceCentralizedImpl.java | 50 +-- .../portalsdk/core/service/ProfileServiceImpl.java | 31 +- .../core/service/RestApiRequestBuilder.java | 41 ++- .../onap/portalsdk/core/service/RoleService.java | 107 +++--- .../core/service/RoleServiceCentralizedAccess.java | 79 ++--- .../portalsdk/core/service/RoleServiceImpl.java | 50 +-- .../onap/portalsdk/core/service/UrlAccessImpl.java | 9 +- .../portalsdk/core/service/UrlAccessService.java | 8 +- .../portalsdk/core/service/UserProfileService.java | 9 +- .../core/service/UserProfileServiceImpl.java | 77 ++-- .../onap/portalsdk/core/service/UserService.java | 9 +- .../core/service/UserServiceCentalizedImpl.java | 13 +- .../portalsdk/core/service/UserServiceImpl.java | 10 +- .../core/service/WebServiceCallService.java | 9 +- .../core/service/WebServiceCallServiceImpl.java | 152 ++------ .../core/service/support/FusionService.java | 7 +- .../core/service/support/ServiceLocator.java | 5 +- .../core/service/support/ServiceLocatorImpl.java | 110 +++--- 46 files changed, 1289 insertions(+), 1684 deletions(-) (limited to 'ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service') diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AccessConfiguration.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AccessConfiguration.java index d369199d..9feeb3a2 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AccessConfiguration.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AccessConfiguration.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppService.java index 6ca1d013..07d8fec7 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -68,10 +68,11 @@ public interface AppService { * FN_APP table. */ App getDefaultApp(); - + /** - * Fetches the application name once from database - * and keep refers to the same name later on as required. + * Fetches the application name once from database and keep refers to the same + * name later on as required. + * * @return Default Application Name */ String getDefaultAppName(); diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppServiceImpl.java index 179b0864..e0f8fc24 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AppServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -47,19 +47,18 @@ import org.springframework.transaction.annotation.Transactional; @Service("appService") @Transactional -public class AppServiceImpl implements AppService{ +public class AppServiceImpl implements AppService { private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppServiceImpl.class); - + @Autowired - private DataAccessService dataAccessService; + private DataAccessService dataAccessService; /** - * Loads the appName once from database and - * keep refers to it as required. + * Loads the appName once from database and keep refers to it as required. */ private static String defaultAppName = ""; - + @SuppressWarnings("unchecked") @Override public List getApps() { @@ -68,16 +67,17 @@ public class AppServiceImpl implements AppService{ @Override public App getApp(Long appId) { - return (App)getDataAccessService().getDomainObject(App.class, appId, null); + return (App) getDataAccessService().getDomainObject(App.class, appId, null); } @Override public App getDefaultApp() { return getApp(1L); } - + /** * Gets the data access service. + * * @return DataAccessService */ public DataAccessService getDataAccessService() { @@ -86,25 +86,28 @@ public class AppServiceImpl implements AppService{ /** * Sets the data access service. + * * @param dataAccessService */ public void setDataAccessService(DataAccessService dataAccessService) { this.dataAccessService = dataAccessService; } - + /** - * Fetches the application name once from database - * and keep refers to the same name later on as required. + * Fetches the application name once from database and keep refers to the same + * name later on as required. + * * @return Default Application Name */ @Override public String getDefaultAppName() { - if (AppServiceImpl.defaultAppName==null || AppServiceImpl.defaultAppName=="") { + if (AppServiceImpl.defaultAppName == null || AppServiceImpl.defaultAppName == "") { App app = getApp(1L); - if (app!=null) { - AppServiceImpl.defaultAppName = app.getName(); + if (app != null) { + AppServiceImpl.defaultAppName = app.getName(); } else { - logger.warn(EELFLoggerDelegate.errorLogger, ("Unable to locate the app information from the database.")); + logger.warn(EELFLoggerDelegate.errorLogger, + "Unable to locate the app information from the database."); } } return AppServiceImpl.defaultAppName; diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditService.java index ec0c7ce7..40fc2f08 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,7 +37,7 @@ */ package org.onap.portalsdk.core.service; -import java.util.HashMap; +import java.util.Map; import org.onap.portalsdk.core.domain.AuditLog; @@ -49,7 +49,7 @@ public interface AuditService { * @param auditLog * @param additionalParams */ - + @SuppressWarnings("rawtypes") - void logActivity(AuditLog auditLog, HashMap additionalParams); + void logActivity(AuditLog auditLog, Map additionalParams); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditServiceImpl.java index 77db3681..1bc81d9a 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/AuditServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,7 +37,7 @@ */ package org.onap.portalsdk.core.service; -import java.util.HashMap; +import java.util.Map; import org.onap.portalsdk.core.domain.AuditLog; import org.springframework.beans.factory.annotation.Autowired; @@ -47,15 +47,18 @@ import org.springframework.transaction.annotation.Transactional; @Service("auditService") @Transactional public class AuditServiceImpl implements AuditService { - public AuditServiceImpl() {} - - @Autowired - private DataAccessService dataAccessService; - - @SuppressWarnings("rawtypes") - public void logActivity(AuditLog auditLog, HashMap additionalParams) { + + @Autowired + private DataAccessService dataAccessService; + + public AuditServiceImpl() { + } + + @Override + @SuppressWarnings("rawtypes") + public void logActivity(AuditLog auditLog, Map additionalParams) { getDataAccessService().saveDomainObject(auditLog, additionalParams); - } + } public DataAccessService getDataAccessService() { return dataAccessService; @@ -64,5 +67,5 @@ public class AuditServiceImpl implements AuditService { public void setDataAccessService(DataAccessService dataAccessService) { this.dataAccessService = dataAccessService; } - + } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastService.java index bef46450..3cbf6644 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,7 +37,7 @@ */ package org.onap.portalsdk.core.service; -import java.util.*; +import java.util.Map; import javax.servlet.http.HttpServletRequest; @@ -45,10 +45,16 @@ import org.onap.portalsdk.core.domain.BroadcastMessage; @SuppressWarnings("rawtypes") public interface BroadcastService { - HashMap getBcModel(HttpServletRequest request); - Hashtable getBroadcastMessages(); - void loadMessages(); - BroadcastMessage getBroadcastMessage(HttpServletRequest request); + + Map getBcModel(HttpServletRequest request); + + Map getBroadcastMessages(); + + void loadMessages(); + + BroadcastMessage getBroadcastMessage(HttpServletRequest request); + void saveBroadcastMessage(BroadcastMessage broadcastMessage); + void removeBroadcastMessage(BroadcastMessage broadcastMessage); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastServiceImpl.java index 19803d94..5d14ee47 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/BroadcastServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -42,6 +42,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.TreeSet; @@ -49,6 +50,7 @@ import javax.servlet.http.HttpServletRequest; import org.onap.portalsdk.core.domain.BroadcastMessage; import org.onap.portalsdk.core.domain.Lookup; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.service.support.FusionService; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.web.support.AppUtils; @@ -62,199 +64,201 @@ import org.springframework.web.bind.ServletRequestUtils; @Service("broadcastService") @Transactional public class BroadcastServiceImpl extends FusionService implements BroadcastService { - - public BroadcastServiceImpl() { - } + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(BroadcastServiceImpl.class); @Autowired - private DataAccessService dataAccessService; - private static Hashtable broadcastMessages = new Hashtable(); - - @SuppressWarnings("unchecked") - public void loadMessages() { - List messageLocations = AppUtils.getLookupListNoCache("fn_lu_message_location", "message_location_id", "message_location_descr", "", "message_location_id"); - - for (int i=0; i < messageLocations.size(); i++) { - Lookup location = (Lookup)messageLocations.get(i); - String locationId = location.getValue(); - - broadcastMessages.put(locationId, getPersistedBroadcastMessages(locationId)); - } - } - - public HashMap getBcModel(HttpServletRequest request){ - HashMap bcModel = new HashMap(); - - List items = null; - int messageId = ServletRequestUtils.getIntParameter(request, "message_id", 0); - String task = ServletRequestUtils.getStringParameter(request, "task", "get"); - - // delete or toggle activation on the selected record (if applicable) - if (messageId != 0 && (task.equals("delete") || task.equals("toggleActive"))) { - BroadcastMessage message = (BroadcastMessage)getDataAccessService().getDomainObject(BroadcastMessage.class, new Long(messageId), null); - - if (task.equals("delete")) { - getDataAccessService().deleteDomainObject(message, null); - } - else if (task.equals("toggleActive")) { - HashMap additionalParams = new HashMap(); - additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request); - - message.setActive(new Boolean(!message.getActive().booleanValue())); - getDataAccessService().saveDomainObject(message, additionalParams); - } - loadMessages(); - } - - items = getDataAccessService().getList(BroadcastMessage.class, null); - Collections.sort(items); - bcModel.put("messagesList", packageMessages(items)); - - List locations = AppUtils.getLookupList("fn_lu_message_location", "message_location_id", "message_location_descr", "", "message_location_id"); - bcModel.put("messageLocations", locations); - - if ("true".equals(SystemProperties.getProperty(SystemProperties.CLUSTERED))) { - List sites = AppUtils.getLookupList("fn_lu_broadcast_site", "broadcast_site_cd", "broadcast_site_descr", "", "broadcast_site_descr"); - bcModel.put("broadcastSites", sites); - } - - return bcModel; - } - - @SuppressWarnings("unchecked") - private HashMap packageMessages(List messages) { - HashMap messagesList = new HashMap(); - Set locationMessages = null; - - Integer previousLocationId = null; - - for (int i=0; i < messages.size(); i++) { - BroadcastMessage message = (BroadcastMessage)messages.get(i); - - if (!message.getLocationId().equals(previousLocationId)) { - if (previousLocationId != null) { - messagesList.put(previousLocationId.toString(), locationMessages); - } - - locationMessages = new TreeSet(); - previousLocationId = message.getLocationId(); - } - - locationMessages.add(message); - } - - if (previousLocationId != null) { - messagesList.put(previousLocationId.toString(), locationMessages); - } - - return messagesList; - } - - - @SuppressWarnings("unchecked") - private List getPersistedBroadcastMessages(String locationId) { - HashMap params = new HashMap(); - - - - params.put("location_id", new Integer(locationId)); - - Calendar calInstanceToday = Calendar.getInstance(); - calInstanceToday.set(Calendar.HOUR, 0); - calInstanceToday.set(Calendar.MINUTE, 0); - calInstanceToday.set(Calendar.SECOND, 0); - params.put("today_date", calInstanceToday.getTime()); - - return getDataAccessService().executeNamedQuery("broadcastMessages", params, null); - } - - public Hashtable getBroadcastMessages() { - return broadcastMessages; - } - - public static List getBroadcastMessages(String locationId) { - return (List)broadcastMessages.get(locationId); - } - - public static String displayMessages(String locationId) { - return displayServerMessages(locationId, null); - } - - public static String displayServerMessages(String locationId, String siteCd) { - StringBuffer html = new StringBuffer(); - - List messages = getBroadcastMessages(locationId); - - for (int i=0; i < messages.size(); i++) { - BroadcastMessage message = (BroadcastMessage)messages.get(i); - - if ((message.getSiteCd() == null) || ((message.getSiteCd() != null) && message.getSiteCd().equals(siteCd))) { - html.append("
  • ") - .append(message.getMessageText()); - } - } - - if (html.length() > 0) { - html.insert(0, "
      "); - html.append("
    "); - } - - return html.toString(); - } - - public static boolean hasMessages(String locationId) { - return hasServerMessages(locationId, null); - } - - public static boolean hasServerMessages(String locationId, String siteCd) { - List messages = getBroadcastMessages(locationId); - boolean messagesExist = !((messages == null) || messages.size() == 0); - if (!messagesExist) - return false; - - if (siteCd == null) { - return messagesExist; - } - else { - for (int i=0; i < messages.size(); i++) { - BroadcastMessage message = (BroadcastMessage)messages.get(i); - - if ((message.getSiteCd() == null) || message.getSiteCd().equals(siteCd)) { - return true; - } - } - return false; - } - } - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - public void setDataAccessService(DataAccessService dataAccessService) { - dataAccessService = dataAccessService; - } - - public BroadcastMessage getBroadcastMessage(HttpServletRequest request) { - long messageId = ServletRequestUtils.getLongParameter(request, "message_id", 0); - - BroadcastMessage message = new BroadcastMessage(); - if(messageId!=0) - message = (BroadcastMessage)getDataAccessService().getDomainObject(BroadcastMessage.class, new Long(messageId), null); - - if (message.getLocationId() == null) { - try { - message.setLocationId(new Integer(ServletRequestUtils.getStringParameter(request, "message_location_id"))); - } catch (NumberFormatException e) { - e.printStackTrace(); - } catch (ServletRequestBindingException e) { - e.printStackTrace(); + private DataAccessService dataAccessService; + + private static Hashtable broadcastMessages = new Hashtable(); + + public BroadcastServiceImpl() { + super(); + } + + @Override + @SuppressWarnings("unchecked") + public void loadMessages() { + List messageLocations = AppUtils.getLookupListNoCache("fn_lu_message_location", "message_location_id", + "message_location_descr", "", "message_location_id"); + + for (int i = 0; i < messageLocations.size(); i++) { + Lookup location = (Lookup) messageLocations.get(i); + String locationId = location.getValue(); + + broadcastMessages.put(locationId, getPersistedBroadcastMessages(locationId)); + } + } + + @Override + @SuppressWarnings("unchecked") + public Map getBcModel(HttpServletRequest request) { + HashMap bcModel = new HashMap(); + + int messageId = ServletRequestUtils.getIntParameter(request, "message_id", 0); + String task = ServletRequestUtils.getStringParameter(request, "task", "get"); + + // delete or toggle activation on the selected record (if applicable) + if (messageId != 0 && ("delete".equals(task) || "toggleActive".equals(task))) { + BroadcastMessage message = (BroadcastMessage) getDataAccessService().getDomainObject(BroadcastMessage.class, + new Long(messageId), null); + + if ("delete".equals(task)) { + getDataAccessService().deleteDomainObject(message, null); + } else if ("toggleActive".equals(task)) { + HashMap additionalParams = new HashMap(); + additionalParams.put(Parameters.PARAM_HTTP_REQUEST, request); + + message.setActive(new Boolean(!message.getActive().booleanValue())); + getDataAccessService().saveDomainObject(message, additionalParams); + } + loadMessages(); + } + + List items = getDataAccessService().getList(BroadcastMessage.class, null); + Collections.sort(items); + bcModel.put("messagesList", packageMessages(items)); + + List locations = AppUtils.getLookupList("fn_lu_message_location", "message_location_id", + "message_location_descr", "", "message_location_id"); + bcModel.put("messageLocations", locations); + + if ("true".equals(SystemProperties.getProperty(SystemProperties.CLUSTERED))) { + List sites = AppUtils.getLookupList("fn_lu_broadcast_site", "broadcast_site_cd", "broadcast_site_descr", "", + "broadcast_site_descr"); + bcModel.put("broadcastSites", sites); } - message.setActive(Boolean.TRUE); - } - return message; - } + return bcModel; + } + + @SuppressWarnings("unchecked") + private HashMap packageMessages(List messages) { + HashMap messagesList = new HashMap(); + Set locationMessages = null; + + Integer previousLocationId = null; + + for (int i = 0; i < messages.size(); i++) { + BroadcastMessage message = (BroadcastMessage) messages.get(i); + + if (!message.getLocationId().equals(previousLocationId)) { + if (previousLocationId != null) { + messagesList.put(previousLocationId.toString(), locationMessages); + } + + locationMessages = new TreeSet(); + previousLocationId = message.getLocationId(); + } + + locationMessages.add(message); + } + + if (previousLocationId != null) { + messagesList.put(previousLocationId.toString(), locationMessages); + } + + return messagesList; + } + + @SuppressWarnings("unchecked") + private List getPersistedBroadcastMessages(String locationId) { + HashMap params = new HashMap(); + + params.put("location_id", new Integer(locationId)); + + Calendar calInstanceToday = Calendar.getInstance(); + calInstanceToday.set(Calendar.HOUR, 0); + calInstanceToday.set(Calendar.MINUTE, 0); + calInstanceToday.set(Calendar.SECOND, 0); + params.put("today_date", calInstanceToday.getTime()); + + return getDataAccessService().executeNamedQuery("broadcastMessages", params, null); + } + + @Override + public Map getBroadcastMessages() { + return broadcastMessages; + } + + public static List getBroadcastMessages(String locationId) { + return (List) broadcastMessages.get(locationId); + } + + public static String displayMessages(String locationId) { + return displayServerMessages(locationId, null); + } + + public static String displayServerMessages(String locationId, String siteCd) { + StringBuilder html = new StringBuilder(); + List messages = getBroadcastMessages(locationId); + for (int i = 0; i < messages.size(); i++) { + BroadcastMessage message = (BroadcastMessage) messages.get(i); + if ((message.getSiteCd() == null) + || ((message.getSiteCd() != null) && message.getSiteCd().equals(siteCd))) { + html.append("
  • ").append(message.getMessageText()); + } + } + if (html.length() > 0) { + html.insert(0, "
      "); + html.append("
    "); + } + return html.toString(); + } + + public static boolean hasMessages(String locationId) { + return hasServerMessages(locationId, null); + } + + public static boolean hasServerMessages(String locationId, String siteCd) { + List messages = getBroadcastMessages(locationId); + boolean messagesExist = !((messages == null) || messages.isEmpty()); + if (!messagesExist) + return false; + + if (siteCd == null) { + return messagesExist; + } else { + for (int i = 0; i < messages.size(); i++) { + BroadcastMessage message = (BroadcastMessage) messages.get(i); + + if ((message.getSiteCd() == null) || message.getSiteCd().equals(siteCd)) { + return true; + } + } + return false; + } + } + + @Override + public BroadcastMessage getBroadcastMessage(HttpServletRequest request) { + long messageId = ServletRequestUtils.getLongParameter(request, "message_id", 0); + + BroadcastMessage message = new BroadcastMessage(); + if (messageId != 0) + message = (BroadcastMessage) getDataAccessService().getDomainObject(BroadcastMessage.class, + new Long(messageId), null); + + if (message.getLocationId() == null) { + try { + message.setLocationId( + new Integer(ServletRequestUtils.getStringParameter(request, "message_location_id"))); + } catch (NumberFormatException | ServletRequestBindingException e) { + logger.error(EELFLoggerDelegate.errorLogger, "getBroadcastMessage failed", e); + } + message.setActive(Boolean.TRUE); + } + + return message; + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(final DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } @Override public void saveBroadcastMessage(BroadcastMessage broadcastMessage) { @@ -265,5 +269,5 @@ public class BroadcastServiceImpl extends FusionService implements BroadcastServ public void removeBroadcastMessage(BroadcastMessage broadcastMessage) { dataAccessService.deleteDomainObject(broadcastMessage, null); } - + } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/CentralAccessCondition.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/CentralAccessCondition.java index 65ee9460..e4b7a163 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/CentralAccessCondition.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/CentralAccessCondition.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,22 +44,21 @@ import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class CentralAccessCondition implements Condition { - + /** * returns true if the application is centralized */ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { boolean isRemote = false; - - if(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) == null) - { + + if (PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) == null) { isRemote = false; + } else if (PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) != null + && "remote".equals(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED))) { + isRemote = true; } - else if(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) != null && PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED).equals("remote")){ - isRemote = true; - } - - return isRemote; - } + + return isRemote; + } } \ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessService.java index 737d6a6f..8eacefa9 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,9 +37,7 @@ */ package org.onap.portalsdk.core.service; - import java.io.Serializable; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -52,47 +50,68 @@ import org.onap.portalsdk.core.domain.support.DomainVo; @SuppressWarnings("rawtypes") public interface DataAccessService { - // generic view, save, delete methods - DomainVo getDomainObject(Class domainClass, Serializable id, HashMap additionalParams); - void deleteDomainObject(DomainVo domainObject, HashMap additionalParams); - void deleteDomainObjects(Class domainClass, String whereClause, HashMap additionalParams); - void saveDomainObject(DomainVo domainObject, HashMap additionalParams); - - // generic get list method(s) - List getList(Class domainClass, HashMap additionalParams); - List getList(Class domainClass, String filter, String orderBy, HashMap additionalParams); - List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy, HashMap additionalParams); - List getList(Class domainClass, ProjectionList projectionsList , List restrictionsList , List orderByList); - public List getList(Class domainClass, ProjectionList projectionsList, List restrictionsList, List orderByList,HashMap fetchModeMap); - - List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, HashMap additionalParams); - - // generic native-SQL execution methods - List executeSQLQuery(String sql, Class domainClass, HashMap additionalParams); - List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex,HashMap additionalParams); - - // generic HQL execution methods - List executeQuery(String hql, HashMap additionalParams); - List executeQuery(String hql, Integer fromIndex, Integer toIndex, HashMap additionalParams); - - // generic named query execution methods - List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, HashMap additionalParams); - List executeNamedQuery(String queryName, Map params, HashMap additionalParams); - List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex, HashMap additionalParams); - - //with Where Clause for RAPTOR ZK - List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams); - List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params); - List executeNamedQuery(Class entity, String queryName, String whereClause, Map params, Integer fromIndex, Integer toIndex, HashMap additionalParams); - List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params, String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams); - - // generic update query execution method - int executeUpdateQuery(String sql, HashMap additionalParams) throws RuntimeException; - - // generic named update query execution method - int executeNamedUpdateQuery(String queryName, Map params, HashMap additionalParams) throws RuntimeException; - - // synchronizes the local updates with the database (and vice versa) - void synchronize(HashMap additionalParams); + // generic view, save, delete methods + DomainVo getDomainObject(Class domainClass, Serializable id, Map additionalParams); + + void deleteDomainObject(DomainVo domainObject, Map additionalParams); + + void deleteDomainObjects(Class domainClass, String whereClause, Map additionalParams); + + void saveDomainObject(DomainVo domainObject, Map additionalParams); + + // generic get list method(s) + List getList(Class domainClass, Map additionalParams); + + List getList(Class domainClass, String filter, String orderBy, Map additionalParams); + + List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy, + Map additionalParams); + + List getList(Class domainClass, ProjectionList projectionsList, List restrictionsList, + List orderByList); + + public List getList(Class domainClass, ProjectionList projectionsList, List restrictionsList, + List orderByList, Map fetchModeMap); + + List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, + Map additionalParams); + + // generic native-SQL execution methods + List executeSQLQuery(String sql, Class domainClass, Map additionalParams); + + List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex, Map additionalParams); + + // generic HQL execution methods + List executeQuery(String hql, Map additionalParams); + + List executeQuery(String hql, Integer fromIndex, Integer toIndex, Map additionalParams); + + // generic named query execution methods + List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, Map additionalParams); + + List executeNamedQuery(String queryName, Map params, Map additionalParams); + + List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex, Map additionalParams); + + // with Where Clause for RAPTOR ZK + List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String orderBy, boolean asc, + Integer fromIndex, Integer toIndex, Map additionalParams); + + List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params); + + List executeNamedQuery(Class entity, String queryName, String whereClause, Map params, Integer fromIndex, + Integer toIndex, Map additionalParams); + + List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params, String orderBy, + boolean asc, Integer fromIndex, Integer toIndex, Map additionalParams); + + // generic update query execution method + int executeUpdateQuery(String sql, Map additionalParams); + + // generic named update query execution method + int executeNamedUpdateQuery(String queryName, Map params, Map additionalParams); + + // synchronizes the local updates with the database (and vice versa) + void synchronize(Map additionalParams); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessServiceImpl.java index e53260db..f34610cb 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/DataAccessServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -41,7 +41,6 @@ import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Date; -import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -75,66 +74,55 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe private SessionFactory sessionFactory; @Override - public DomainVo getDomainObject(Class domainClass, Serializable id, HashMap additionalParams) { - DomainVo vo = null; + public DomainVo getDomainObject(Class domainClass, Serializable id, Map additionalParams) { Session session = sessionFactory.getCurrentSession(); - logger.info(EELFLoggerDelegate.debugLogger, "Getting " + domainClass.getName() + " record for id - " + id.toString()); - vo = (DomainVo) session.get(domainClass, id); - + logger.info(EELFLoggerDelegate.debugLogger, + "Getting " + domainClass.getName() + " record for id - " + id.toString()); + DomainVo vo = (DomainVo) session.get(domainClass, id); if (vo == null) { try { vo = (DomainVo) domainClass.newInstance(); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "An error occured while instantiating a class of " + domainClass.getName() + e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, + "getDomainObject failed while instantiating class " + domainClass.getName(), e); } } return vo; } @Override - public void deleteDomainObject(DomainVo domainObject, HashMap additionalParams) { + public void deleteDomainObject(DomainVo domainObject, Map additionalParams) { Session session = sessionFactory.getCurrentSession(); session.delete(domainObject); } @Override - public void deleteDomainObjects(Class domainClass, String whereClause, HashMap additionalParams) { - int rowsAffected = 0; + public void deleteDomainObjects(Class domainClass, String whereClause, Map additionalParams) { Session session = sessionFactory.getCurrentSession(); - StringBuffer sql = new StringBuffer("delete from "); - sql.append(domainClass.getName()).append(" where ").append(whereClause); - - rowsAffected = session.createQuery(sql.toString()).executeUpdate(); - /* return rowsAffected; */ + Query query = session.createQuery(sql.toString()); + query.executeUpdate(); } @Override - public void saveDomainObject(DomainVo vo, HashMap additionalParams) { + public void saveDomainObject(DomainVo vo, Map additionalParams) { Integer userId = 1; if (additionalParams != null) { - // look for a passed user id - // userId = (Integer)additionalParams.get(Parameters.PARAM_USERID); Object uid = additionalParams.get(Parameters.PARAM_USERID); if (uid instanceof Integer) { userId = (Integer) uid; } else if (uid instanceof Long) { userId = ((Long) uid).intValue(); } - // if (userId == null) { - // look for a passed request to get the user id from - // userId = new - // Integer(UserUtils.getUserId((HttpServletRequest)additionalParams.get(Parameters.PARAM_HTTP_REQUEST))); - // } } _update(vo, userId); } /** - * Creates or updates the specified virtual object. Uses the specified user - * ID as the creator and modifier if a new object is created; uses ID only - * as modifier if an object already exists. + * Creates or updates the specified virtual object. Uses the specified user ID + * as the creator and modifier if a new object is created; uses ID only as + * modifier if an object already exists. * * @param vo * @param userId @@ -178,7 +166,6 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe */ private List getListCommon(Class domainClass, String filterClause, Integer fromIndex, Integer toIndex, String orderBy) { - List list = null; String className = domainClass.getName(); Session session = sessionFactory.getCurrentSession(); @@ -187,13 +174,12 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe + ((fromIndex != null) ? " from rows " + fromIndex.toString() + " to " + toIndex.toString() : "") + "..."); if (filterClause != null && filterClause.length() > 0) - logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause); + logger.info(EELFLoggerDelegate.debugLogger, "Filtering " + className + " by: " + filterClause); } - list = session.createQuery("from " + className + Utilities.nvl(filterClause, "") + List list = session.createQuery("from " + className + Utilities.nvl(filterClause, "") + ((orderBy != null) ? " order by " + orderBy : "")).list(); list = (fromIndex != null) ? list.subList(fromIndex.intValue() - 1, toIndex.intValue()) : list; - if (orderBy == null && list != null) Collections.sort(list); @@ -201,18 +187,18 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe } @Override - public List getList(Class domainClass, HashMap additionalParams) { + public List getList(Class domainClass, Map additionalParams) { return getListCommon(domainClass, null, null, null, null); } @Override - public List getList(Class domainClass, String filter, String orderBy, HashMap additionalParams) { + public List getList(Class domainClass, String filter, String orderBy, Map additionalParams) { return getListCommon(domainClass, filter, null, null, orderBy); } @Override public List getList(Class domainClass, String filter, int fromIndex, int toIndex, String orderBy, - HashMap additionalParams) { + Map additionalParams) { return getListCommon(domainClass, filter, new Integer(fromIndex), new Integer(toIndex), orderBy); } @@ -237,36 +223,28 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe for (Order order : orderByList) criteria.addOrder(order); } - /* - * if(fetchModeMap!=null){ Iterator itr = - * fetchModeMap.keySet().iterator(); String key=null; - * while(itr.hasNext()){ key = itr.next(); - * criteria.setFetchMode(key,fetchModeMap.get(key)); } } - */ + return criteria.list(); } @Override public List getLookupList(String dbTable, String dbValueCol, String dbLabelCol, String dbFilter, String dbOrderBy, - HashMap additionalParams) { + Map additionalParams) { if (logger.isInfoEnabled()) - logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list..."); + logger.info(EELFLoggerDelegate.debugLogger, "Retrieving " + dbTable + " lookup list..."); String dbOrderByCol = dbOrderBy; Session session = sessionFactory.getCurrentSession(); - // default the orderBy if null; + // default the orderBy if null if (Utilities.nvl(dbOrderBy).length() == 0) { dbOrderByCol = dbLabelCol; dbOrderBy = dbLabelCol; - } else { - if (dbOrderBy.lastIndexOf(" ") > -1) { - dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" ")); - } + } else if (dbOrderBy.lastIndexOf(" ") > -1) { + dbOrderByCol = dbOrderBy.substring(0, dbOrderBy.lastIndexOf(" ")); } - StringBuffer sql = new StringBuffer(); - + StringBuilder sql = new StringBuilder(); sql.append("select distinct ").append(dbLabelCol).append(" as lab, ").append(dbValueCol).append(" as val, ") .append(dbOrderByCol).append(" as sortOrder ").append("from ").append(dbTable).append(" ") .append((Utilities.nvl(dbFilter).length() == 0) ? "" : (" where " + dbFilter)).append(" order by ") @@ -276,7 +254,7 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe try { list = session.createSQLQuery(sql.toString()).addEntity(Lookup.class).list(); } catch (Exception e) { - logger.error(EELFLoggerDelegate.debugLogger, "Failed to create SQL lookup query for [" + sql + "]" + e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "getLookupList failed on query query [" + sql + "]", e); } return list; } @@ -287,13 +265,13 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe */ @Override - public List executeSQLQuery(String sql, Class domainClass, HashMap additionalParams) { + public List executeSQLQuery(String sql, Class domainClass, Map additionalParams) { return executeSQLQuery(sql, domainClass, null, null, additionalParams); } @Override public List executeSQLQuery(String sql, Class domainClass, Integer fromIndex, Integer toIndex, - HashMap additionalParams) { + Map additionalParams) { Session session = sessionFactory.getCurrentSession(); SQLQuery query = session.createSQLQuery(sql).addEntity(domainClass.getName().toLowerCase(), domainClass); @@ -308,12 +286,12 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe } @Override - public List executeQuery(String sql, HashMap additionalParams) { + public List executeQuery(String sql, Map additionalParams) { return executeQuery(sql, null, null, additionalParams); } @Override - public List executeQuery(String sql, Integer fromIndex, Integer toIndex, HashMap additionalParams) { + public List executeQuery(String sql, Integer fromIndex, Integer toIndex, Map additionalParams) { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery(sql); @@ -328,18 +306,18 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe } @Override - public List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, HashMap additionalParams) { + public List executeNamedQuery(String queryName, Integer fromIndex, Integer toIndex, Map additionalParams) { return executeNamedQuery(queryName, null, fromIndex, toIndex, additionalParams); } @Override - public List executeNamedQuery(String queryName, Map params, HashMap additionalParams) { + public List executeNamedQuery(String queryName, Map params, Map additionalParams) { return executeNamedQuery(queryName, params, null, null, additionalParams); } @Override public List executeNamedQuery(String queryName, Map params, Integer fromIndex, Integer toIndex, - HashMap additionalParams) { + Map additionalParams) { Session session = sessionFactory.getCurrentSession(); Query query = session.getNamedQuery(queryName); bindQueryParameters(query, params); @@ -364,15 +342,16 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe if (params != null) { for (Iterator i = params.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); - Object parameterValue = entry.getValue(); - if (!(parameterValue instanceof Collection) && !(parameterValue instanceof Object[])) { query.setParameter((String) entry.getKey(), parameterValue); } else if (parameterValue instanceof Collection) { query.setParameterList((String) entry.getKey(), (Collection) parameterValue); } else if (parameterValue instanceof Object[]) { query.setParameterList((String) entry.getKey(), (Object[]) parameterValue); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "bindQueryParameters: no match for value {}", + parameterValue); } } } @@ -381,62 +360,55 @@ public class DataAccessServiceImpl extends FusionService implements DataAccessSe // With Where Clause & RAPTOR's ZK @Override - public List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String _orderBy, boolean asc, - Integer fromIndex, Integer toIndex, HashMap additionalParams) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return null; + public List executeNamedQueryWithOrderBy(Class entity, String queryName, Map params, String orderBy, boolean asc, + Integer fromIndex, Integer toIndex, Map additionalParams) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @Override public List executeNamedCountQuery(Class entity, String queryName, String whereClause, Map params) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return null; + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @Override public List executeNamedQuery(Class entity, String queryName, String whereClause, Map params, Integer fromIndex, - Integer toIndex, HashMap additionalParams) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return null; + Integer toIndex, Map additionalParams) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @Override public List executeNamedQueryWithOrderBy(Class entity, String queryName, String whereClause, Map params, - String _orderBy, boolean asc, Integer fromIndex, Integer toIndex, HashMap additionalParams) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return null; + String orderBy, boolean asc, Integer fromIndex, Integer toIndex, Map additionalParams) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @Override public List getList(Class domainClass, ProjectionList projectionsList, List restrictionsList, - List orderByList, HashMap fetchModeMap) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return null; + List orderByList, Map fetchModeMap) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @Override - public int executeUpdateQuery(String sql, HashMap additionalParams) throws RuntimeException { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return 0; + public int executeUpdateQuery(String sql, Map additionalParams) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @Override - public int executeNamedUpdateQuery(String queryName, Map params, HashMap additionalParams) throws RuntimeException { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); - return 0; + public int executeNamedUpdateQuery(String queryName, Map params, Map additionalParams) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } @Override - public void synchronize(HashMap additionalParams) { - // TODO Auto-generated method stub - logger.info(EELFLoggerDelegate.debugLogger, "Not implemented"); + public void synchronize(Map additionalParams) { + logger.error(EELFLoggerDelegate.errorLogger, "Not implemented"); + throw new UnsupportedOperationException(); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementLinkService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementLinkService.java index d9c25377..e096d832 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementLinkService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementLinkService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,22 +44,25 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.util.YamlUtils; public class ElementLinkService { + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ElementLinkService.class); + /** * Builds renderable model of element links in the network map. Parses YAML - * files with metadata and builds input for JoinJS to render in the browser - * as SVG. + * files with metadata and builds input for JoinJS to render in the browser as + * SVG. * * @param args * arg 0 - realPath; arg 1 - callFlowName; arg 2 - callFlowStep. * @return Renderable model of element links - * @throws Exception + * @throws IOException */ - public String buildElementLinkYaml(String[] args) throws Exception { + public String buildElementLinkYaml(String[] args) throws IOException { String relFilePath; if (args[1].startsWith("custom")) relFilePath = SystemProperties.getProperty("customCallFlow_path"); @@ -82,69 +85,26 @@ public class ElementLinkService { return linkYaml; } - /* - * public String main2(String[] args) throws Exception { - * - * String filePath = SystemProperties.getProperty("element_map_file_path") + - * File.separator; String callFlowBusinessYml = ""; String callFlowStep = - * ""; - * - * if (args != null && args.length > 0) { - * - * if (args[0] != null) { callFlowBusinessYml = args[0] + "-Override.yml"; } - * - * if (args[1] != null) { callFlowStep = args[1]; } } - * - * ElementLinkService mapper = new ElementLinkService(); - * - * return mapper.createLinkFileAdditional(filePath, callFlowBusinessYml, - * callFlowStep); } - */ - - public static void main(String[] args) throws Exception { - - String filePath = "\\D2Platform\\war\\WEB-INF\\resources\\trisim_files"; - String callFlowBusinessYml = "call_flow_hc-origination-termination-to-volteue-3.3.16-Override.yml"; - - ElementLinkService mapper = new ElementLinkService(); - - // System.out.print(mapper.createLinkFile(filePath, networkToscaYml, - // networkToscaUeYml, networkLayoutYml, callFlowBusinessYml,"Step_1")); - System.out.print(mapper.createLinkFileAdditional(filePath, callFlowBusinessYml, "Step_2")); - } - @SuppressWarnings("unchecked") protected String createLinkFile(String resourceFilePath, String callFLowBsFileName, String callFlowStep) - throws Exception { - + throws IOException { Map callFlowBs = YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName); - List> callSteps = (List>) callFlowBs.get("callSequenceSteps"); String callFlowName = (String) callFlowBs.get("shortName"); return addLinks(resourceFilePath, callFlowName, callSteps, callFlowStep); - } @SuppressWarnings("unchecked") protected String createLinkFileAdditional(String resourceFilePath, String callFLowBsFileName, String callFlowStep) throws Exception { - - // Map callFlowBs = - // YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName); - - // return YamlUtils.returnYaml(callFlowBs); - Map callFlowBs; - try { callFlowBs = YamlUtils.readYamlFile(resourceFilePath, callFLowBsFileName); - List> callSteps = (List>) callFlowBs.get("callSequenceSteps"); String callFlowName = (String) callFlowBs.get("shortName"); return addLinksAdditional(resourceFilePath, callFlowName, callSteps, callFlowStep); - } catch (Exception e) { - + logger.error(EELFLoggerDelegate.errorLogger, "createLinkFileAdditional failed", e); return ""; } @@ -154,22 +114,18 @@ public class ElementLinkService { protected String addLinks(String filePath, String callFlowName, List> callSteps, String callFlowStep) throws IOException { - Map> checkDuplicateMap = new HashMap>(); + Map> checkDuplicateMap = new HashMap<>(); for (Map callStep : callSteps) { if (((String) callStep.get("name")).split(":")[0].trim().replace(" ", "_").equals(callFlowStep)) { - // String callFlowStepName = callFlowName + "_" + - // ((String)callStep.get("name")).split("-")[0].trim().replace(" - // ", "_")+".yml"; - - List> links = new ArrayList>(); + List> links = new ArrayList<>(); List> subSteps = (List>) callStep.get("subSteps"); for (Map subStep : subSteps) { - Map link = new HashMap(); + Map link = new HashMap<>(); String source = (String) subStep.get("source_tosca_id"); String destination = (String) subStep.get("destination_tosca_id"); @@ -177,12 +133,12 @@ public class ElementLinkService { if ((checkDuplicateMap.get(source) == null || checkDuplicateMap.get(source).isEmpty() || !checkDuplicateMap.get(source).contains(destination)) && !source.equals(destination)) { if (checkDuplicateMap.get(destination) == null) { - List toscaList = new ArrayList(); + List toscaList = new ArrayList<>(); checkDuplicateMap.put(destination, toscaList); } if (checkDuplicateMap.get(source) == null) { - List toscaList = new ArrayList(); + List toscaList = new ArrayList<>(); checkDuplicateMap.put(source, toscaList); } @@ -195,30 +151,14 @@ public class ElementLinkService { link.put("s", source); link.put("d", destination); links.add(link); - - /* - * may be needed in future but nnot currently - * - * if((String) subStep.get("link_visibility")!=null){ - * if(((String) - * subStep.get("link_visibility")).equals("No")){ - * - * } }else{ - * - * links.add(link); } - */ - } } - Map callFlowUI = new HashMap(); + Map callFlowUI = new HashMap<>(); callFlowUI.put("linkList", links); return YamlUtils.returnYaml(callFlowUI); - - // YamlUtils.writeYamlFile(filePath, callFlowStepName, - // callFlowUI); } } @@ -232,25 +172,24 @@ public class ElementLinkService { if (((String) callStep.get("name")).split(":")[0].trim().replace(" ", "_").equals(callFlowStep)) { - // String callFlowStepName = callFlowName + "_" + - // ((String)callStep.get("name")).split("-")[0].trim().replace(" - // ", "_")+".yml"; - - Map callFlowUI = new HashMap(); + Map callFlowUI = new HashMap<>(); try { List> links = addLinkVertices(callStep); callFlowUI.put("linkList", links); } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addLinksAdditional failed", e); } try { List activeIds = addActiveNodes(callStep); callFlowUI.put("activeIds", activeIds); } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addLinksAdditional failed", e); } try { List> disconnectLinks = addDisconnectLinks(callStep); callFlowUI.put("disconnectLinks", disconnectLinks); } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addLinksAdditional failed", e); } return YamlUtils.returnYaml(callFlowUI); @@ -274,13 +213,13 @@ public class ElementLinkService { @SuppressWarnings("unchecked") List> addLinkVertices(Map callStep) { - List> links = new ArrayList>(); + List> links = new ArrayList<>(); List> vertices = (List>) callStep.get("vertices"); for (int i = 0; i < vertices.size() - 1; i++) { - Map vertex = (Map) vertices.get(i); - Map vertexNext = (Map) vertices.get(i + 1); + Map vertex = vertices.get(i); + Map vertexNext = vertices.get(i + 1); Integer sourceX = (Integer) vertex.get("x"); Integer sourceY = (Integer) vertex.get("y"); @@ -297,7 +236,7 @@ public class ElementLinkService { if (destinationX == -999) // there is a break in the linkage continue; - Map link = new HashMap(); + Map link = new HashMap<>(); link.put("s", sourceX + "," + sourceY + "," + sourceD + "," + sourceL); link.put("d", destinationX + "," + destinationY + "," + destinationD); @@ -305,4 +244,12 @@ public class ElementLinkService { } return links; } + + public static void main(String[] args) throws Exception { + String filePath = "\\D2Platform\\war\\WEB-INF\\resources\\trisim_files"; + String callFlowBusinessYml = "call_flow_hc-origination-termination-to-volteue-3.3.16-Override.yml"; + ElementLinkService mapper = new ElementLinkService(); + System.out.print(mapper.createLinkFileAdditional(filePath, callFlowBusinessYml, "Step_2")); + } + } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementMapService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementMapService.java index 2c89dccd..d24bd503 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementMapService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ElementMapService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,6 +38,7 @@ package org.onap.portalsdk.core.service; import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -63,28 +64,39 @@ public class ElementMapService { private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ElementMapService.class); + private static HashMap toscaElementsMap = new HashMap<>(); + private static HashMap elementMap = new HashMap<>(); + private static HashMap miscElementMap = new HashMap<>(); + private static HashMap outercontainers = new HashMap<>(); + private static HashMap innercontainers = new HashMap<>(); + private static HashMap domainMap = new HashMap<>(); + + private static String filePath = SystemProperties.getProperty("element_map_file_path"); + private static String networkToscaYml = null;// "NetworkMap_topology_composition.yml"; + private static String networkLayoutYml = null;// "network_map_layout.yml"; + /** * * @param contextRealPath * @param layout * @return - * @throws Exception + * @throws IOException */ - private String convertToYAML(String contextRealPath, Layout layout) throws Exception { + private String convertToYAML(String contextRealPath, Layout layout) throws IOException { // Used to build image file relative URLs - final String iconRelPath = SystemProperties.getProperty("element_map_icon_path"); // "static/img/map/icons/"; + final String iconRelPath = SystemProperties.getProperty("element_map_icon_path"); - Map resultAICDomain = layout.domainRowCol; - Map> domainMap = new HashMap>(); - List domainList = new ArrayList(); + Map resultAICDomain = layout.getDomainRowCol(); + Map> domainMap = new HashMap<>(); + List domainList = new ArrayList<>(); for (Domain d : resultAICDomain.values()) { d.setWidth(10 * d.computeSize().getWidth()); d.setHeight(10 * d.computeSize().getHeight()); d.setLeft(10 * d.getP().getX()); d.setTop(10 * d.getP().getY()); - List containerList = new ArrayList(); + List containerList = new ArrayList<>(); for (Container c : d.getContainerRowCol().values()) { c.setWidth(10 * c.computeSize().getWidth()); c.setHeight(10 * c.computeSize().getHeight()); @@ -97,7 +109,7 @@ public class ElementMapService { } if (c.getContainerRowCol() != null) { - List innerContainerList = new ArrayList(); + List innerContainerList = new ArrayList<>(); for (Container innerC : c.getContainerRowCol().values()) { innerC.setName(innerC.getName()); innerC.setWidth(10 * innerC.computeSize().getWidth()); @@ -106,9 +118,8 @@ public class ElementMapService { innerC.setTop(10 * innerC.getP().getY()); if (innerC.getElementRowCol() != null) { - List innerContainerEList = new ArrayList(); + List innerContainerEList = new ArrayList<>(); for (Element ele : innerC.getElementRowCol().values()) { - // ele.setName(ele.getName()); ele.setWidth(10 * ele.computeSize().getWidth()); ele.setHeight(10 * ele.computeSize().getHeight()); ele.setLeft(10 * ele.getP().getX()); @@ -128,9 +139,8 @@ public class ElementMapService { } if (c.getElementRowCol() != null) { - List elementList = new ArrayList(); + List elementList = new ArrayList<>(); for (Element e : c.getElementRowCol().values()) { - // e.setName(e.getName()); e.setWidth(10 * e.computeSize().getWidth()); e.setHeight(10 * e.computeSize().getHeight()); e.setLeft(10 * e.getP().getX()); @@ -157,7 +167,7 @@ public class ElementMapService { } domainMap.put("domainList", domainList); - List collapsedDomains = new ArrayList(); + List collapsedDomains = new ArrayList<>(); // nline for (Domain collapsed : layout.getCollapsedDomainsNewList()) { @@ -183,30 +193,17 @@ public class ElementMapService { } - private static HashMap toscaElementsMap = new HashMap(); - private static HashMap elementMap = new HashMap(); - private static HashMap miscElementMap = new HashMap(); - private static HashMap outercontainers = new HashMap(); - private static HashMap innercontainers = new HashMap(); - private static HashMap domainMap = new HashMap(); - - private static String filePath = SystemProperties.getProperty("element_map_file_path"); - private static String networkToscaYml = null;// "NetworkMap_topology_composition.yml"; - private static String networkLayoutYml = null;// "network_map_layout.yml"; - /** * Builds renderable model of elements in the network map. Parses YAML files - * with metadata and builds input for JoinJS to render in the browser as - * SVG. + * with metadata and builds input for JoinJS to render in the browser as SVG. * * @param args - * arg 0 - collapsedDomains; arg 1 - expandedDomains; arg 2 - - * context real path; arg 3 - contentFileName; arg 4 - - * layoutFileName + * arg 0 - collapsedDomains; arg 1 - expandedDomains; arg 2 - context + * real path; arg 3 - contentFileName; arg 4 - layoutFileName * @return Renderable model of elements - * @throws Exception + * @throws IOException */ - public String buildElementMapYaml(String args[]) throws Exception { + public String buildElementMapYaml(String args[]) throws IOException { final String yamlDirPath = new File(args[2], filePath).getPath(); if (args != null && args.length > 4) { @@ -219,12 +216,12 @@ public class ElementMapService { Map toscaYaml = YamlUtils.readYamlFile(yamlDirPath, networkToscaYml); Map networkMapLayoutYaml = YamlUtils.readYamlFile(yamlDirPath, networkLayoutYml); - toscaElementsMap = new HashMap(); - elementMap = new HashMap(); - domainMap = new HashMap(); - outercontainers = new HashMap(); - innercontainers = new HashMap(); - miscElementMap = new HashMap(); + toscaElementsMap = new HashMap<>(); + elementMap = new HashMap<>(); + domainMap = new HashMap<>(); + outercontainers = new HashMap<>(); + innercontainers = new HashMap<>(); + miscElementMap = new HashMap<>(); if (toscaYaml != null) { for (String key : toscaYaml.keySet()) { @@ -238,12 +235,6 @@ public class ElementMapService { toscaElementsMap = (HashMap) toscaTopologyDetails.get(detailsKey); - // for (String toscaElementKey : - // toscaElementsMap.keySet()) { - //// System.out.println("Element - "+ "key :" + - //// toscaElementKey); - // } - } } } @@ -267,8 +258,6 @@ public class ElementMapService { if (elementlist != null) { for (Object eachElement : elementlist) { - // System.out.println("toscaNetworkMapElementStyleList - // Container : " +eachElement); if (eachElement != null && eachElement instanceof HashMap) { HashMap elementDetails = (HashMap) eachElement; if (elementDetails != null) { @@ -279,7 +268,7 @@ public class ElementMapService { column = "0"; for (String detailsKey : elementDetails.keySet()) { if ("tosca_id".equalsIgnoreCase(detailsKey)) - elementName = elementDetails.get(detailsKey).toString(); + elementName = elementDetails.get(detailsKey); if ("id".equalsIgnoreCase(detailsKey)) { elementID = String.valueOf(elementDetails.get(detailsKey)); } @@ -290,7 +279,7 @@ public class ElementMapService { column = String.valueOf(elementDetails.get(detailsKey)); } if ("icon".equalsIgnoreCase(detailsKey)) - imgPath = elementDetails.get(detailsKey).toString(); + imgPath = elementDetails.get(detailsKey); } if (elementMap.containsKey(elementName.concat("/").concat(row).concat(column))) { @@ -313,12 +302,11 @@ public class ElementMapService { for (String elementkey : elementMap.keySet()) { Element c = (Element) elementMap.get(elementkey); - // System.out.println("Element - "+ "key :" +elementkey +" - - // " + "value :" + c.getName()); + logger.trace(EELFLoggerDelegate.debugLogger, "buildElementMapYaml: element {}", c); } if (!elementMap.isEmpty()) { - miscElementMap = new HashMap(elementMap); + miscElementMap = new HashMap<>(elementMap); } } @@ -349,12 +337,12 @@ public class ElementMapService { for (String detailsKey : containerDetails.keySet()) { if ("logical_group_name".equalsIgnoreCase(detailsKey)) - containerName = containerDetails.get(detailsKey).toString(); + containerName = containerDetails.get(detailsKey); if ("id".equalsIgnoreCase(detailsKey)) { containerID = String.valueOf(containerDetails.get(detailsKey)); } if ("domain".equalsIgnoreCase(detailsKey)) { - domain = containerDetails.get(detailsKey).toString(); + domain = containerDetails.get(detailsKey); } if ("row".equalsIgnoreCase(detailsKey)) { row = String.valueOf(containerDetails.get(detailsKey)); @@ -401,12 +389,12 @@ public class ElementMapService { for (String detailsKey : containerDetails.keySet()) { if ("logical_group_name".equalsIgnoreCase(detailsKey)) - containerName = containerDetails.get(detailsKey).toString(); + containerName = containerDetails.get(detailsKey); if ("id".equalsIgnoreCase(detailsKey)) { containerID = String.valueOf(containerDetails.get(detailsKey)); } if ("domain".equalsIgnoreCase(detailsKey)) { - domain = containerDetails.get(detailsKey).toString(); + domain = containerDetails.get(detailsKey); } if ("row".equalsIgnoreCase(detailsKey)) { row = String.valueOf(containerDetails.get(detailsKey)); @@ -430,9 +418,6 @@ public class ElementMapService { outercontainers.put(mapKey, fetchContainerObject(containerID, containerName, false, containerName, domain)); } - // else innercontainers.put(domain +":"+ - // containerName, - // fetchContainerObject(containerID,containerName.substring(containerName.indexOf("/")+1),false,containerName,domain)); } } @@ -442,10 +427,12 @@ public class ElementMapService { for (String innerContainerkey : innercontainers.keySet()) { Container c = (Container) innercontainers.get(innerContainerkey); + logger.trace(EELFLoggerDelegate.debugLogger, "buildElementMapYaml: inner container {}", c); } for (String outerContainerkey : outercontainers.keySet()) { Container c = (Container) outercontainers.get(outerContainerkey); + logger.trace(EELFLoggerDelegate.debugLogger, "buildElementMapYaml: outer container {}", c); } } @@ -463,10 +450,8 @@ public class ElementMapService { if (domainlist != null) { - HashMap domainStagingMap = new HashMap(); + HashMap domainStagingMap = new HashMap<>(); for (Object eachDomain : domainlist) { - // System.out.println("domainlist Container : " - // +eachDomain); if (eachDomain != null && eachDomain instanceof HashMap) { HashMap domainDetails = (HashMap) eachDomain; if (domainDetails != null) { @@ -476,7 +461,7 @@ public class ElementMapService { column = "0"; for (String detailsKey : domainDetails.keySet()) { if ("name".equalsIgnoreCase(detailsKey)) - domainName = domainDetails.get(detailsKey).toString(); + domainName = domainDetails.get(detailsKey); if ("id".equalsIgnoreCase(detailsKey)) { domainID = String.valueOf(domainDetails.get(detailsKey)); } @@ -510,11 +495,6 @@ public class ElementMapService { } } - // for (String domainkey : domainMap.keySet()) { - // Domain c = (Domain) domainMap.get(domainkey); - // System.out.println("Domain - "+ "key :" +domainkey +" - " - // + "value :" + c.getName()); - // } } } @@ -522,35 +502,20 @@ public class ElementMapService { Layout dynamicLayout = new Layout(domainMap, 2, 10, 1, 5); dynamicLayout.computeDomainPositionsModified(); - /* - * Map resultAICDomain2 = dynamicLayout.domainRowCol; - * for (String key : resultAICDomain2.keySet()) { if - * (resultAICDomain2.get(key).getP() != null) { - * System.out.println(resultAICDomain2.get(key).name+" "+"x:"+ - * resultAICDomain2.get(key).getP().getX()+","+"y:"+ - * resultAICDomain2.get(key).getP().getY()+","+"width:"+ - * resultAICDomain2.get(key).computeSize().getWidth() - * +","+"height:"+resultAICDomain2.get(key).computeSize(). getHeight()); - * - * } } - */ - ElementMapService cm2 = new ElementMapService(); try { if (args != null && args.length > 0) { if (args[0] != null) { - String collapsedDomains[] = args[0].split(","); + String[] collapsedDomains = args[0].split(","); for (String collapsedDomain : collapsedDomains) - // dynamicLayout.collapseDomainModified(collapsedDomain); dynamicLayout.collapseDomainNew(collapsedDomain); } if (args[1] != null) { - String expandedDomains[] = args[1].split(","); + String[] expandedDomains = args[1].split(","); for (String expandedDomain : expandedDomains) - // dynamicLayout.uncollapseDomainNew(expandedDomain); dynamicLayout.uncollapseDomainNew1(expandedDomain); } @@ -605,7 +570,7 @@ public class ElementMapService { private static Container fetchContainerObject(String id, String name, boolean isInner, String logicalGroupName, String domain) { - Map containerElementsMap = new HashMap(); + Map containerElementsMap = new HashMap<>(); containerElementsMap = fetchElementsMapForContainer(name, isInner, logicalGroupName, domain); int rows = 1; @@ -620,7 +585,6 @@ public class ElementMapService { Container thisContainer = new Container(id, name, rows, columns, 1, 4, 8, 12, 1, 2); thisContainer.setElements(containerElementsMap); - // thisContainer.setVisibilityType(""); return thisContainer; } else { @@ -629,7 +593,7 @@ public class ElementMapService { if (innerContainersMap != null && !innerContainersMap.isEmpty()) { if (containerElementsMap != null && !containerElementsMap.isEmpty()) { - Set keys = new HashSet(innerContainersMap.keySet()); + Set keys = new HashSet<>(innerContainersMap.keySet()); keys.addAll(containerElementsMap.keySet()); rows = computeRows(keys); columns = computeColumns(keys); @@ -648,8 +612,7 @@ public class ElementMapService { if (containerElementsMap != null && !containerElementsMap.isEmpty()) { for (Element thisElement : containerElementsMap.values()) { - if (thisElement.getId() != null - ) { + if (thisElement.getId() != null) { thisContainer.setVisibilityType("invisible"); } } @@ -660,7 +623,7 @@ public class ElementMapService { } private static Domain fetchDomainObject(String id, String name) { - HashMap domainContainersMap = fetchContainersForDomain(name); + Map domainContainersMap = fetchContainersForDomain(name); int rows = 1; int columns = 1; @@ -671,31 +634,25 @@ public class ElementMapService { double domainWidth = 11; Domain thisDomain; - if (domainMap != null && !domainMap.isEmpty()) { int domainsCountSoFar = domainMap.size(); switch (domainsCountSoFar) { - case 1: { + case 1: domainWidth = 12.1; break; - } - case 2: { + case 2: domainWidth = 13.3; break; - } - case 3: { + case 3: domainWidth = 14.5; break; - } - case 4: { + case 4: domainWidth = 15.6; break; - } - default: { + default: domainWidth = 11; break; } - } for (String domainsKey : new TreeSet(domainMap.keySet())) { Domain eachDomain = domainMap.get(domainsKey); @@ -707,8 +664,6 @@ public class ElementMapService { thisDomain = new Domain(id, name, 2, 1, 11, 10, 3, rows, columns); } - // Domain thisDomain = new Domain(id, name, 2, 1, leftPosition, 10, 3, - // rows, columns); thisDomain.setContainers(domainContainersMap); thisDomain.computeConatinerPositions(); @@ -716,42 +671,18 @@ public class ElementMapService { for (Container thisContainer : domainContainersMap.values()) { thisContainer.computeSize(); thisContainer.computeElementPositions(); - Map resultElementMap = thisContainer.elementRowCol; + Map resultElementMap = thisContainer.getElementRowCol(); for (String key : resultElementMap.keySet()) { if (resultElementMap.get(key) == null || resultElementMap.get(key).getP() == null) { - // System.out.println("culprit " +key); + logger.debug(EELFLoggerDelegate.debugLogger, "fetchDomainObject: {}", key); } - /* - * System.out.println(resultElementMap.get(key).name+" " - * +"x:"+resultElementMap.get(key).getP().getX()+","+"y:"+ - * resultElementMap.get(key).getP().getY()+","+"width:"+ - * resultElementMap.get(key).computeSize().getWidth() - * +","+"height:"+resultElementMap.get(key).computeSize(). - * getHeight()); - */ - } HashMap innerContainersMap = (HashMap) thisContainer .getContainerRowCol(); if (innerContainersMap != null && !innerContainersMap.isEmpty()) { for (Container thisInnerContainer : innerContainersMap.values()) { - // thisInnerContainer.computeSize(); thisInnerContainer.computeElementPositions(); - /* - * Map resultInnerElementMap = - * thisContainer.elementRowCol; for (String key : - * resultElementMap.keySet()) { // - * System.out.println(resultElementMap.get(key).name+" " - * +"x:"+resultElementMap.get(key).getP().getX()+","+ - * "y:"+ - * resultElementMap.get(key).getP().getY()+","+"width:"+ - * resultElementMap.get(key).computeSize().getWidth() - * +","+"height:"+resultElementMap.get(key).computeSize( - * ).getHeight()); - * - * } - */ } } } @@ -760,29 +691,12 @@ public class ElementMapService { return thisDomain; } - private static HashMap fetchContainersForDomain(String domain) { - HashMap domainContainersMap = new HashMap(); - - domainContainersMap = fetchFromOuterContainers(domain); - + private static Map fetchContainersForDomain(String domain) { + Map domainContainersMap = fetchFromOuterContainers(domain); return domainContainersMap; - } private static Element fetchElementObject(String id, String name, String imgPath) { - String bgColor = "bgColor"; - String logical_group; - String display_longname; - String display_shortname; - String description; - String primary_function; - String key_interfaces; - String location; - String vendor; - String vendor_shortname; - String enclosingContainer; - String borderType; - String network_function; if (toscaElementsMap.containsKey(name)) { @@ -791,35 +705,33 @@ public class ElementMapService { for (String detailsKey : toscaElementDetails.keySet()) { if ("properties".equalsIgnoreCase(detailsKey) - && toscaElementDetails.get(detailsKey) instanceof HashMap) { - HashMap elementDetails = (HashMap) toscaElementDetails - .get(detailsKey); + && toscaElementDetails.get(detailsKey) instanceof Map) { + Map elementDetails = (Map) toscaElementDetails.get(detailsKey); if (elementDetails != null) { - logical_group = elementDetails.get("logical_group") == null ? "" - : elementDetails.get("logical_group").toString(); - display_longname = elementDetails.get("display_longname") == null ? "" - : elementDetails.get("display_longname").toString(); - display_shortname = elementDetails.get("display_shortname") == null ? "" - : elementDetails.get("display_shortname").toString(); - description = elementDetails.get("description") == null ? "" - : elementDetails.get("description").toString(); - primary_function = elementDetails.get("primary_function") == null ? "" - : elementDetails.get("primary_function").toString(); - key_interfaces = elementDetails.get("key_interfaces") == null ? "" - : elementDetails.get("key_interfaces").toString(); - location = elementDetails.get("location") == null ? "" - : elementDetails.get("location").toString(); - vendor = elementDetails.get("vendor") == null ? "" - : elementDetails.get("vendor").toString(); - vendor_shortname = elementDetails.get("vendor_shortname") == null ? "" - : elementDetails.get("vendor_shortname").toString(); - enclosingContainer = logical_group.replace("/", "-"); - network_function = elementDetails.get("network_function"); - borderType = elementDetails.get("network_function") == null ? "P" - : elementDetails.get("network_function").toString().toUpperCase(); - bgColor = elementDetails.get("background_color") == null ? "bgColor" - : elementDetails.get("background_color").toString(); + String logical_group = elementDetails.get("logical_group") == null ? "" + : elementDetails.get("logical_group"); + String display_longname = elementDetails.get("display_longname") == null ? "" + : elementDetails.get("display_longname"); + String display_shortname = elementDetails.get("display_shortname") == null ? "" + : elementDetails.get("display_shortname"); + String description = elementDetails.get("description") == null ? "" + : elementDetails.get("description"); + String primary_function = elementDetails.get("primary_function") == null ? "" + : elementDetails.get("primary_function"); + String key_interfaces = elementDetails.get("key_interfaces") == null ? "" + : elementDetails.get("key_interfaces"); + String location = elementDetails.get("location") == null ? "" + : elementDetails.get("location"); + String vendor = elementDetails.get("vendor") == null ? "" : elementDetails.get("vendor"); + String vendor_shortname = elementDetails.get("vendor_shortname") == null ? "" + : elementDetails.get("vendor_shortname"); + String enclosingContainer = logical_group.replace("/", "-"); + String network_function = elementDetails.get("network_function"); + String borderType = elementDetails.get("network_function") == null ? "P" + : elementDetails.get("network_function").toUpperCase(); + String bgColor = elementDetails.get("background_color") == null ? "bgColor" + : elementDetails.get("background_color"); ElementDetails details = new ElementDetails(logical_group, display_longname, description, primary_function, network_function, key_interfaces, location, vendor, @@ -833,10 +745,6 @@ public class ElementMapService { } - // Element(id, name, imgPath, bgColor, logical_group, - // display_longname, - // description, primary_function, key_interfaces, location, vendor, - // vendor_shortname); } else { return new Element(id, name); } @@ -857,7 +765,7 @@ public class ElementMapService { .get(detailsKey); if (elementDetails != null) { - return elementDetails.get("domain") == null ? "" : elementDetails.get("domain").toString(); + return elementDetails.get("domain") == null ? "" : elementDetails.get("domain"); } } @@ -872,34 +780,29 @@ public class ElementMapService { return ""; } - private static HashMap fetchInnerContainersMapForOuter(String name, boolean isInner, + private static Map fetchInnerContainersMapForOuter(String name, boolean isInner, String logicalGroupName, String domain) { return fetchInnerContainersMap(name, logicalGroupName, domain); } - private static HashMap fetchElementsMapForContainer(String name, boolean isInner, + private static Map fetchElementsMapForContainer(String name, boolean isInner, String logicalGroupName, String domain) { return fetchElementsMap(logicalGroupName, domain); } - private static HashMap fetchInnerContainersMap(String name, String logicalGroupName, - String domain) { - HashMap containersMap = new HashMap(); - String rowColumnKey = ""; - int count = 0; + private static Map fetchInnerContainersMap(String name, String logicalGroupName, String domain) { + HashMap containersMap = new HashMap<>(); if (innercontainers != null && !innercontainers.isEmpty()) { for (String key : innercontainers.keySet()) { - Container eachContainer = innercontainers.get(key); - if (key.toUpperCase().contains((domain + ":" + name).toUpperCase())) { + String rowColumnKey = ""; if (key.contains("/")) { rowColumnKey = key.substring(key.lastIndexOf("/") + 1); } - if (rowColumnKey.isEmpty() || containersMap.containsKey(rowColumnKey)) { - count = 0; + int count = 0; while (count <= 9) { if (containersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) { count++; @@ -920,22 +823,21 @@ public class ElementMapService { } - private static HashMap fetchFromOuterContainers(String domain) { - HashMap thisContainersMap = new HashMap(); - String rowColumnKey = ""; - int count = 0; + private static Map fetchFromOuterContainers(String domain) { + HashMap thisContainersMap = new HashMap<>(); if (outercontainers != null && !outercontainers.isEmpty()) { for (String key : outercontainers.keySet()) { Container eachContainer = outercontainers.get(key); if (key.toUpperCase().contains((domain + ":").toUpperCase())) { + String rowColumnKey = ""; if (key.contains("/")) { rowColumnKey = key.substring(key.lastIndexOf("/") + 1); } if (rowColumnKey.isEmpty() || thisContainersMap.containsKey(rowColumnKey)) { - count = 0; + int count = 0; while (count <= 9) { if (thisContainersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) { count++; @@ -962,9 +864,10 @@ public class ElementMapService { String domainName = fetchDomainNameOfElement(elementName); if (domain.equalsIgnoreCase(domainName)) { + String rowColumnKey = ""; Container eachContainer = new Container(domainName + ":" + elementName, elementName, 1, 1, 3, 6, 2, 5, 0, 0); - count = 0; + int count = 0; while (count <= 9) { if (thisContainersMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) { count++; @@ -984,45 +887,25 @@ public class ElementMapService { return thisContainersMap.isEmpty() ? null : thisContainersMap; } - private static HashMap addOuterContainersForMiscElements(String domain) { - HashMap containerElementsMap = new HashMap(); - if (miscElementMap != null && !miscElementMap.isEmpty()) { - for (String key : miscElementMap.keySet()) { - Element eachElement = miscElementMap.get(key); - String elementName = eachElement.getName(); - String domainName = fetchDomainNameOfElement(elementName); - - if (domain.equalsIgnoreCase(domainName)) { - Container newContainer = new Container(domainName + ":" + elementName, elementName, 1, 1, 3, 6, 2, - 5, 0, 0); - containerElementsMap.put(domainName + ":" + elementName, newContainer); - } - - } - - } - return containerElementsMap.isEmpty() ? null : containerElementsMap; - } - - private static HashMap fetchElementsMap(String logicalGroupName, String domain) { - HashMap innerElementMap = new HashMap(); - String rowColumnKey = ""; - int count = 0; + private static Map fetchElementsMap(String logicalGroupName, String domain) { + HashMap innerElementMap = new HashMap<>(); if (elementMap != null && !elementMap.isEmpty()) { for (String key : elementMap.keySet()) { Element eachElement = elementMap.get(key); String elementName = eachElement.getId(); - String elementLogicalGroup = eachElement.details == null ? "" : eachElement.details.logical_group; + String elementLogicalGroup = eachElement.getDetails() == null ? "" + : eachElement.getDetails().getLogical_group(); if (elementLogicalGroup.equalsIgnoreCase(logicalGroupName) && domain.equalsIgnoreCase(fetchDomainNameOfElement(elementName))) { + String rowColumnKey = ""; if (key.contains("/")) { rowColumnKey = key.substring(key.indexOf("/") + 1); } if (rowColumnKey.isEmpty() || innerElementMap.containsKey(rowColumnKey)) { - count = 0; + int count = 0; while (count <= 9) { if (innerElementMap.containsKey(String.valueOf(count).concat(String.valueOf(count)))) { count++; diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuService.java index 12203671..c426f2b5 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuServiceImpl.java index 8c445a46..6d7251ec 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FnMenuServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -56,6 +56,7 @@ public class FnMenuServiceImpl implements FnMenuService { @Autowired private DataAccessService dataAccessService; + @Override @SuppressWarnings("unchecked") public List getFnMenuItems() { return getDataAccessService().getList(MenuData.class, null, "1", null); @@ -77,7 +78,7 @@ public class FnMenuServiceImpl implements FnMenuService { @SuppressWarnings("unchecked") @Override public List getParentId(String label) { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("paramLabel", label); return getDataAccessService().executeNamedQuery("IdForLabelList", params, null); } @@ -98,6 +99,7 @@ public class FnMenuServiceImpl implements FnMenuService { getDataAccessService().deleteDomainObject(domainFnMenu, null); } + @Override public MenuData getMenuItemRow(Long id) { return (MenuData) getDataAccessService().getDomainObject(MenuData.class, id, null); } @@ -121,7 +123,7 @@ public class FnMenuServiceImpl implements FnMenuService { parentData.setAction(menu.getAction()); parentData.setImageSrc(menu.getImageSrc()); parentList.add(parentData); - List tempList = new ArrayList(); + List tempList = new ArrayList<>(); for (Object o : menu.getChildMenus()) { MenuData m = (MenuData) o; MenuData data = new MenuData(); diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListService.java index e2e6349d..53328315 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -45,7 +45,7 @@ import javax.servlet.http.HttpServletRequest; import org.onap.portalsdk.core.domain.RoleFunction; public interface FunctionalMenuListService { - + List getFunctionCDList(HttpServletRequest request) throws IOException; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceCentralizedImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceCentralizedImpl.java index 7192198d..d4d04538 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceCentralizedImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceCentralizedImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -50,7 +50,7 @@ import org.springframework.beans.factory.annotation.Autowired; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; -public class FunctionalMenuListServiceCentralizedImpl implements FunctionalMenuListService{ +public class FunctionalMenuListServiceCentralizedImpl implements FunctionalMenuListService { @Autowired private RestApiRequestBuilder restApiRequestBuilder; diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceImpl.java index b9e70e6e..becb1734 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/FunctionalMenuListServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -45,10 +45,10 @@ import javax.servlet.http.HttpServletRequest; import org.onap.portalsdk.core.domain.RoleFunction; import org.springframework.beans.factory.annotation.Autowired; -public class FunctionalMenuListServiceImpl implements FunctionalMenuListService{ - +public class FunctionalMenuListServiceImpl implements FunctionalMenuListService { + @Autowired - private DataAccessService dataAccessService; + private DataAccessService dataAccessService; public DataAccessService getDataAccessService() { return dataAccessService; diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapService.java index 9156c8a7..c810c19d 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,13 +37,15 @@ */ package org.onap.portalsdk.core.service; +import javax.naming.NamingException; + import org.onap.portalsdk.core.command.support.SearchResult; import org.onap.portalsdk.core.domain.support.DomainVo; - public interface LdapService { - // search POST for users based on the criteria selected in the Request - SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, int pageNo, int dataSize, int userId) throws Exception; + // search POST for users based on the criteria selected in the Request + SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, int pageNo, + int dataSize, int userId) throws NamingException; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapServiceImpl.java index ca2e13aa..6470ca63 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LdapServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -62,225 +62,189 @@ import org.springframework.transaction.annotation.Transactional; @Service("ldapService") @Transactional public class LdapServiceImpl extends FusionService implements LdapService { - + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LdapServiceImpl.class); - + @Autowired private ServiceLocator serviceLocator; - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, - int pageNo, int dataSize, int userId) throws Exception { - - // initialize the directory context to access POST - DirContext dirContext = serviceLocator.getDirContext(SystemProperties.getProperty(SystemProperties.POST_INITIAL_CONTEXT_FACTORY), - SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL), - SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL)); - - SearchResult searchResult = new SearchResult(); - - try { - - String[] postAttributes = {"nickname","givenName","initials","sn","employeeNumber","mail","telephoneNumber", - "departmentNumber","a1","street","roomNumber","l","st","postalCode","zip4","physicalDeliveryOfficeName","bc", - "friendlyCountryName","bd","bdname","bu","buname","jtname","mgrid","a2","compcode","compdesc", - "costcenter","silo","b2"}; - - SearchControls searchControls = new SearchControls(); - searchControls.setTimeLimit(5000); - searchControls.setReturningAttributes(postAttributes); - - StringBuffer filterClause = new StringBuffer("(&(objectClass=*)"); - - User user = (User)searchCriteria; - - if(Utilities.nvl(user.getFirstName()).length() > 0) { - filterClause.append("(givenName=").append(user.getFirstName()).append("*)"); - } - if(Utilities.nvl(user.getLastName()).length() > 0) { - filterClause.append("(sn=").append(user.getLastName()).append("*)"); - } - if(Utilities.nvl(user.getHrid()).length() > 0) { - filterClause.append("(employeeNumber=").append(user.getHrid()).append("*)"); - } - if(Utilities.nvl(user.getOrgManagerUserId()).length() > 0) { - filterClause.append("(mgrid=").append(user.getOrgManagerUserId()).append("*)"); - } - if(Utilities.nvl(user.getOrgCode()).length() > 0) { - filterClause.append("(departmentNumber=").append(user.getOrgCode()).append("*)"); - } - if(Utilities.nvl(user.getEmail()).length() > 0) { - filterClause.append("(mail=").append(user.getEmail()).append("*)"); - } - if(Utilities.nvl(user.getOrgUserId()).length() > 0) { - filterClause.append("(a1=").append(user.getOrgUserId()).append("*)"); - } - filterClause.append("(c3=N)"); // this has been added to filter CP09 entries on the LDAP server that are duplicates of existing individuals - filterClause.append(")"); - List list = new ArrayList(); - if (!filterClause.toString().equals("(&(objectClass=*))")) { - NamingEnumeration e = dirContext.search(SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL) + "/" + - SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL), - filterClause.toString(), - searchControls); - - list = processResults(e); - } - - Collections.sort(list); - - searchResult = new SearchResult(list); - searchResult.setPageNo(pageNo); - if(dataSize >= 0) { - searchResult.setDataSize(dataSize); - } - else { - searchResult.setDataSize(list.size()); - } // else - - } - catch(NamingException ne) { - logger.error(EELFLoggerDelegate.errorLogger,ne.getMessage()); - } - finally { - dirContext.close(); - } - - return searchResult; - } + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, int pageNo, + int dataSize, int userId) throws NamingException { + + // initialize the directory context to access POST + DirContext dirContext = serviceLocator.getDirContext( + SystemProperties.getProperty(SystemProperties.POST_INITIAL_CONTEXT_FACTORY), + SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL), + SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL)); + + SearchResult searchResult = new SearchResult(); + + String[] postAttributes = { "nickname", "givenName", "initials", "sn", "employeeNumber", "mail", + "telephoneNumber", "departmentNumber", "a1", "street", "roomNumber", "l", "st", "postalCode", "zip4", + "physicalDeliveryOfficeName", "bc", "friendlyCountryName", "bd", "bdname", "bu", "buname", "jtname", + "mgrid", "a2", "compcode", "compdesc", "costcenter", "silo", "b2" }; + + SearchControls searchControls = new SearchControls(); + searchControls.setTimeLimit(5000); + searchControls.setReturningAttributes(postAttributes); + + StringBuilder filterClause = new StringBuilder("(&(objectClass=*)"); + User user = (User) searchCriteria; + + if (Utilities.nvl(user.getFirstName()).length() > 0) { + filterClause.append("(givenName=").append(user.getFirstName()).append("*)"); + } + if (Utilities.nvl(user.getLastName()).length() > 0) { + filterClause.append("(sn=").append(user.getLastName()).append("*)"); + } + if (Utilities.nvl(user.getHrid()).length() > 0) { + filterClause.append("(employeeNumber=").append(user.getHrid()).append("*)"); + } + if (Utilities.nvl(user.getOrgManagerUserId()).length() > 0) { + filterClause.append("(mgrid=").append(user.getOrgManagerUserId()).append("*)"); + } + if (Utilities.nvl(user.getOrgCode()).length() > 0) { + filterClause.append("(departmentNumber=").append(user.getOrgCode()).append("*)"); + } + if (Utilities.nvl(user.getEmail()).length() > 0) { + filterClause.append("(mail=").append(user.getEmail()).append("*)"); + } + if (Utilities.nvl(user.getOrgUserId()).length() > 0) { + filterClause.append("(a1=").append(user.getOrgUserId()).append("*)"); + } + filterClause.append("(c3=N)"); // this has been added to filter CP09 entries on the LDAP server that are + // duplicates of existing individuals + filterClause.append(")"); + + List list = new ArrayList(); + if (!"(&(objectClass=*))".equals(filterClause.toString())) { + NamingEnumeration e = dirContext.search( + SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL) + "/" + + SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL), + filterClause.toString(), searchControls); + + list = processResults(e); + } + + Collections.sort(list); + + searchResult = new SearchResult(list); + searchResult.setPageNo(pageNo); + if (dataSize >= 0) { + searchResult.setDataSize(dataSize); + } else { + searchResult.setDataSize(list.size()); + } // else + + dirContext.close(); + + return searchResult; + } @SuppressWarnings({ "rawtypes", "unchecked" }) - private ArrayList processResults(NamingEnumeration e) throws NamingException { - ArrayList results = new ArrayList(); - int count = 0; + private ArrayList processResults(NamingEnumeration e) throws NamingException { + ArrayList results = new ArrayList(); + int count = 0; - while (e.hasMore()) { - javax.naming.directory.SearchResult searchResult = (javax.naming.directory.SearchResult)e.next(); - results.add(processAttributes(searchResult.getAttributes())); - count++; + while (e.hasMore()) { + javax.naming.directory.SearchResult searchResult = (javax.naming.directory.SearchResult) e.next(); + results.add(processAttributes(searchResult.getAttributes())); + count++; - if(count > Integer.parseInt(SystemProperties.getProperty(SystemProperties.POST_MAX_RESULT_SIZE))) { - break; - } + if (count > Integer.parseInt(SystemProperties.getProperty(SystemProperties.POST_MAX_RESULT_SIZE))) { + break; + } - } + } - return results; - } + return results; + } @SuppressWarnings("rawtypes") - private DomainVo processAttributes(Attributes resultAttributes) throws NamingException { - User user = new User(); - - try { - if (resultAttributes == null) { - // System.out.println("This result has no attributes"); - } else { - for (NamingEnumeration e = resultAttributes.getAll(); e.hasMore();) { //why the nested loop? - Attribute attribute = (Attribute)e.next(); - for (NamingEnumeration ie = attribute.getAll(); ie.hasMore();) { - if (attribute.getID().equalsIgnoreCase("nickname")) { - user.setFirstName((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("initials")) { - user.setMiddleInitial((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("sn")) { - user.setLastName((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("employeeNumber")) { - user.setHrid((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("mail")) { - user.setEmail((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("telephoneNumber")) { - user.setPhone((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("departmentNumber")) { - user.setOrgCode((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("a1")) { - user.setOrgUserId((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("street")) { - user.setAddress1((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("roomNumber")) { - user.setAddress2((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("l")) { - user.setCity((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("st")) { - user.setState((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("postalCode")) { - user.setZipCode((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("zip4")) { - user.setZipCodeSuffix((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("physicalDeliveryOfficeName")) { - user.setLocationClli((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("bc")) { - user.setBusinessCountryCode((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("friendlyCountryName")) { - user.setBusinessCountryName((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("bd")) { - user.setDepartment((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("bdname")) { - user.setDepartmentName((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("jtname")) { - user.setJobTitle((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("mgrid")) { - user.setOrgManagerUserId((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("a2")) { - user.setCommandChain((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("compcode")) { - user.setCompanyCode((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("compdesc")) { - user.setCompany((String) ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("bu")) { - user.setBusinessUnit((String)ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("buname")) { - user.setBusinessUnitName((String)ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("silo")) { - user.setSiloStatus((String)ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("costcenter")) { - user.setCostCenter((String)ie.next()); - } - else if (attribute.getID().equalsIgnoreCase("b2")) { - user.setFinancialLocCode((String)ie.next()); - } - else { //we don't care about returned attribute, let's move on - ie.next(); - } - - } - } - } - } catch (NamingException e) { - logger.error(EELFLoggerDelegate.errorLogger, "An error occurred while processing the following user from POST with an ORGUSERID of " + user.getOrgUserId() + e.getMessage()); - } - - return user; - - } - + private DomainVo processAttributes(Attributes resultAttributes) { + User user = new User(); + try { + if (resultAttributes == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "processAttributes: no attributes"); + } else { + for (NamingEnumeration e = resultAttributes.getAll(); e.hasMore();) { // why the nested loop? + Attribute attribute = (Attribute) e.next(); + for (NamingEnumeration ie = attribute.getAll(); ie.hasMore();) { + if (attribute.getID().equalsIgnoreCase("nickname")) { + user.setFirstName((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("initials")) { + user.setMiddleInitial((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("sn")) { + user.setLastName((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("employeeNumber")) { + user.setHrid((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("mail")) { + user.setEmail((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("telephoneNumber")) { + user.setPhone((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("departmentNumber")) { + user.setOrgCode((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("a1")) { + user.setOrgUserId((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("street")) { + user.setAddress1((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("roomNumber")) { + user.setAddress2((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("l")) { + user.setCity((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("st")) { + user.setState((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("postalCode")) { + user.setZipCode((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("zip4")) { + user.setZipCodeSuffix((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("physicalDeliveryOfficeName")) { + user.setLocationClli((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("bc")) { + user.setBusinessCountryCode((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("friendlyCountryName")) { + user.setBusinessCountryName((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("bd")) { + user.setDepartment((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("bdname")) { + user.setDepartmentName((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("jtname")) { + user.setJobTitle((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("mgrid")) { + user.setOrgManagerUserId((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("a2")) { + user.setCommandChain((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("compcode")) { + user.setCompanyCode((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("compdesc")) { + user.setCompany((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("bu")) { + user.setBusinessUnit((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("buname")) { + user.setBusinessUnitName((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("silo")) { + user.setSiloStatus((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("costcenter")) { + user.setCostCenter((String) ie.next()); + } else if (attribute.getID().equalsIgnoreCase("b2")) { + user.setFinancialLocCode((String) ie.next()); + } else { // we don't care about returned attribute, let's move on + ie.next(); + } + + } + } + } + } catch (NamingException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "An error occurred while processing the following user from POST with an ORGUSERID of " + + user.getOrgUserId() + e.getMessage()); + } + + return user; + + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LocalAccessCondition.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LocalAccessCondition.java index 772b2559..c7636f10 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LocalAccessCondition.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LocalAccessCondition.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -43,14 +43,16 @@ import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class LocalAccessCondition implements Condition{ - +public class LocalAccessCondition implements Condition { + /** * returns true if the application is not centralized */ @Override - public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - return PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) == null || (PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) != null && ! PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED).equals("remote")); - } + public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { + return PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) == null + || (PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED) != null && !"remote" + .equals(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED))); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginService.java index f3a62de7..b03be694 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,36 +37,34 @@ */ package org.onap.portalsdk.core.service; +import java.io.IOException; +import java.util.Map; -import java.util.*; - -import org.onap.portalsdk.core.command.*; - +import org.onap.portalsdk.core.command.LoginBean; public interface LoginService { /** - * + * validate user exists in the system * @param bean * @param menuPropertiesFilename * @param additionalParams * @return returns login user bean - * @throws Exception + * @throws IOException */ - // validate user exists in the system @SuppressWarnings("rawtypes") - LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams) throws Exception; - - + LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams) throws IOException; + /** * * @param bean * @param menuPropertiesFilename * @param additionalParams * @param matchPassword - * @return returns login user bean - * @throws Exception + * @return returns login user bean + * @throws IOException */ @SuppressWarnings("rawtypes") - LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception; + LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams, boolean matchPassword) + throws IOException; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceCentralizedImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceCentralizedImpl.java index 9956cc48..749fdc38 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceCentralizedImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceCentralizedImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,6 +37,7 @@ */ package org.onap.portalsdk.core.service; +import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -48,6 +49,7 @@ import java.util.Set; import org.onap.portalsdk.core.command.LoginBean; import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.menu.MenuBuilder; import org.onap.portalsdk.core.service.support.FusionService; import org.onap.portalsdk.core.util.SystemProperties; @@ -56,19 +58,17 @@ import org.onap.portalsdk.core.web.support.UserUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; - @Transactional public class LoginServiceCentralizedImpl extends FusionService implements LoginService { - @Autowired - private AppService appService; + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginServiceCentralizedImpl.class); @Autowired private DataAccessService dataAccessService; - + @Autowired private RestApiRequestBuilder restApiRequestBuilder; - + @Autowired private UserService userService; @@ -76,28 +76,26 @@ public class LoginServiceCentralizedImpl extends FusionService implements LoginS private MenuBuilder menuBuilder; @Override - public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams) - throws Exception { + public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams) throws IOException { return findUser(bean, menuPropertiesFilename, additionalParams, true); } + @Override @SuppressWarnings("rawtypes") - public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, - boolean matchPassword) throws Exception { - User user = null; - User userCopy = null; + public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams, + boolean matchPassword) throws IOException { - if (bean.getUserid() != null && bean.getUserid() != null) { - user = (User) findUser(bean); + User user; + if (bean.getUserid() != null) { + user = findUser(bean); } else { if (matchPassword) - user = (User) findUser(bean.getLoginId(), bean.getLoginPwd()); + user = findUser(bean.getLoginId(), bean.getLoginPwd()); else - user = (User) findUserWithoutPwd(bean.getLoginId()); + user = findUserWithoutPwd(bean.getLoginId()); } if (user != null) { - if (AppUtils.isApplicationLocked() && !UserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) { bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED); @@ -116,14 +114,19 @@ public class LoginServiceCentralizedImpl extends FusionService implements LoginS // this will be a snapshot of the user's information as // retrieved from the database - userCopy = (User) user.clone(); + User userCopy = null; + try { + userCopy = (User) user.clone(); + } catch (CloneNotSupportedException ex) { + // Never happens + logger.error(EELFLoggerDelegate.errorLogger, "findUser failed", ex); + } User appuser = getUser(userCopy); appuser.setLastLoginDate(new Date()); // update the last logged in date for the user - // user.setLastLoginDate(new Date()); getDataAccessService().saveDomainObject(appuser, additionalParams); // update the audit log of the user @@ -162,17 +165,15 @@ public class LoginServiceCentralizedImpl extends FusionService implements LoginS return hasActiveRole; } - @SuppressWarnings("null") - public User findUser(LoginBean bean) throws Exception { - User user = null; + public User findUser(LoginBean bean) throws IOException { String repsonse = restApiRequestBuilder.getViaREST("/user/" + bean.getUserid(), true, bean.getUserid()); - user = userService.userMapper(repsonse); + User user = userService.userMapper(repsonse); user.setId(getUserIdByOrgUserId(user.getOrgUserId())); return user; } - + public Long getUserIdByOrgUserId(String orgUserId) { - Map params = new HashMap(); + Map params = new HashMap<>(); params.put("orgUserId", orgUserId); @SuppressWarnings("rawtypes") List list = getDataAccessService().executeNamedQuery("getUserIdByorgUserId", params, null); @@ -181,26 +182,20 @@ public class LoginServiceCentralizedImpl extends FusionService implements LoginS userId = (Long) list.get(0); return userId; } - public User findUser(String loginId, String password) { - - List list = null; - - StringBuffer criteria = new StringBuffer(); + StringBuilder criteria = new StringBuilder(); criteria.append(" where login_id = '").append(loginId).append("'").append(" and login_pwd = '").append(password) .append("'"); - - list = getDataAccessService().getList(User.class, criteria.toString(), null, null); - return (list == null || list.size() == 0) ? null : (User) list.get(0); + List list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + return (list == null || list.isEmpty()) ? null : (User) list.get(0); } private User findUserWithoutPwd(String loginId) { - List list = null; - StringBuffer criteria = new StringBuffer(); + StringBuilder criteria = new StringBuilder(); criteria.append(" where login_id = '").append(loginId).append("'"); - list = getDataAccessService().getList(User.class, criteria.toString(), null, null); - return (list == null || list.size() == 0) ? null : (User) list.get(0); + List list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + return (list == null || list.isEmpty()) ? null : (User) list.get(0); } public DataAccessService getDataAccessService() { @@ -220,14 +215,10 @@ public class LoginServiceCentralizedImpl extends FusionService implements LoginS } public User getUser(User user) { - List list = null; - - StringBuffer criteria = new StringBuffer(); + StringBuilder criteria = new StringBuilder(); criteria.append(" where login_id = '").append(user.getLoginId()).append("'"); - - list = getDataAccessService().getList(User.class, criteria.toString(), null, null); - return (list == null || list.size() == 0) ? null : (User) list.get(0); - + List list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + return (list == null || list.isEmpty()) ? null : (User) list.get(0); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceImpl.java index 6965bf3c..4d240972 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/LoginServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,15 +38,16 @@ package org.onap.portalsdk.core.service; import java.util.Date; -import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.Set; import org.onap.portalsdk.core.command.LoginBean; import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.menu.MenuBuilder; import org.onap.portalsdk.core.service.support.FusionService; import org.onap.portalsdk.core.util.SystemProperties; @@ -58,161 +59,144 @@ import org.springframework.transaction.annotation.Transactional; @Transactional public class LoginServiceImpl extends FusionService implements LoginService { + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginServiceImpl.class); + @SuppressWarnings("unused") - private MenuBuilder menuBuilder; - - @Autowired - private DataAccessService dataAccessService; - - @SuppressWarnings("rawtypes") - public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams ) throws Exception { - return findUser(bean, menuPropertiesFilename, additionalParams, true); - } - - @SuppressWarnings("rawtypes") - public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception { - User user = null; - User userCopy = null; - - if (bean.getUserid() != null && bean.getUserid() != null) { - user = (User)findUser(bean); - } - else { - if (matchPassword) - user = (User)findUser(bean.getLoginId(), bean.getLoginPwd()); - else - user = (User)findUserWithoutPwd(bean.getLoginId()); - } - - if (user != null) { - - // raise an error if the application is locked and the user does not have system administrator privileges - if (AppUtils.isApplicationLocked() && !UserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) { - bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED); - } - - // raise an error if the user is inactive - if (!user.getActive()) { - bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE); - } - - // raise an error if no active roles exist for the user -// boolean hasActiveRole = false; -// Iterator roles = user.getRoles().iterator(); -// while (roles.hasNext()) { -// Role role = (Role)roles.next(); -// if (role.getActive()) { -// hasActiveRole = true; -// break; -// } -// } - -// if (!hasActiveRole) { -// bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE); -// } - if (!userHasActiveRoles(user)) { - bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE); - } - // only login the user if no errors have occurred - if (bean.getLoginErrorMessage() == null) { - - // this will be a snapshot of the user's information as retrieved from the database - userCopy = (User)user.clone(); - - // update the last logged in date for the user - user.setLastLoginDate(new Date()); - getDataAccessService().saveDomainObject(user, additionalParams); - - // update the audit log of the user - //Check for the client device type and set log attributes appropriately - - - // save the above changes to the User and their audit trail - - // create the application menu based on the user's privileges - Set appMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME),dataAccessService); - bean.setMenu(appMenu != null?appMenu:new HashSet()); - Set businessDirectMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_SET_NAME),dataAccessService); - bean.setBusinessDirectMenu(businessDirectMenu != null?businessDirectMenu:new HashSet()); - - bean.setUser(userCopy); - } - - } - - return bean; - } - - private boolean userHasActiveRoles(User user) { - boolean hasActiveRole = false; - @SuppressWarnings("rawtypes") - Iterator roles = user.getRoles().iterator(); - while (roles.hasNext()) { - Role role = (Role)roles.next(); - if (role.getActive()) { - hasActiveRole = true; - break; - } - } - return hasActiveRole; - } + private MenuBuilder menuBuilder; - @SuppressWarnings("rawtypes") - public User findUser(String loginId, String password) { - List list = null; + @Autowired + private DataAccessService dataAccessService; - StringBuffer criteria = new StringBuffer(); - criteria.append(" where login_id = '").append(loginId).append("'") - .append(" and login_pwd = '").append(password).append("'"); - - list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + @Override + @SuppressWarnings("rawtypes") + public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams) { + return findUser(bean, menuPropertiesFilename, additionalParams, true); + } - return (list == null || list.size() == 0) ? null : (User)list.get(0); - } - - @SuppressWarnings("rawtypes") - private User findUserWithoutPwd(String loginId) { - List list = null; + @Override + @SuppressWarnings("rawtypes") + public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams, + boolean matchPassword) { + + User user; + if (bean.getUserid() != null && bean.getUserid() != null) { + user = findUser(bean); + } else { + if (matchPassword) + user = findUser(bean.getLoginId(), bean.getLoginPwd()); + else + user = findUserWithoutPwd(bean.getLoginId()); + } - StringBuffer criteria = new StringBuffer(); - criteria.append(" where login_id = '").append(loginId).append("'"); - - list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + if (user != null) { + + // raise an error if the application is locked and the user does not have system + // administrator privileges + if (AppUtils.isApplicationLocked() + && !UserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) { + bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED); + } + + // raise an error if the user is inactive + if (!user.getActive()) { + bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE); + } + + if (!userHasActiveRoles(user)) { + bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE); + } + // only login the user if no errors have occurred + if (bean.getLoginErrorMessage() == null) { + + // this will be a snapshot of the user's information as retrieved from the + // database + User userCopy = null; + try { + userCopy = (User) user.clone(); + } catch (CloneNotSupportedException ex) { + // Never happens + logger.error(EELFLoggerDelegate.errorLogger, "findUser failed", ex); + } + + // update the last logged in date for the user + user.setLastLoginDate(new Date()); + getDataAccessService().saveDomainObject(user, additionalParams); + + // update the audit log of the user + // Check for the client device type and set log attributes appropriately + + // save the above changes to the User and their audit trail + + // create the application menu based on the user's privileges + Set appMenu = getMenuBuilder().getMenu( + SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME), dataAccessService); + bean.setMenu(appMenu != null ? appMenu : new HashSet()); + Set businessDirectMenu = getMenuBuilder().getMenu( + SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_SET_NAME), + dataAccessService); + bean.setBusinessDirectMenu(businessDirectMenu != null ? businessDirectMenu : new HashSet()); + + bean.setUser(userCopy); + } - return (list == null || list.size() == 0) ? null : (User)list.get(0); - } + } - @SuppressWarnings("rawtypes") - public User findUser(LoginBean bean) { - List list = null; + return bean; + } - StringBuffer criteria = new StringBuffer(); - criteria.append(" where org_user_id = '").append(bean.getUserid()).append("'"); - - list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + private boolean userHasActiveRoles(User user) { + boolean hasActiveRole = false; + @SuppressWarnings("rawtypes") + Iterator roles = user.getRoles().iterator(); + while (roles.hasNext()) { + Role role = (Role) roles.next(); + if (role.getActive()) { + hasActiveRole = true; + break; + } + } + return hasActiveRole; + } - return (list == null || list.size() == 0) ? null : (User)list.get(0); - } + @SuppressWarnings("rawtypes") + public User findUser(String loginId, String password) { + StringBuilder criteria = new StringBuilder(); + criteria.append(" where login_id = '").append(loginId).append("'").append(" and login_pwd = '").append(password) + .append("'"); + List list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + return (list == null || list.isEmpty()) ? null : (User) list.get(0); + } + @SuppressWarnings("rawtypes") + private User findUserWithoutPwd(String loginId) { + StringBuilder criteria = new StringBuilder(); + criteria.append(" where login_id = '").append(loginId).append("'"); + List list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + return (list == null || list.isEmpty()) ? null : (User) list.get(0); + } - public MenuBuilder getMenuBuilder() { - return new MenuBuilder(); - } + @SuppressWarnings("rawtypes") + public User findUser(LoginBean bean) { + StringBuilder criteria = new StringBuilder(); + criteria.append(" where org_user_id = '").append(bean.getUserid()).append("'"); + List list = getDataAccessService().getList(User.class, criteria.toString(), null, null); + return (list == null || list.isEmpty()) ? null : (User) list.get(0); + } + public MenuBuilder getMenuBuilder() { + return new MenuBuilder(); + } - public void setMenuBuilder(MenuBuilder menuBuilder) { - this.menuBuilder = menuBuilder; - } + public void setMenuBuilder(MenuBuilder menuBuilder) { + this.menuBuilder = menuBuilder; + } - - public DataAccessService getDataAccessService() { + public DataAccessService getDataAccessService() { return dataAccessService; } - public void setDataAccessService(DataAccessService dataAccessService) { this.dataAccessService = dataAccessService; } - } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsService.java index b299f021..831b2734 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -44,9 +44,9 @@ import org.onap.portalsdk.core.command.PostDroolsBean; public interface PostDroolsService { String execute(String droolsFile, String className, String selectedRules); - + List fetchDroolBeans(); - + String retrieveClass(String droolsFile); - + } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsServiceImpl.java index 1d5d9cc9..faa15329 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostDroolsServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,8 +38,6 @@ package org.onap.portalsdk.core.service; import java.io.File; -import java.io.IOException; -import java.nio.file.DirectoryIteratorException; import java.nio.file.DirectoryStream; import java.nio.file.FileSystems; import java.nio.file.Files; @@ -65,14 +63,10 @@ import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.databind.ObjectMapper; -/** - * TODO REFACTOR - * - */ @Service("postDroolsService") @Transactional -public class PostDroolsServiceImpl implements PostDroolsService{ - +public class PostDroolsServiceImpl implements PostDroolsService { + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostDroolsServiceImpl.class); @Override @@ -82,29 +76,26 @@ public class PostDroolsServiceImpl implements PostDroolsService{ return resultsString; } - + @Override public List fetchDroolBeans() { - - List beanList = new ArrayList(); + + List beanList = new ArrayList<>(); Path path = FileSystems.getDefault().getPath(SystemProperties.getProperty(SystemProperties.FILES_PATH)); - try (DirectoryStream stream = Files.newDirectoryStream(path,"*.{drl}")) { - for (Path entry: stream) { - - PostDroolsBean postDroolsBean = new PostDroolsBean(); - String fileName = entry.getName(entry.getNameCount()-1).toString(); - postDroolsBean.setDroolsFile(fileName);//sample populated + try (DirectoryStream stream = Files.newDirectoryStream(path, "*.{drl}")) { + for (Path entry : stream) { + + PostDroolsBean postDroolsBean = new PostDroolsBean(); + String fileName = entry.getName(entry.getNameCount() - 1).toString(); + postDroolsBean.setDroolsFile(fileName);// sample populated postDroolsBean.setClassName(retrieveClass(fileName)); - //postDroolsBean.setSelectedRules("[\"NJ\",\"NY\",\"KY\"]"); beanList.add(postDroolsBean); - } - } catch (DirectoryIteratorException ex) { - logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage()); - } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + } + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "fetchDroolBeans failed", ex); } - return beanList; + return beanList; } - + @Override public String retrieveClass(String fileName) { String resultsString = ""; @@ -113,51 +104,43 @@ public class PostDroolsServiceImpl implements PostDroolsService{ final KnowledgeBuilder kbuilder = loadKBuilder(fileName); final Collection pkgs = kbuilder.getKnowledgePackages(); return pkgs.iterator().next().getFactTypes().iterator().next().getFactClass().getName(); - + } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "retrieveClass failed", e); } - + return resultsString; } - + protected static KnowledgeBuilder loadKBuilder(String fileName) { final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); // this will parse and compile in one step - kbuilder.add(ResourceFactory.newFileResource(SystemProperties.getProperty(SystemProperties.FILES_PATH) + File.separator + fileName), - //kbuilder.add(ResourceFactory.newClassPathResource(SystemProperties.getProperty(SystemProperties.FILES_PATH) + File.separator + drl_file_path, DroolsRuleService.class), + kbuilder.add( + ResourceFactory.newFileResource( + SystemProperties.getProperty(SystemProperties.FILES_PATH) + File.separator + fileName), ResourceType.DRL); - // kbuilder.add(ResourceFactory.newClassPathResource("rules.drl",DroolsRuleService.class), - // ResourceType.DRL); // Check the builder for errors if (kbuilder.hasErrors()) { - logger.error(EELFLoggerDelegate.errorLogger, kbuilder.getErrors().toString()); - - throw new RuntimeException("Unable to compile \".drl\"."); - + throw new IllegalArgumentException("Unable to compile \".drl\"."); } return kbuilder; } - @SuppressWarnings({ "deprecation", "unchecked" }) public static String executeDemoRules(String fileName, String className, String ruleValue) { String resultsString = ""; try { // load up the knowledge base - // KieServices ks = KieServices.Factory.get(); - // KieContainer kContainer = ks.getKieClasspathContainer(); - // KieSession kSession = kContainer.newKieSession("ksession-rules"); final KnowledgeBuilder kbuilder = loadKBuilder(fileName); // get the compiled packages (which are serializable) final Collection pkgs = kbuilder.getKnowledgePackages(); - + // add the packages to a knowledgebase (deploy the knowledge // packages). @@ -168,37 +151,29 @@ public class PostDroolsServiceImpl implements PostDroolsService{ final StatefulKnowledgeSession kSession = kbase.newStatefulKnowledgeSession(); ObjectMapper mapper = new ObjectMapper(); - if(ruleValue == null || ruleValue.equals("")) { + if (ruleValue == null || "".equals(ruleValue)) { resultsString = "Please enter valid rule"; return resultsString; } List selectedRules = mapper.readValue(ruleValue, List.class); - List ruleResponse = new ArrayList(); - - for(String rule : selectedRules){ + List ruleResponse = new ArrayList<>(); + + for (String rule : selectedRules) { Class clazz = (Class) Class.forName(className); - DroolsRuleService droolsIntroduction =clazz.newInstance(); + DroolsRuleService droolsIntroduction = clazz.newInstance(); droolsIntroduction.init(rule); kSession.insert(droolsIntroduction); kSession.fireAllRules(); ruleResponse.add(droolsIntroduction.getResultsString()); } - + resultsString = mapper.writeValueAsString(ruleResponse); - -// kSession.insert(new DroolsRuleService("KY")); -// kSession.fireAllRules(); -// -// kSession.setGlobal("age", "25"); -// kSession.insert(new DroolsRuleService("NY")); -// kSession.fireAllRules(); + } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "executeDemoRules failed", e); } - + return resultsString; } - - } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchService.java index 91d21776..248fdbfb 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchServiceImpl.java index e799e313..4bf78eed 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/PostSearchServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileService.java index 2ee612a6..b2831c5b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,42 +37,42 @@ */ package org.onap.portalsdk.core.service; +import java.io.IOException; import java.util.List; import org.onap.portalsdk.core.domain.Profile; import org.onap.portalsdk.core.domain.User; - public interface ProfileService { - + /** * * @return returns list of profiles - * @throws Exception + * @throws IOException */ - List findAll() throws Exception; - + List findAll() throws IOException; + /** * * @param id * @return returns profile of requested ID - * @throws Exception + * @throws IOException */ - Profile getProfile(int id) throws Exception; - - + Profile getProfile(int id) throws IOException; + /** * - * @param id loginId + * @param id + * loginId * @return returns User info of requested ID - * @throws Exception + * @throws IOException */ - User getUser(String id) throws Exception; - + User getUser(String id) throws IOException; + /** * * @param user - *saveUser method saves the user object + * saveUser method saves the user object */ void saveUser(User user); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceCentralizedImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceCentralizedImpl.java index 91661e61..6503dd34 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceCentralizedImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceCentralizedImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,27 +37,25 @@ */ package org.onap.portalsdk.core.service; +import java.io.IOException; import java.util.List; import org.onap.portalsdk.core.domain.Profile; import org.onap.portalsdk.core.domain.User; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.databind.ObjectMapper; @Transactional -public class ProfileServiceCentralizedImpl implements ProfileService{ - - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProfileServiceCentralizedImpl.class); - +public class ProfileServiceCentralizedImpl implements ProfileService { + @Autowired - AppService appService; - + private DataAccessService dataAccessService; + @Autowired - private DataAccessService dataAccessService; - + private RestApiRequestBuilder restApiRequestBuilder; + public DataAccessService getDataAccessService() { return dataAccessService; } @@ -66,40 +64,30 @@ public class ProfileServiceCentralizedImpl implements ProfileService{ this.dataAccessService = dataAccessService; } - @Autowired - RestApiRequestBuilder restApiRequestBuilder ; - @SuppressWarnings("unchecked") @Override - public List findAll() throws Exception{ + public List findAll() throws IOException { return getDataAccessService().getList(Profile.class, null); } @Override - public Profile getProfile(int id) throws Exception{ + public Profile getProfile(int id) throws IOException { ObjectMapper mapper = new ObjectMapper(); - Profile user = null; - String responseString = restApiRequestBuilder.getViaREST("/getProfile/" + id, true,Integer.toString(id)); - user = mapper.readValue(responseString, Profile.class); - return user; + String responseString = restApiRequestBuilder.getViaREST("/getProfile/" + id, true, Integer.toString(id)); + Profile profile = mapper.readValue(responseString, Profile.class); + return profile; } @Override - public User getUser(String id) throws Exception{ + public User getUser(String id) throws IOException { ObjectMapper mapper = new ObjectMapper(); - User user = new User(); - String responseString =restApiRequestBuilder.getViaREST("/user/" + id, true,id); - user = mapper.readValue(responseString, User.class); - + String responseString = restApiRequestBuilder.getViaREST("/user/" + id, true, id); + User user = mapper.readValue(responseString, User.class); return user; } @Override public void saveUser(User user) { - try { - getDataAccessService().saveDomainObject(user, null); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "saveUser failed", e); - } - } + getDataAccessService().saveDomainObject(user, null); + } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceImpl.java index ac7c2d01..20b14eb6 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/ProfileServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -46,44 +46,41 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @Transactional -public class ProfileServiceImpl implements ProfileService{ +public class ProfileServiceImpl implements ProfileService { @Autowired private ProfileDao profileDao; - + @Autowired private DataAccessService dataAccessService; - + + @Override @SuppressWarnings("unchecked") public List findAll() { - //List msgDB = getDataAccessService().getList(Profile.class, null); return getDataAccessService().getList(Profile.class, null); } - - public User getUser(String userId){ + + @Override + public User getUser(String userId) { return (User) getDataAccessService().getDomainObject(User.class, Long.parseLong(userId), null); } - - public void saveUser(User user){ - + + @Override + public void saveUser(User user) { getDataAccessService().saveDomainObject(user, null); } - - + + @Override public Profile getProfile(int id) { return profileDao.getProfile(id); } - public DataAccessService getDataAccessService() { return dataAccessService; } - public void setDataAccessService(DataAccessService dataAccessService) { this.dataAccessService = dataAccessService; } - - } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RestApiRequestBuilder.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RestApiRequestBuilder.java index 5870dc29..c6c40b70 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RestApiRequestBuilder.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RestApiRequestBuilder.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -54,11 +54,11 @@ public class RestApiRequestBuilder { private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestApiRequestBuilder.class); + private static final String APPLICATION_JSON = "application/json"; + @Autowired private AppService appService; - private static final String content_type = "application/json"; - /** * * @param restEndPoint @@ -69,9 +69,9 @@ public class RestApiRequestBuilder { */ public String getViaREST(String restEndPoint, boolean isBasicAuth, String userId) throws IOException { logger.info(EELFLoggerDelegate.debugLogger, "getViaRest: endpoint {}", restEndPoint); - String appName = ""; - String appUserName = ""; - String decryptedPwd = ""; + String appName; + String appUserName; + String decryptedPwd = null; App app = appService.getDefaultApp(); if (app != null) { appName = app.getName(); @@ -81,12 +81,13 @@ public class RestApiRequestBuilder { SystemProperties.getProperty(SystemProperties.Decryption_Key)); } catch (CipherUtilException e) { logger.error(EELFLoggerDelegate.errorLogger, "getViaREST failed", e); - throw new IOException(e.toString()); + throw new IOException("getViaREST failed", e); } } else { logger.warn(EELFLoggerDelegate.errorLogger, "getViaREST: Unable to locate the app information from the database."); appName = SystemProperties.SDK_NAME; + appUserName = "unknown"; } String requestId = MDC.get(MDC_KEY_REQUEST_ID); String response = RestWebServiceClient.getInstance().getPortalContent(restEndPoint, userId, appName, requestId, @@ -106,9 +107,9 @@ public class RestApiRequestBuilder { public void postViaREST(String restEndPoint, boolean isBasicAuth, String content, String userId) throws IOException { logger.info(EELFLoggerDelegate.debugLogger, "postViaRest: endpoint {}", restEndPoint); - String appName = ""; - String appUserName = ""; - String decryptedPwd = ""; + String appName; + String appUserName; + String decryptedPwd = null; App app = appService.getDefaultApp(); if (app != null) { appName = app.getName(); @@ -118,16 +119,17 @@ public class RestApiRequestBuilder { SystemProperties.getProperty(SystemProperties.Decryption_Key)); } catch (CipherUtilException e) { logger.error(EELFLoggerDelegate.errorLogger, "postViaREST failed", e); - throw new IOException(e.toString()); + throw new IOException("postViaREST failed", e); } } else { logger.warn(EELFLoggerDelegate.errorLogger, "postViaRest: Unable to locate the app information from the database."); appName = SystemProperties.SDK_NAME; + appUserName = "unknown"; } String requestId = MDC.get(MDC_KEY_REQUEST_ID); String response = RestWebServiceClient.getInstance().postPortalContent(restEndPoint, userId, appName, requestId, - appUserName, decryptedPwd, content_type, content, isBasicAuth); + appUserName, decryptedPwd, APPLICATION_JSON, content, isBasicAuth); logger.debug(EELFLoggerDelegate.debugLogger, "postViaRest response: {}", response); } @@ -142,9 +144,9 @@ public class RestApiRequestBuilder { public void deleteViaRest(String restEndPoint, boolean isBasicAuth, String content, String userId) throws IOException { logger.info(EELFLoggerDelegate.debugLogger, "deleteViaRest: endpoint {}", restEndPoint); - String appName = ""; - String appUserName = ""; - String decryptedPwd = ""; + String appName; + String appUserName; + String decryptedPwd = null; App app = appService.getDefaultApp(); if (app != null) { appName = app.getName(); @@ -153,17 +155,18 @@ public class RestApiRequestBuilder { decryptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key)); } catch (CipherUtilException e) { - logger.error(EELFLoggerDelegate.errorLogger, "postViaREST failed", e); - throw new IOException(e.toString()); + logger.error(EELFLoggerDelegate.errorLogger, "deleteViaRest failed", e); + throw new IOException("deleteViaRest failed", e); } } else { logger.warn(EELFLoggerDelegate.errorLogger, "deleteViaRest: Unable to locate the app information from the database."); appName = SystemProperties.SDK_NAME; + appUserName = "unknown"; } String requestId = MDC.get(MDC_KEY_REQUEST_ID); String response = RestWebServiceClient.getInstance().deletePortalContent(restEndPoint, userId, appName, - requestId, appUserName, decryptedPwd, content_type, content, isBasicAuth); + requestId, appUserName, decryptedPwd, APPLICATION_JSON, content, isBasicAuth); logger.debug(EELFLoggerDelegate.debugLogger, "deleteViaRest response: {}", response); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleService.java index 12c9d59e..b0730859 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,111 +37,118 @@ */ package org.onap.portalsdk.core.service; +import java.io.IOException; import java.util.List; import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.domain.RoleFunction; - public interface RoleService { /** + * returns list of Role Functions * - * @param requestedLoginId loginId + * @param requestedLoginId + * loginId * @return returns List of RoleFunction - * @throws Exception - * Method getRoleFunctions returns list of Role Functions + * @throws IOException */ - List getRoleFunctions(String requestedLoginId) throws Exception; - - + List getRoleFunctions(String requestedLoginId) throws IOException; + /** + * returns list of avialable child roles * * @param requestedLoginId * @param roleId * @return returns List of Role - * @throws Exception - * Method getAvailableChildRoles returns list of avialable child roles + * @throws IOException */ - List getAvailableChildRoles(String requestedLoginId,Long roleId) throws Exception; - - + List getAvailableChildRoles(String requestedLoginId, Long roleId) throws IOException; + /** + * returns Role object with requested roleID * * @param requestedLoginId - * @param id roleId - * @return returns role - * @throws Exception - * Method getRole returns Role object if requested roleID + * @param id + * roleId + * @return returns role + * @throws IOException */ - Role getRole(String requestedLoginId,Long id) throws Exception; - + Role getRole(String requestedLoginId, Long id) throws IOException; + /** + * saves the Role Object * * @param requestedLoginId - * @param domainRole Object to be saved - * Method saveRole saves the Role Object + * @param domainRole + * Object to be saved + * @throws IOException */ - void saveRole(String requestedLoginId,Role domainRole) throws Exception; - + void saveRole(String requestedLoginId, Role domainRole) throws IOException; + /** + * + * deletes the requested Role Object * * @param requestedLoginId - * @param domainRole Object to be removed - * Method deleteRole deletes the requested Role Object + * @param domainRole + * Object to be removed + * @throws IOException */ - void deleteRole(String requestedLoginId,Role domainRole) throws Exception; - + void deleteRole(String requestedLoginId, Role domainRole) throws IOException; + /** + * gets the list of available roles * * @param requestedLoginId * @return returns list of available roles - * @throws Exception - * Method getAvailableRoles gets the list of available roles + * @throws IOException */ - - List getAvailableRoles(String requestedLoginId) throws Exception; - + List getAvailableRoles(String requestedLoginId) throws IOException; + /** + * gets the list of active roles of application * * @param requestedLoginId * @return List of active roles - * @throws Exception - * Method getActiveRoles gets the list of active roles of application - * + * @throws IOException */ - List getActiveRoles(String requestedLoginId) throws Exception; + List getActiveRoles(String requestedLoginId) throws IOException; /** + * returns RoleFunction of requested function code * * @param requestedLoginId - * @param code function code + * @param code + * function code * @return RoleFunction of requested function code - * @throws Exception - * Method getRoleFunction returns RoleFunction of requested function code + * @throws IOException */ - RoleFunction getRoleFunction(String requestedLoginId,String code) throws Exception; - + RoleFunction getRoleFunction(String requestedLoginId, String code) throws IOException; + /** + * saves the requested RoleFunction object * * @param requestedLoginId * @param domainRoleFunction - * Method saveRoleFunction saves the requested RoleFunction object + * @throws IOException */ - void saveRoleFunction(String requestedLoginId,RoleFunction domainRoleFunction) throws Exception; - + void saveRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws IOException; + /** + * deletes the requested RoleFunction object * * @param requestedLoginId * @param domainRoleFunction - * Method deleteRoleFunction deletes the requested RoleFunction object + * @throws IOException */ - void deleteRoleFunction(String requestedLoginId,RoleFunction domainRoleFunction) throws Exception; - + void deleteRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws IOException; + /** + * deletes the requested object * * @param requestedLoginId * @param id - * Method deleteDependcyRoleRecord deletes the requested object + * @throws IOException */ - void deleteDependcyRoleRecord(String requestedLoginId,Long id); + void deleteDependcyRoleRecord(String requestedLoginId, Long id) throws IOException; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceCentralizedAccess.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceCentralizedAccess.java index 13da750c..3ef7cb8b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceCentralizedAccess.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceCentralizedAccess.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,6 +37,7 @@ */ package org.onap.portalsdk.core.service; +import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.List; @@ -61,26 +62,23 @@ public class RoleServiceCentralizedAccess implements RoleService { private RestApiRequestBuilder restApiRequestBuilder; @Override - public List getRoleFunctions(String loginId) throws Exception { - - List roleFunctionList = null; - String role_function_list = ""; - role_function_list = restApiRequestBuilder.getViaREST("/functions", true, loginId); + public List getRoleFunctions(String loginId) throws IOException { + String roleFunctionString = restApiRequestBuilder.getViaREST("/functions", true, loginId); ObjectMapper mapper = new ObjectMapper(); - roleFunctionList = mapper.readValue(role_function_list, + List roleFunctionList = mapper.readValue(roleFunctionString, TypeFactory.defaultInstance().constructCollectionType(List.class, RoleFunction.class)); return roleFunctionList; } @Override - public List getAvailableChildRoles(String loginId, Long roleId) throws Exception { + public List getAvailableChildRoles(String loginId, Long roleId) throws IOException { List availableChildRoles = getAvailableRoles(loginId); if (roleId == null || roleId == 0) { return availableChildRoles; } Role currentRole = getRole(loginId, roleId); - Set allParentRoles = new TreeSet(); + Set allParentRoles = new TreeSet<>(); allParentRoles = getAllParentRolesAsList(loginId, currentRole, allParentRoles); Iterator availableChildRolesIterator = availableChildRoles.iterator(); @@ -105,11 +103,10 @@ public class RoleServiceCentralizedAccess implements RoleService { } @Override - public Role getRole(String loginId, Long id) throws Exception { + public Role getRole(String loginId, Long id) throws IOException { ObjectMapper mapper = new ObjectMapper(); String roleString = restApiRequestBuilder.getViaREST("/role/" + id, true, loginId); - Role role = new Role(); - role = mapper.readValue(roleString, Role.class); + Role role = mapper.readValue(roleString, Role.class); if (role.getRoleFunctions() != null) { @SuppressWarnings("unchecked") Set roleFunctionList = role.getRoleFunctions(); @@ -129,50 +126,38 @@ public class RoleServiceCentralizedAccess implements RoleService { } @Override - public void saveRole(String loginId, Role domainRole) throws Exception { + public void saveRole(String loginId, Role domainRole) throws IOException { ObjectMapper mapper = new ObjectMapper(); String role = mapper.writeValueAsString(domainRole); - try { - restApiRequestBuilder.postViaREST("/role", true, role, loginId); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "saveRole Failed", e); - throw new Exception(e.getMessage()); - } + restApiRequestBuilder.postViaREST("/role", true, role, loginId); } @Override - public void deleteRole(String loginId, Role domainRole) throws Exception { + public void deleteRole(String loginId, Role domainRole) throws IOException { String roleName = domainRole.getName().replaceAll(" ", "%20"); - try { - restApiRequestBuilder.deleteViaRest("/deleteRole/"+ roleName, true, null, loginId); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteRole Failed", e); - throw new Exception(e.getMessage()); - } + restApiRequestBuilder.deleteViaRest("/deleteRole/" + roleName, true, null, loginId); } + @Override - public List getAvailableRoles(String requestedLoginId) throws Exception { + public List getAvailableRoles(String requestedLoginId) throws IOException { ObjectMapper mapper = new ObjectMapper(); String roleList = restApiRequestBuilder.getViaREST("/roles", true, requestedLoginId); - List roles = null; - roles = mapper.readValue(roleList, + List roles = mapper.readValue(roleList, TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class)); return roles; } @Override - public List getActiveRoles(String requestedLoginId) throws Exception { + public List getActiveRoles(String requestedLoginId) throws IOException { ObjectMapper mapper = new ObjectMapper(); String roleString = restApiRequestBuilder.getViaREST("/activeRoles", true, requestedLoginId); - List roles = null; - roles = mapper.readValue(roleString, + List roles = mapper.readValue(roleString, TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class)); return roles; - } @Override - public RoleFunction getRoleFunction(String requestedLoginId, String code) throws Exception { + public RoleFunction getRoleFunction(String requestedLoginId, String code) throws IOException { ObjectMapper mapper = new ObjectMapper(); String responseString = restApiRequestBuilder.getViaREST("/function/" + code, true, requestedLoginId); RoleFunction roleFunction = new RoleFunction(); @@ -183,35 +168,21 @@ public class RoleServiceCentralizedAccess implements RoleService { } @Override - public void saveRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws Exception { + public void saveRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws IOException { ObjectMapper mapper = new ObjectMapper(); String roleFunction = mapper.writeValueAsString(domainRoleFunction); - try{ restApiRequestBuilder.postViaREST("/roleFunction", true, roleFunction, requestedLoginId); - }catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction Failed", e); - throw new Exception(e.getMessage()); - } } @Override - public void deleteRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws Exception { + public void deleteRoleFunction(String requestedLoginId, RoleFunction domainRoleFunction) throws IOException { String code = domainRoleFunction.getCode(); - try { - restApiRequestBuilder.deleteViaRest("/roleFunction/"+ code, true, null, requestedLoginId); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction Failed ", e); - throw new Exception(e.getMessage()); - } + restApiRequestBuilder.deleteViaRest("/roleFunction/" + code, true, null, requestedLoginId); } @Override - public void deleteDependcyRoleRecord(String requestedLoginId, Long id) { - try { - restApiRequestBuilder.deleteViaRest("/deleteDependcyRoleRecord/" + id, true, null, requestedLoginId); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord Failed", e); - } + public void deleteDependcyRoleRecord(String requestedLoginId, Long id) throws IOException { + restApiRequestBuilder.deleteViaRest("/deleteDependcyRoleRecord/" + id, true, null, requestedLoginId); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceImpl.java index abf785a0..e0e2d2e3 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/RoleServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -61,7 +61,7 @@ public class RoleServiceImpl implements RoleService { @Autowired private DataAccessService dataAccessService; - DataSource dataSource; + private DataSource dataSource; public DataSource getDataSource() { return dataSource; @@ -72,22 +72,23 @@ public class RoleServiceImpl implements RoleService { this.dataSource = dataSource; } + @Override @SuppressWarnings("unchecked") public List getRoleFunctions(String loginId) { - // List msgDB = getDataAccessService().getList(Profile.class, null); return getDataAccessService().getList(RoleFunction.class, null); } + @Override @SuppressWarnings("unchecked") - public List getAvailableChildRoles(String loginId,Long roleId) { + public List getAvailableChildRoles(String loginId, Long roleId) { List availableChildRoles = (List) getDataAccessService().getList(Role.class, null); if (roleId == null || roleId == 0) { return availableChildRoles; } Role currentRole = (Role) getDataAccessService().getDomainObject(Role.class, roleId, null); - Set allParentRoles = new TreeSet(); - allParentRoles = getAllParentRolesAsList(loginId,currentRole, allParentRoles); + Set allParentRoles = new TreeSet<>(); + allParentRoles = getAllParentRolesAsList(loginId, currentRole, allParentRoles); Iterator availableChildRolesIterator = availableChildRoles.iterator(); while (availableChildRolesIterator.hasNext()) { @@ -100,47 +101,54 @@ public class RoleServiceImpl implements RoleService { } @SuppressWarnings("unchecked") - private Set getAllParentRolesAsList(String loginId,Role role, Set allParentRoles) { + private Set getAllParentRolesAsList(String loginId, Role role, Set allParentRoles) { Set parentRoles = role.getParentRoles(); allParentRoles.addAll(parentRoles); Iterator parentRolesIterator = parentRoles.iterator(); while (parentRolesIterator.hasNext()) { - getAllParentRolesAsList( loginId,parentRolesIterator.next(), allParentRoles); + getAllParentRolesAsList(loginId, parentRolesIterator.next(), allParentRoles); } return allParentRoles; } - public RoleFunction getRoleFunction(String loginId,String code) { + @Override + public RoleFunction getRoleFunction(String loginId, String code) { return (RoleFunction) getDataAccessService().getDomainObject(RoleFunction.class, code, null); } - public void saveRoleFunction(String loginId,RoleFunction domainRoleFunction) { + @Override + public void saveRoleFunction(String loginId, RoleFunction domainRoleFunction) { getDataAccessService().saveDomainObject(domainRoleFunction, null); } - public void deleteRoleFunction(String loginId,RoleFunction domainRoleFunction) { + @Override + public void deleteRoleFunction(String loginId, RoleFunction domainRoleFunction) { getDataAccessService().deleteDomainObject(domainRoleFunction, null); } - public Role getRole(String loginId,Long id) { + @Override + public Role getRole(String loginId, Long id) { return (Role) getDataAccessService().getDomainObject(Role.class, id, null); } - public void saveRole(String loginId,Role domainRole) { + @Override + public void saveRole(String loginId, Role domainRole) { getDataAccessService().saveDomainObject(domainRole, null); } - public void deleteRole(String loginId,Role domainRole) { + @Override + public void deleteRole(String loginId, Role domainRole) { getDataAccessService().deleteDomainObject(domainRole, null); } + @Override @SuppressWarnings("unchecked") public List getAvailableRoles(String loginId) { return getDataAccessService().getList(Role.class, null); } - @SuppressWarnings("unchecked") @Override + @SuppressWarnings("unchecked") public List getActiveRoles(String loginId) { String filter = " where active_yn = 'Y' "; return getDataAccessService().getList(Role.class, filter, null, null); @@ -155,7 +163,7 @@ public class RoleServiceImpl implements RoleService { } @Override - public void deleteDependcyRoleRecord(String loginId,Long id) { + public void deleteDependcyRoleRecord(String loginId, Long id) { Connection conn = null; Statement stmt = null; try { @@ -163,22 +171,16 @@ public class RoleServiceImpl implements RoleService { stmt = conn.createStatement(); String sql = "delete from fn_user_role where role_id = '" + id + "'"; stmt.executeUpdate(sql); - stmt.close(); - conn.close(); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", e); } finally { try { if (stmt != null) stmt.close(); - } catch (SQLException se2) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", se2); - } - try { if (conn != null) conn.close(); } catch (SQLException se) { - logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", se); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed to close", se); } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessImpl.java index 2a9718a6..4dde6116 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -64,11 +64,10 @@ public class UrlAccessImpl implements UrlAccessService { List list = dataAccessService.executeNamedQuery("restrictedUrls", params, null); // loop through the list of restricted URL's - if (list != null && list.size() > 0) { + if (list != null && !list.isEmpty()) { for (int i = 0; i < list.size(); i++) { UrlsAccessible urlFunctions = (UrlsAccessible) list.get(i); - // String url = (String) urlFunctions.getUrl(); - String functionCd = (String) urlFunctions.getFunctionCd(); + String functionCd = urlFunctions.getFunctionCd(); if (UserUtils.isAccessible(request, functionCd)) { isAccessible = true; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessService.java index 7b915854..106dcb1b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UrlAccessService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,7 +40,7 @@ package org.onap.portalsdk.core.service; import javax.servlet.http.HttpServletRequest; public interface UrlAccessService { - + /** * Answers whether the specified URL is accessible. * @@ -48,5 +48,5 @@ public interface UrlAccessService { * @param currentUrl * @return true if yes, false if no. */ - public boolean isUrlAccessible(HttpServletRequest request, String currentUrl); + public boolean isUrlAccessible(HttpServletRequest request, String currentUrl); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileService.java index a7537959..c9dfae12 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -41,11 +41,14 @@ import java.util.List; import org.onap.portalsdk.core.domain.User; - public interface UserProfileService { List findAll(); + User getUserByLoginId(String loginId); + void saveUser(User user); + public List findAllUserWithOnOffline(String originOrgUserId); + List findAllActive(); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileServiceImpl.java index 5a123393..184ec85b 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserProfileServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -38,9 +38,9 @@ package org.onap.portalsdk.core.service; import java.util.ArrayList; -import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Set; import java.util.SortedSet; import org.hibernate.criterion.Criterion; @@ -54,75 +54,78 @@ import org.springframework.transaction.annotation.Transactional; @Service("userProfile") @Transactional -public class UserProfileServiceImpl implements UserProfileService{ +public class UserProfileServiceImpl implements UserProfileService { - @Autowired - private DataAccessService dataAccessService; - + private DataAccessService dataAccessService; + + @Override @SuppressWarnings("unchecked") public List findAll() { return getDataAccessService().getList(User.class, null); } - + + @Override @SuppressWarnings("unchecked") - public User getUserByLoginId(String loginId){ - User user=null; + public User getUserByLoginId(String loginId) { + User user = null; List restrictionsList = new ArrayList(); - Criterion criterion1= Restrictions.eq("loginId",loginId); + Criterion criterion1 = Restrictions.eq("loginId", loginId); restrictionsList.add(criterion1); - List users = (List) getDataAccessService().getList(User.class,null, restrictionsList, null); - if(users!=null && users.size()==1) + List users = (List) getDataAccessService().getList(User.class, null, restrictionsList, null); + if (users != null && users.size() == 1) user = users.get(0); return user; } - - public void saveUser(User user){ - + + @Override + public void saveUser(User user) { getDataAccessService().saveDomainObject(user, null); } - + public DataAccessService getDataAccessService() { return dataAccessService; } - public void setDataAccessService(DataAccessService dataAccessService) { this.dataAccessService = dataAccessService; } - + + @Override @SuppressWarnings("unchecked") public List findAllUserWithOnOffline(String originOrgUserId) { - HashSet onlineUser = CollaborateList.getInstance().getAllUserName(); - List users = getDataAccessService().getList(User.class, null); - for(User u:users){ - if(onlineUser.contains(u.getOrgUserId())) + Set onlineUser = CollaborateList.getInstance().getAllUserName(); + List users = getDataAccessService().getList(User.class, null); + for (User u : users) { + if (onlineUser.contains(u.getOrgUserId())) u.setOnline(true); - if(u.getOrgUserId()!=null){ - if(originOrgUserId.compareTo(u.getOrgUserId()) > 0) { + if (u.getOrgUserId() != null) { + if (originOrgUserId.compareTo(u.getOrgUserId()) > 0) { u.setChatId(originOrgUserId + "-" + u.getOrgUserId()); - } else u.setChatId(u.getOrgUserId() + "-" + originOrgUserId ); + } else + u.setChatId(u.getOrgUserId() + "-" + originOrgUserId); } } return users; - + } - + + @Override public List findAllActive() { @SuppressWarnings("unchecked") - List users = getDataAccessService().getList(User.class, null); + List users = getDataAccessService().getList(User.class, null); Iterator itr = users.iterator(); - while(itr.hasNext()){ - User u = (User) itr.next(); - if(!u.getActive()) - itr.remove();//if not active remove user from list + while (itr.hasNext()) { + User u = itr.next(); + if (!u.getActive()) + itr.remove();// if not active remove user from list else { SortedSet roles = u.getRoles(); Iterator itrRoles = roles.iterator(); - while(itrRoles.hasNext()){ - Role role = (Role) itrRoles.next(); - if(!role.getActive()) - u.removeRole(role.getId());//if not active remove role from list + while (itrRoles.hasNext()) { + Role role = itrRoles.next(); + if (!role.getActive()) + u.removeRole(role.getId());// if not active remove role from list } } } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserService.java index 8a667462..1f6e240d 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -41,8 +41,6 @@ import java.io.IOException; import org.onap.portalsdk.core.domain.User; -import com.fasterxml.jackson.core.JsonProcessingException; - public interface UserService { /** @@ -61,7 +59,6 @@ public interface UserService { * @param response * @return User object * @throws IOException - * @throws JsonProcessingException */ - User userMapper(String response) throws IOException, JsonProcessingException; + User userMapper(String response) throws IOException; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceCentalizedImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceCentalizedImpl.java index 17735bd6..d1b05695 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceCentalizedImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceCentalizedImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -54,7 +54,6 @@ import org.onap.portalsdk.core.domain.UserApp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @Transactional @@ -94,7 +93,7 @@ public class UserServiceCentalizedImpl implements UserService { } @Override - public User userMapper(String res) throws IOException, JsonProcessingException { + public User userMapper(String res) throws IOException { ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(res, User.class); Set roleFunctionListNew = new HashSet<>(); @@ -108,9 +107,9 @@ public class UserServiceCentalizedImpl implements UserService { Role role = nextApp.getRole(); @SuppressWarnings("unchecked") Set roleFunctionList = role.getRoleFunctions(); - Iterator itetaror = roleFunctionList.iterator(); - while (itetaror.hasNext()) { - Object nextValue = itetaror.next(); + Iterator roleFnIter = roleFunctionList.iterator(); + while (roleFnIter.hasNext()) { + Object nextValue = roleFnIter.next(); RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class); roleFunctionListNew.add(roleFunction); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceImpl.java index d41499a0..0318020d 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/UserServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -45,13 +45,13 @@ import org.springframework.transaction.annotation.Transactional; public class UserServiceImpl implements UserService { @Autowired - private DataAccessService dataAccessService; - + private DataAccessService dataAccessService; + @Override public User getUser(String id) { return (User) dataAccessService.getDomainObject(User.class, Long.parseLong(id), null); } - + @Override public User userMapper(String response) { throw new UnsupportedOperationException("method cannot be used"); diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallService.java index 6db9cb86..23ff1f99 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,8 +37,9 @@ */ package org.onap.portalsdk.core.service; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; public interface WebServiceCallService { - public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword)throws Exception; - /*public String get(String restURL, String restPath);*/ + public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword) + throws CipherUtilException; } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallServiceImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallServiceImpl.java index f1a0cb28..71479820 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallServiceImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/WebServiceCallServiceImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -40,7 +40,7 @@ package org.onap.portalsdk.core.service; import java.util.List; import org.onap.portalsdk.core.domain.App; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; import org.onap.portalsdk.core.onboarding.util.CipherUtil; import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; @@ -49,159 +49,51 @@ import org.springframework.transaction.annotation.Transactional; @Service("webServiceCallService") @Transactional -public class WebServiceCallServiceImpl implements WebServiceCallService{ - - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebServiceCallServiceImpl.class); +public class WebServiceCallServiceImpl implements WebServiceCallService { @Autowired - private DataAccessService dataAccessService; - + private DataAccessService dataAccessService; + @Autowired private AppService appService; - + /** - * Verify REST Credential + * Verify REST Credential + * * @return true if the credential is accepted; else false. */ @Override - public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword)throws Exception { + public boolean verifyRESTCredential(String secretKey, String requestAppName, String requestPassword) + throws CipherUtilException { App app = appService.getDefaultApp(); - if (app!=null) { + if (app != null) { String encriptedPwdDB = app.getAppPassword(); String appUserName = app.getUsername(); - String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB, secretKey==null?SystemProperties.getProperty(SystemProperties.Decryption_Key):secretKey); - if(decreptedPwd.equals(requestPassword) && appUserName.equals(requestAppName)) { + String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB, + secretKey == null ? SystemProperties.getProperty(SystemProperties.Decryption_Key) : secretKey); + if (decreptedPwd.equals(requestPassword) && appUserName.equals(requestAppName)) { return true; } } return false; } - + /** * Getting App information from FN_APP table + * * @return App domain object, or null if not found. */ - public App findApp(){ - List list = null; - StringBuffer criteria = new StringBuffer(); - criteria.append(" where id = 1"); - list = getDataAccessService().getList(App.class, criteria.toString(), null, null); - return (list == null || list.size() == 0) ? null : (App) list.get(0); + public App findApp() { + List list = getDataAccessService().getList(App.class, " where id = 1", null, null); + return (list == null || list.isEmpty()) ? null : (App) list.get(0); } - + public DataAccessService getDataAccessService() { return dataAccessService; } - + public void setDataAccessService(DataAccessService dataAccessService) { this.dataAccessService = dataAccessService; } - /*/ - @Override - public String get(String restURL, String restPath) { - String appUserName = ""; - String appUebKey = ""; - String decreptedPwd = ""; - String appName = ""; - String inputLine = ""; - String serviceName = ""; - String loginId = ""; - StringBuffer jsonResponse = new StringBuffer(); - - StopWatch stopWatch = new StopWatch("WebServiceCallServiceImpl.get"); - stopWatch.start(); - try { - logger.info(EELFLoggerDelegate.metricsLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started."); - logger.debug(EELFLoggerDelegate.debugLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started."); - loginId = MDC.get("LoginId"); - appUebKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); - App app = appService.getDefaultApp(); - if (app!=null) { - appName = app.getName(); - appUserName = app.getUsername(); - try{ - decreptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key)); - } catch(Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: " + e.getMessage()); - } - } else { - logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database."); - appName = SystemProperties.SERVICE_NAME; - } - - //Create the connection object - URL obj = new URL(restURL + restPath); - HttpURLConnection con = (HttpURLConnection) obj.openConnection(); - con.setRequestMethod("GET"); - con.setConnectTimeout(3000); - con.setReadTimeout(8000); - - //add request header - con.setRequestProperty("username", appUserName); - con.setRequestProperty("password", decreptedPwd); - con.setRequestProperty("uebkey", appUebKey); - con.setRequestProperty(SystemProperties.LOGIN_ID, loginId); - con.setRequestProperty(SystemProperties.USERAGENT_NAME, appName); - con.setRequestProperty(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID)); - - //set MDC context for outgoing audit logging - serviceName = String.format("%s:%s.%s", appName, SystemProperties.ECOMP_PORTAL_BE, restPath); - MDC.put(Configuration.MDC_SERVICE_NAME, serviceName); - MDC.put(Configuration.MDC_REMOTE_HOST, restURL); - MDC.put(SystemProperties.MDC_APPNAME, appName); - MDC.put(SystemProperties.MDC_REST_PATH, restPath); - MDC.put(SystemProperties.MDC_REST_METHOD, "GET"); - - int responseCode = con.getResponseCode(); - logger.info(EELFLoggerDelegate.errorLogger, "Received the response code '" + responseCode + "' while getting the '" + restPath + "' for user: " + loginId); - - BufferedReader in = new BufferedReader( - new InputStreamReader(con.getInputStream())); - - while ((inputLine = in.readLine()) != null) { - jsonResponse.append(inputLine); - } - in.close(); - - logSecurityMessage(RESULT_ENUM.SUCCESS); - logger.debug(EELFLoggerDelegate.debugLogger, restPath + " response: " + jsonResponse.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is started."); - } catch(UrlAccessRestrictedException e) { - logger.error(EELFLoggerDelegate.errorLogger, "Authentication exception occurred in WebServiceCallServiceImpl.get (" + restPath + "). Details: " + e.getMessage()); - logSecurityMessage(RESULT_ENUM.FAILURE); - } catch(Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get (" + restPath + "). Details: " + e.getMessage()); - logSecurityMessage(RESULT_ENUM.FAILURE); - } finally { - if (stopWatch.isRunning()) stopWatch.stop(); - MDC.put(SystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms"); - logger.info(EELFLoggerDelegate.metricsLogger, "WebServiceCallServiceImpl.get (" + restPath + ") operation is completed."); - - //clear the temporary MDC context values - MDC.remove(SystemProperties.MDC_TIMER); - MDC.remove(SystemProperties.MDC_REST_METHOD); - MDC.remove(SystemProperties.MDC_REST_PATH); - MDC.remove(SystemProperties.MDC_APPNAME); - MDC.remove(Configuration.MDC_REMOTE_HOST); - MDC.remove(Configuration.MDC_SERVICE_NAME); - } - - return jsonResponse.toString(); - } - - //Handles all the outgoing rest/ueb messages. - public void logSecurityMessage(RESULT_ENUM isSuccess) { - String additionalInfo = ""; - String protocol = "HTTP"; - String loginId = MDC.get("LoginId"); - additionalInfo = String.format("Rest API=%s, Rest Method=%s, App-Name=%s, Request-URL=%s", - MDC.get(SystemProperties.MDC_REST_PATH), MDC.get(SystemProperties.MDC_REST_METHOD), - MDC.get(SystemProperties.MDC_APPNAME), MDC.get(Configuration.MDC_REMOTE_HOST)); - - logger.info(EELFLoggerDelegate.auditLogger, AuditLogFormatter.getInstance().createMessage( - protocol, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE.name(), loginId, SystemProperties.SERVICE_NAME, - isSuccess.name(), additionalInfo)); - } - /**/ } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/FusionService.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/FusionService.java index 601afc66..da043820 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/FusionService.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/FusionService.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -37,9 +37,8 @@ */ package org.onap.portalsdk.core.service.support; - import org.onap.portalsdk.core.FusionObject; public class FusionService implements FusionObject { - /** Logger for this class and subclasses */ + /** Logger for this class and subclasses */ } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocator.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocator.java index bcd55878..ef12d3db 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocator.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocator.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -39,7 +39,6 @@ package org.onap.portalsdk.core.service.support; import javax.naming.directory.DirContext; - public interface ServiceLocator { DirContext getDirContext(String initialContextFactory, String providerUrl, String securityPrincipal); } diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocatorImpl.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocatorImpl.java index b72d5d51..704cd39a 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocatorImpl.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/service/support/ServiceLocatorImpl.java @@ -6,7 +6,7 @@ * =================================================================== * * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the “License”); + * under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * @@ -19,7 +19,7 @@ * limitations under the License. * * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the “License”); + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * @@ -55,68 +55,58 @@ import org.springframework.stereotype.Service; @Service("serviceLocator") public class ServiceLocatorImpl implements ServiceLocator { - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ServiceLocatorImpl.class); + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ServiceLocatorImpl.class); - private Context context; // JNDI context (not currently in use) - private Context rootContext; // Java env root context (not currently in use) - private DirContext dirContext; // LDAP DIR context - private InitialLdapContext ldapContext; // LDAP context LDAPv3-style (not currently in use) + private Context context; // JNDI context (not currently in use) + private Context rootContext; // Java env root context (not currently in use) + private DirContext dirContext; // LDAP DIR context + private InitialLdapContext ldapContext; // LDAP context LDAPv3-style (not currently in use) + // cannot directly instantiate + public ServiceLocatorImpl() { + } - // cannot directly instantiate - public ServiceLocatorImpl() {} - - /*public static ServiceLocator getLocator() { - if (locator == null) - locator = new ServiceLocator(); - return locator; - } - - public Object clone() throws CloneNotSupportedException { - throw new CloneNotSupportedException(); - }*/ - - - // Get an LDAP directory context - public DirContext getDirContext(String initialContextFactory, String providerUrl, String securityPrincipal) { - - if (dirContext == null) { - - Properties properties = new Properties(); - properties.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); - properties.put(Context.PROVIDER_URL, providerUrl); - properties.put(Context.SECURITY_PRINCIPAL, securityPrincipal); - - try { - dirContext = new InitialDirContext(properties); - } - catch (NamingException ne) { - logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while creating an Initial Directory Context: " + ne.getMessage()); - logger.error(EELFLoggerDelegate.errorLogger, "Explanation: " + ne.getExplanation()); - } - } - - return dirContext; - } - - // Get an LDAP directory context - LDAPv3-style - /*public InitialLdapContext getLdapContext() { //throws NamingException { - if (ldapContext == null) { - Properties properties = new Properties(); - // @todo - need to parameterize context factoy class and url - properties.put(Context.INITIAL_CONTEXT_FACTORY, AttLdap.DIR_INITIAL_CONTEXT_FACTORY); - properties.put(Context.PROVIDER_URL, AttLdap.DIR_PROVIDER_URL); - properties.put(Context.SECURITY_PRINCIPAL, AttLdap.DIR_SECURITY_PRINCIPAL); - Control[] ctrl = null; - try { - ldapContext = new InitialLdapContext(properties, ctrl); - } - catch (NamingException ne) { - // MJ FIX log exception? - } + /* + * public static ServiceLocator getLocator() { if (locator == null) locator = + * new ServiceLocator(); return locator; } + * + * public Object clone() throws CloneNotSupportedException { throw new + * CloneNotSupportedException(); } + */ + + // Get an LDAP directory context + public DirContext getDirContext(String initialContextFactory, String providerUrl, String securityPrincipal) { + + if (dirContext == null) { + + Properties properties = new Properties(); + properties.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory); + properties.put(Context.PROVIDER_URL, providerUrl); + properties.put(Context.SECURITY_PRINCIPAL, securityPrincipal); + + try { + dirContext = new InitialDirContext(properties); + } catch (NamingException ne) { + logger.error(EELFLoggerDelegate.errorLogger, + "An error has occurred while creating an Initial Directory Context: " + ne.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, "Explanation: " + ne.getExplanation()); + } + } + + return dirContext; } - return ldapContext; - }*/ + // Get an LDAP directory context - LDAPv3-style + /* + * public InitialLdapContext getLdapContext() { //throws NamingException { if + * (ldapContext == null) { Properties properties = new Properties(); // @todo - + * need to parameterize context factoy class and url + * properties.put(Context.INITIAL_CONTEXT_FACTORY, + * AttLdap.DIR_INITIAL_CONTEXT_FACTORY); properties.put(Context.PROVIDER_URL, + * AttLdap.DIR_PROVIDER_URL); properties.put(Context.SECURITY_PRINCIPAL, + * AttLdap.DIR_SECURITY_PRINCIPAL); Control[] ctrl = null; try { ldapContext = + * new InitialLdapContext(properties, ctrl); } catch (NamingException ne) { // + * MJ FIX log exception? } } return ldapContext; } + */ } -- cgit 1.2.3-korg