diff options
author | talasila <talasila@research.att.com> | 2017-02-07 11:47:55 -0500 |
---|---|---|
committer | talasila <talasila@research.att.com> | 2017-02-07 12:51:32 -0500 |
commit | 1faf201e8608dfa4d7af3460fd3d1fc7ebec398b (patch) | |
tree | 2208f76271cc6b1a81dbfb9143cd7118b071a909 /ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller | |
parent | ca23569858b8cc9f60010e193b7041feb2d3227b (diff) |
Initial OpenECOMP Portal SDK commit
Change-Id: I66a3491600a4b9ea241128dc29267eed6a78ed76
Signed-off-by: talasila <talasila@research.att.com>
Diffstat (limited to 'ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller')
26 files changed, 4003 insertions, 0 deletions
diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/AdminAuthGenericController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/AdminAuthGenericController.java new file mode 100644 index 00000000..8a1f1d2c --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/AdminAuthGenericController.java @@ -0,0 +1,134 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; +/*package org.openecomp.portalsdk.core.controller; + +import java.io.IOException; +import java.util.List; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.onboarding.crossapi.IGenericRolesService; +import org.openecomp.portalsdk.core.onboarding.crossapi.IGenericUsersService; +import com.fasterxml.jackson.core.JsonProcessingException; + + +@RestController +@RequestMapping("/api") +public class AdminAuthGenericController extends RestrictedRESTfulBaseController { + protected final Log logger = LogFactory.getLog(getClass()); + @Autowired + IGenericUsersService genericUserService; + + @Autowired + IGenericRolesService genericRolesService; + + *//** + * RESTful service method to fetch available roles + * @return + *//* + @RequestMapping(value={"/roles"}, method = RequestMethod.GET, produces = "application/json") + public String getAvailableRoles() throws Exception{ + return genericRolesService.getAvailableRoles(); + } + + *//** + * RESTful service method to save user - expects user details in json string + * @param userJson + *//* + @RequestMapping(value={"/user"}, method = RequestMethod.POST) + public String pushUser(@RequestBody String userJson) throws Exception{ + return genericUserService.pushUser(userJson); + } + + *//** + * RESTful service method to edit user - expects user details in json string + * @param userJson + *//* + @RequestMapping(value={"/user/{loginId}"}, method = RequestMethod.POST) + public String editUser(@PathVariable("loginId") String loginId, @RequestBody String userJson) throws Exception{ + return genericUserService.editUser(loginId, userJson); + } + + *//** + * RESTful service method to save user role using user's login Id and details in role Json string + * @param loginId + * @param roleJson + * @throws JsonProcessingException + *//* + @RequestMapping(value={"/user/{loginId}/roles"}, method = RequestMethod.POST) + public String pushUserRole(@PathVariable("loginId") String loginId, @RequestBody String rolesJson) throws Exception{ + return genericRolesService.pushUserRole(loginId, rolesJson); + } + + + *//** + * Below method is to retrieve user - TODO @Talasila - Created to test the fn_app relation to fn_user_role. If not needed, please remove this method. + * @param id + * @return + * @throws Exception + *//* + @RequestMapping(value={"/user/{loginId}"}, method = RequestMethod.GET, produces = "application/json") + public String getUser(@PathVariable("loginId") String loginId) throws Exception{ + return genericUserService.getUser(loginId); + } + + @RequestMapping(value={"/users"}, method = RequestMethod.GET, produces = "application/json") + public String getUsers() throws Exception{ + return genericUserService.getUsers(); + } + + *//** + * RESTful service method to fetch individual user's roles using user's loginId + * @param loginId + * @return + *//* + @RequestMapping(value={"/user/{loginId}/roles"}, method = RequestMethod.GET, produces = "application/json") + public String getUserRoles(@PathVariable("loginId") String loginId) throws Exception{ + return genericRolesService.getUserRoles(loginId); + } + + *//** + * RESTful service method to fetch available roles + * @return + *//* + + //Commenting this out as it depends on Role API - Ikram + @RequestMapping(value={"/rolesFull"}, method = RequestMethod.GET, produces = "application/json") + public List<Role> getAvailableFullRoles(){ + return genericRolesService.getAvailableFullRoles(); + } + + @ExceptionHandler(Exception.class) + void handleBadRequests(Exception e, HttpServletResponse response) throws IOException { + response.sendError(HttpStatus.BAD_REQUEST.value(),e.getMessage()); + } +} +*/ diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/AngularAdminController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/AngularAdminController.java new file mode 100644 index 00000000..e3aab7dd --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/AngularAdminController.java @@ -0,0 +1,50 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +@Controller +@RequestMapping("/") +public class AngularAdminController extends RestrictedBaseController{ + + @RequestMapping(value = {"/userProfile" }, method = RequestMethod.GET) + public ModelAndView view(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + + return new ModelAndView("user_profile_list","model", model); + } + + @RequestMapping(value = {"/admin" }, method = RequestMethod.GET) + public ModelAndView adminView(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + + return new ModelAndView(getViewName(),"model", model); + } + +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/BroadcastController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/BroadcastController.java new file mode 100644 index 00000000..6dfe9cac --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/BroadcastController.java @@ -0,0 +1,130 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.portalsdk.core.domain.BroadcastMessage; +import org.openecomp.portalsdk.core.service.BroadcastService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class BroadcastController extends RestrictedBaseController { + + @Autowired + private BroadcastService broadcastService; + + @RequestMapping(value = { "/broadcast" }, method = RequestMethod.GET) + public ModelAndView broadcast(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + + try { + model.put("broadcastMessage", mapper.writeValueAsString(broadcastService.getBroadcastMessage(request))); + model.put("broadcastSites", mapper.writeValueAsString(referenceData(request).get("broadcastSites"))); + } catch (Exception e) { + e.printStackTrace(); + } + return new ModelAndView(getViewName(), model); + } + + @RequestMapping(value = { "/get_broadcast" }, method = RequestMethod.GET) + public void getBroadcast(HttpServletRequest request, HttpServletResponse response) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + + try { + + model.put("broadcastMessage", mapper.writeValueAsString(broadcastService.getBroadcastMessage(request))); + model.put("broadcastSites", mapper.writeValueAsString(referenceData(request).get("broadcastSites"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + protected Map referenceData(HttpServletRequest request) { + Map lookupData = new HashMap(); + + if ("true".equals(SystemProperties.getProperty(SystemProperties.CLUSTERED))) { + lookupData.put("broadcastSites", AppUtils.getLookupList("fn_lu_broadcast_site", "broadcast_site_cd", + "broadcast_site_descr", "", "broadcast_site_descr")); + } + + return lookupData; + } + + @RequestMapping(value = { "/broadcast/save" }, method = RequestMethod.POST) + public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception { + + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + BroadcastMessage broadcastMessage = mapper.readValue(root.get("broadcastMessage").toString(), + BroadcastMessage.class); + + broadcastService.saveBroadcastMessage(broadcastMessage); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(broadcastMessage); + JSONObject j = new JSONObject("{broadcastMessage: " + responseString + "}"); + + out.write(j.toString()); + + return null; + } catch (Exception e) { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/BroadcastListController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/BroadcastListController.java new file mode 100644 index 00000000..7e0789c2 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/BroadcastListController.java @@ -0,0 +1,142 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.portalsdk.core.domain.BroadcastMessage; +import org.openecomp.portalsdk.core.service.BroadcastService; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class BroadcastListController extends RestrictedBaseController { + + @Autowired + private BroadcastService broadcastService; + + @RequestMapping(value = { "/broadcast_list" }, method = RequestMethod.GET) + public ModelAndView broadcastList(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + + model.put("model", broadcastService.getBcModel(request)); + return new ModelAndView(getViewName(), model); + } + + @RequestMapping(value = { "/get_broadcast_list" }, method = RequestMethod.GET) + public void getBroadcast(HttpServletRequest request, HttpServletResponse response) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + try { + model.put("model", broadcastService.getBcModel(request)); + model.put("messagesList", broadcastService.getBcModel(request).get("messagesList")); + model.put("messageLocations", broadcastService.getBcModel(request).get("messageLocations")); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + @RequestMapping(value = { "/broadcast_list/remove" }, method = RequestMethod.POST) + public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception { + + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + BroadcastMessage broadcastMessage = mapper.readValue(root.get("broadcastMessage").toString(), + BroadcastMessage.class); + + broadcastService.removeBroadcastMessage(broadcastMessage); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(broadcastMessage); + JSONObject j = new JSONObject("{broadcastMessage: " + responseString + "}"); + + out.write(j.toString()); + + return null; + } catch (Exception e) { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } + + @RequestMapping(value = { "/broadcast_list/toggleActive" }, method = RequestMethod.POST) + public ModelAndView toggleActive(HttpServletRequest request, HttpServletResponse response) throws Exception { + + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + BroadcastMessage broadcastMessage = mapper.readValue(root.get("broadcastMessage").toString(), + BroadcastMessage.class); + + broadcastService.saveBroadcastMessage(broadcastMessage); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(broadcastMessage); + JSONObject j = new JSONObject("{broadcastMessage: " + responseString + "}"); + + out.write(j.toString()); + + return null; + } catch (Exception e) { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CacheAdminController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CacheAdminController.java new file mode 100644 index 00000000..095c41b6 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CacheAdminController.java @@ -0,0 +1,252 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.jcs.JCS; +import org.apache.jcs.admin.CacheRegionInfo; +import org.apache.jcs.admin.JCSAdminBean; +import org.apache.jcs.engine.behavior.ICacheElement; +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +@Controller +@RequestMapping("/") +public class CacheAdminController extends RestrictedBaseController { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CacheAdminController.class); + private JCSAdminBean jcsAdminBean = new JCSAdminBean(); + + @RequestMapping(value = {"/jcs_admin" }, method = RequestMethod.GET) + public ModelAndView cacheAdmin(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + + model.put("model", getRegions()); + + return new ModelAndView(getViewName(),model); + } + + @RequestMapping(value = {"/get_regions" }, method = RequestMethod.GET) + public void getRegions(HttpServletRequest request,HttpServletResponse response) { + // ObjectMapper mapper = new ObjectMapper(); + try{ + JsonMessage msg = new JsonMessage(getRegions().toString()); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + }catch (Exception e) { + e.printStackTrace(); + } + + } + + @RequestMapping(value = {"/jcs_admin/clearRegion" }, method = RequestMethod.GET) + public void clearRegion(HttpServletRequest request,HttpServletResponse response) throws Exception { + String cacheName = (String) request.getParameter("cacheName"); + clearCacheRegion(cacheName); + + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.write(getRegions().toString()); + } + + @RequestMapping(value = {"/jcs_admin/clearAll" }, method = RequestMethod.GET) + public void clearAll(HttpServletRequest request,HttpServletResponse response) throws Exception { + clearAllRegions(); + + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.write(getRegions().toString()); + } + + @RequestMapping(value = {"/jcs_admin/clearItem" }, method = RequestMethod.GET) + public void clearItem(HttpServletRequest request,HttpServletResponse response) throws Exception { + String keyName = (String) request.getParameter("keyName"); + String cacheName = (String) request.getParameter("cacheName"); + clearCacheRegionItem(cacheName, keyName); + + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.write(getRegions().toString()); + } + + @RequestMapping(value = {"/jcs_admin/showItemDetails" }, method = RequestMethod.GET) + public void showItemDetails(HttpServletRequest request,HttpServletResponse response) throws Exception { + String cacheName = (String) request.getParameter("cacheName"); + String keyName = (String) request.getParameter("keyName"); + String details = null; + + try { + details = getItemDetails(cacheName, keyName); + } catch (Exception e) { + details = "There was an error retrieving the region details. Please try again."; + logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while retrieving the item details for the cache region - " + + cacheName + e.getMessage()); + + } + + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.write(details); + } + + @RequestMapping(value = {"/jcs_admin/showRegionDetails" }, method = RequestMethod.GET) + public void showRegionDetails(HttpServletRequest request,HttpServletResponse response) throws Exception { + String cacheName = (String) request.getParameter("cacheName"); + String details = null; + + try { + details = getRegionStats(cacheName); + } catch (Exception e) { + details = "There was an error retrieving the region details. Please try again."; + logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while retrieving the region details for the cache region - " + + cacheName + e.getMessage()); + + } + + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.write(details); + } + + @SuppressWarnings("unchecked") + public JSONArray getRegions(){ + LinkedList<CacheRegionInfo> regions = null; + JSONArray ja = new JSONArray(); + try { + regions = getJcsAdminBean().buildCacheInfo(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); + for (CacheRegionInfo cri : regions) { + JSONObject jo = new JSONObject(); + jo.put("cacheName", cri.getCache().getCacheName()); + jo.put("size", cri.getCache().getSize()); + jo.put("byteCount", cri.getByteCount()); + jo.put("status", cri.getStatus()); + jo.put("hitCountRam", cri.getCache().getHitCountRam()); + jo.put("hitCountAux", cri.getCache().getHitCountAux()); + jo.put("missCountNotFound", cri.getCache().getMissCountNotFound()); + jo.put("missCountExpired", cri.getCache().getMissCountExpired()); + jo.put("items",new JSONArray(mapper.writeValueAsString(getRegionItems(cri.getCache().getCacheName())))); + ja.put(jo); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while retrieving the list of cache regions" + e.getMessage()); + + } + + return ja; + } + + private String getRegionStats(String cacheName) throws Exception { + String stats = ""; + + JCS cache = JCS.getInstance(cacheName); + stats = cache.getStats(); + + return stats; + } + + private String getItemDetails(String cacheName, String keyName) + throws Exception { + String details = ""; + + JCS cache = JCS.getInstance(cacheName); + ICacheElement element = cache.getCacheElement(keyName); + + if (element != null) { + ObjectMapper mapper = new ObjectMapper(); + mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); + details = mapper.writeValueAsString(element); + } + + return details; + } + + @SuppressWarnings("rawtypes") + private List getRegionItems(String cacheName) { + List items = null; + + try { + items = getJcsAdminBean().buildElementInfo(cacheName); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while retrieving the list of items for cache region - " + + cacheName + e.getMessage()); + + } + + return items; + } + + private void clearAllRegions() { + try { + getJcsAdminBean().clearAllRegions(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while clearing all cache regions." + e.getMessage()); + + } + } + + private void clearCacheRegion(String cacheName) { + try { + getJcsAdminBean().clearRegion(cacheName); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while clearing the cache region - " + + cacheName + e.getMessage()); + + } + } + + private void clearCacheRegionItem(String cacheName, String keyName) { + try { + getJcsAdminBean().removeItem(cacheName, keyName); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "An error has occurred while removing cache region item - " + + keyName + e.getMessage()); + + } + } + + public JCSAdminBean getJcsAdminBean() { + return jcsAdminBean; + } + + public void setJcsAdminBean(JCSAdminBean jcsAdminBean) { + this.jcsAdminBean = jcsAdminBean; + } +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CollaborateListController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CollaborateListController.java new file mode 100644 index 00000000..9e43e948 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CollaborateListController.java @@ -0,0 +1,84 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.UserProfileService; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class CollaborateListController extends RestrictedBaseController{ + @Autowired + UserProfileService service; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CollaborateListController.class); + + @RequestMapping(value = {"/collaborate_list" }, method = RequestMethod.GET) + public ModelAndView ProfileSearch(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + User user = UserUtils.getUserSession(request); + + List<User> profileList =null; + try { + profileList = service.findAllUserWithOnOffline(user.getOrgUserId()); + model.put("profileList", mapper.writeValueAsString(profileList)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Error happened during collaborate list search" + e.getMessage()); + + } + return new ModelAndView(getViewName(),"model", model); + } + + @RequestMapping(value = {"/get_collaborate_list" }, method = RequestMethod.GET) + public void getCollaborateList(HttpServletRequest request,HttpServletResponse response) { + + ObjectMapper mapper = new ObjectMapper(); + User user = UserUtils.getUserSession(request); + + List<User> profileList =null; + try { + profileList = service.findAllUserWithOnOffline(user.getOrgUserId()); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(profileList)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Error happened during get collaborate list" + e.getMessage()); + + } + } +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CollaborationController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CollaborationController.java new file mode 100644 index 00000000..a9c1d44b --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/CollaborationController.java @@ -0,0 +1,47 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +@Controller +@RequestMapping("/") +public class CollaborationController extends RestrictedBaseController{ + + @RequestMapping(value = {"/collaboration" }, method = RequestMethod.GET) + public ModelAndView view(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + User user = UserUtils.getUserSession(request); + + model.put("name",(user.getFirstName() + " " + (user.getLastName() != null? user.getLastName().substring(0,1): "" ))); + return new ModelAndView(getViewName(),"model", model); + } + +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ElementModelController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ElementModelController.java new file mode 100644 index 00000000..a6e7b966 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ElementModelController.java @@ -0,0 +1,91 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalsdk.core.service.ElementLinkService; +import org.openecomp.portalsdk.core.service.ElementMapService; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + + +@Controller +@RequestMapping("/") +public class ElementModelController extends RestrictedBaseController{ + + @RequestMapping(value = {"/elementMapLayout" }, method = RequestMethod.POST) + public ModelAndView layout(HttpServletRequest request, + HttpServletResponse response) throws Exception{ + + Map<String, Object> model = new HashMap<String, Object>(); + String collapseDomains = request.getParameter("collapsedDomains"); + String expandDomains = request.getParameter("expandedDomains"); + + String contentFileName = request.getParameter("contentFileName"); + String layoutFileName = request.getParameter("layoutFileName"); + + ElementMapService main = new ElementMapService(); + String yamlString = main.main1(new String[]{collapseDomains,expandDomains, contentFileName, layoutFileName }); + + //response.setContentType("application/json"); + //PrintWriter out = response.getWriter(); + //out.print(yamlString); + //out.flush(); + + //return null; + model.put("output_string", yamlString); + return new ModelAndView("data_out", "model", model); + } + + @RequestMapping(value = {"/elementMapLink" }, method = RequestMethod.POST) + public ModelAndView callflow(HttpServletRequest request, + HttpServletResponse response) throws Exception{ + + Map<String, Object> model = new HashMap<String, Object>(); + String callFlowName = request.getParameter("callFlowName"); + String callFlowStep = request.getParameter("callFlowStep"); + + ElementLinkService main = new ElementLinkService(); + String yamlString = main.main1(new String[]{callFlowName,callFlowStep }); + model.put("output_string", yamlString); + return new ModelAndView("data_out", "model", model); + } + + public ModelAndView callflowAdditional(HttpServletRequest request, + HttpServletResponse response) throws Exception{ + + Map<String, Object> model = new HashMap<String, Object>(); + String callFlowName = request.getParameter("callFlowName"); + String callFlowStep = request.getParameter("callFlowStep"); + + ElementLinkService main = new ElementLinkService(); + String yamlString = main.main2(new String[]{callFlowName,callFlowStep }); + model.put("output_string", yamlString); + return new ModelAndView("data_out", "model", model); + } + +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ExternalLoginController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ExternalLoginController.java new file mode 100644 index 00000000..90e47d42 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ExternalLoginController.java @@ -0,0 +1,121 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalsdk.core.command.LoginBean; +import org.openecomp.portalsdk.core.menu.MenuProperties; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalTimeoutHandler; +import org.openecomp.portalsdk.core.service.LoginService; +import org.openecomp.portalsdk.core.service.ProfileService; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; + +@Controller +@RequestMapping("/") +public class ExternalLoginController extends UnRestrictedBaseController{ + @Autowired + ProfileService service; + @Autowired + private LoginService loginService; + String viewName; + + @RequestMapping(value = {"/login_external.htm" }, method = RequestMethod.GET) + public ModelAndView ExternalLogin(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + return new ModelAndView(getViewName(),"model", model); + } + + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @RequestMapping(value = {"/login_external/login" }, method = RequestMethod.POST) + public @ResponseBody String ExternalLogin(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + Map model = new HashMap(); + LoginBean commandBean = new LoginBean(); + String loginId = request.getParameter("loginId"); + String password = request.getParameter("password"); + commandBean.setLoginId(loginId); + commandBean.setLoginPwd(password); + HashMap additionalParamsMap = new HashMap(); + + commandBean = getLoginService().findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), + additionalParamsMap); + + if (commandBean.getUser() == null) { + String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage() + : "login.error.external.invalid"; + model.put("error", loginErrorMessage); + String[] errorCodes = new String[1]; + errorCodes[0] = loginErrorMessage; + return "failure"; + + } + else { + // store the currently logged in user's information in the session + UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), + null); + initateSessionMgtHandler(request); + // user has been authenticated, now take them to the welcome page + return "success"; + + } + + + } + + public String getJessionId(HttpServletRequest request){ + + return request.getSession().getId(); + + } + + protected void initateSessionMgtHandler(HttpServletRequest request) { + String jSessionId = getJessionId(request); + PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request)); + } + + public String getViewName() { + return viewName; + } + public void setViewName(String viewName) { + this.viewName = viewName; + } + public LoginService getLoginService() { + return loginService; + } + + public void setLoginService(LoginService loginService) { + this.loginService = loginService; + } + +} + diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FavoritesController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FavoritesController.java new file mode 100644 index 00000000..b2ad61f4 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FavoritesController.java @@ -0,0 +1,117 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.portalsdk.core.domain.App; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.aspect.AuditLog; +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.rest.FavoritesClient; +import org.openecomp.portalsdk.core.service.AppService; +import org.openecomp.portalsdk.core.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@AuditLog +public class FavoritesController extends UnRestrictedBaseController { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FavoritesController.class); + + @Autowired + AppService appService; + + /** + * Makes the REST API call to Portal Back-end and retrieves Favorite menu + * items for the currently logged in user. + * + * @param request + * @param response + */ + @RequestMapping(value = { "/get_favorites" }, method = RequestMethod.GET) + public void getFavorites(HttpServletRequest request, HttpServletResponse response) { + String appName = ""; + String requestId = ""; + String appUserName = ""; + String decryptedPwd = ""; + + try { + HttpSession session = request.getSession(); + User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); + if (user == null || user.getId() == null) { + logger.info(EELFLoggerDelegate.errorLogger, + ("Http request did not contain user info, cannot retrieve favorites.")); + + response.setContentType("application/json"); + JSONArray jsonResponse = new JSONArray(); + JSONObject error = new JSONObject(); + error.put("error", "Http request did not contain user info, cannot retrieve favorites."); + jsonResponse.put(error); + response.getWriter().write(jsonResponse.toString()); + } else { + logger.info(EELFLoggerDelegate.errorLogger, + "Retrieving Favorites for the user '" + MDC.get(SystemProperties.MDC_LOGIN_ID) + "'."); + + App app = appService.getDefaultApp(); + if (app!=null) { + appName = app.getName(); + appUserName = app.getUsername(); + try{ + decryptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: " + e.getMessage()); + } + } else { + logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database."); + appName = SystemProperties.SDK_NAME; + } + requestId = MDC.get(MDC_KEY_REQUEST_ID); + + String jsonResponse = FavoritesClient.getFavorites(MDC.get(SystemProperties.MDC_LOGIN_ID), appName, requestId, appUserName, decryptedPwd); + + logger.debug(EELFLoggerDelegate.debugLogger, "FavoritesMenu response: " + jsonResponse); + + response.setContentType("application/json"); + response.getWriter().write(jsonResponse); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred in FavoritesController.getFavorites while performing get_favorites. Details: " + + e.getMessage(), AlarmSeverityEnum.MINOR); + } + } +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FnMenuController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FnMenuController.java new file mode 100644 index 00000000..f19a6f19 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FnMenuController.java @@ -0,0 +1,224 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.portalsdk.core.domain.Menu; +import org.openecomp.portalsdk.core.domain.MenuData; +import org.openecomp.portalsdk.core.service.FnMenuService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Description: this java class is a controller for Admin to add/edit/delete menu items from FN_MENU + */ + +@Controller +@RequestMapping("/") +public class FnMenuController extends RestrictedBaseController { + @Autowired + FnMenuService service; + + String viewName; + + @RequestMapping(value = {"/admin_fn_menu/get_parent_list" }, method = RequestMethod.GET) + public void getParentList(HttpServletRequest request,HttpServletResponse response) throws Exception { + ObjectMapper mapper = new ObjectMapper(); + try{ + + response.getWriter().write(mapper.writeValueAsString(service.getParentList())); + + } catch (Exception e) { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + + } + + } + + @RequestMapping(value = {"/admin_fn_menu/get_function_cd_list" }, method = RequestMethod.GET) + public void getFunctionCDList(HttpServletRequest request,HttpServletResponse response) throws Exception { + ObjectMapper mapper = new ObjectMapper(); + try{ + + response.getWriter().write(mapper.writeValueAsString(service.getFunctionCDList())); + + } catch (Exception e) { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + + } + + } + + @RequestMapping(value = {"/admin_fn_menu" }, method = RequestMethod.GET) + public void getFnMenuList(HttpServletRequest request,HttpServletResponse response) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + List<MenuData> temp =null; + List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>(); + List<MenuData> parentList = new ArrayList<>(); + + try { + temp = service.getFnMenuItems(); + for(MenuData menu: temp){ + MenuData parentData = new MenuData(); + parentData.setId(menu.getId()); + parentData.setLabel(menu.getLabel()); + if(menu.getParentMenu()!=null){ + parentData.setParentId(menu.getParentMenu().getId()); + } + parentData.setAction(menu.getAction()); + parentData.setFunctionCd(menu.getFunctionCd()); + parentData.setImageSrc(menu.getImageSrc()); + parentData.setSortOrder(menu.getSortOrder()); + parentData.setActive(menu.isActive()); + parentData.setServlet(menu.getServlet()); + parentData.setQueryString(menu.getQueryString()); + parentData.setExternalUrl(menu.getExternalUrl()); + parentData.setTarget(menu.getTarget()); + parentData.setMenuSetCode(menu.getMenuSetCode()); + parentData.setSeparator(menu.isSeparator()); + parentData.setImageSrc(menu.getImageSrc()); + parentList.add(parentData); + List<MenuData> tempList = new ArrayList<MenuData>(); + childItemList.add(tempList); + } + model.put("fnMenuItems", parentList); + + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (JsonGenerationException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + + @RequestMapping(value = {"/admin_fn_menu/updateFnMenu" }, method = RequestMethod.POST) + public ModelAndView updateFnMenu(HttpServletRequest request, + HttpServletResponse response) throws Exception { + + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + Menu fnMenuItem = mapper.readValue(root.get("availableFnMenuItem").toString(), Menu.class); + + service.saveFnMenu(fnMenuItem); + request.getSession().removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); + request.getSession().removeAttribute(SystemProperties.LEFT_MENU_CHILDREND); + request.getSession().removeAttribute(SystemProperties.LEFT_MENU_PARENT); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(service.getMenuItem(fnMenuItem.getId())); + + out.write(responseString); + + return null; + + } catch (Exception e) { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + + } + return null; + + } + + @RequestMapping(value = {"/admin_fn_menu/removeMenuItem" }, method = RequestMethod.POST) + public ModelAndView removeFnMenu(HttpServletRequest request, + HttpServletResponse response) throws Exception { + + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + Menu fnMenuItem = mapper.readValue(root.get("fnMenuItem").toString(), Menu.class); + Menu fnMenuItemRow = service.getMenuItemRow(fnMenuItem.getId()); + + service.removeMenuItem(fnMenuItemRow); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(service.getMenuItem(fnMenuItem.getId())); + out.write(responseString); + + return null; + + } catch (Exception e) { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + + + } + return null; + + } + + public String getViewName() { + return viewName; + } + public void setViewName(String viewName) { + this.viewName = viewName; + } + + +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FuncMenuController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FuncMenuController.java new file mode 100644 index 00000000..5baebf00 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FuncMenuController.java @@ -0,0 +1,174 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.portalsdk.core.domain.App; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.aspect.AuditLog; +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties; +import org.openecomp.portalsdk.core.onboarding.rest.FunctionalMenuClient; +import org.openecomp.portalsdk.core.onboarding.ueb.UebException; +import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes; +import org.openecomp.portalsdk.core.service.AppService; +import org.openecomp.portalsdk.core.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +public class FuncMenuController extends UnRestrictedBaseController{ + + @Autowired + AppService appService; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FuncMenuController.class); + + @AuditLog + @RequestMapping(value = {"/get_functional_menu" }, method = RequestMethod.GET) + public void functionalMenu(HttpServletRequest request, HttpServletResponse response) { + + User user = UserUtils.getUserSession(request); + //JSONArray validMenu = new JSONArray("[{\"menuId\":140,\"column\":1,\"text\":\"RT SDK Menu\",\"parentMenuId\":139,\"url\":\"http://www.cnn.com\"},{\"menuId\":139,\"column\":1,\"text\":\"RT Menu\",\"parentMenuId\":11,\"url\":\"\"},{\"menuId\":11,\"column\":1,\"text\":\"Product Design\",\"parentMenuId\":1,\"url\":\"\"},{\"menuId\":1,\"column\":1,\"text\":\"Design\",\"url\":\"\"}]"); + + try { + if ( user != null ) { + String useRestForFunctionalMenu = PortalApiProperties.getProperty(PortalApiConstants.USE_REST_FOR_FUNCTIONAL_MENU); + String funcMenuJsonString = ""; + if (useRestForFunctionalMenu==null || useRestForFunctionalMenu=="" || useRestForFunctionalMenu.equalsIgnoreCase("false")) { + logger.info(EELFLoggerDelegate.errorLogger, "Making use of UEB communication and Requesting functional menu for user " + user.getOrgUserId()); + funcMenuJsonString = getFunctionalMenu(user.getOrgUserId()); + } else { + funcMenuJsonString = getFunctionalMenuViaREST(user.getOrgUserId()); + } + response.setContentType("application/json"); + response.getWriter().write(funcMenuJsonString); + } else { + logger.info(EELFLoggerDelegate.errorLogger, "Http request did not contain user info, cannot retrieve functional menu"); + response.setContentType("application/json"); + JSONArray jsonResponse = new JSONArray(); + JSONObject error = new JSONObject(); + error.put("error","Http request did not contain user info, cannot retrieve functional menu"); + jsonResponse.put(error); + response.getWriter().write(jsonResponse.toString()); + } + } catch (Exception e) { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + JSONArray jsonResponse = new JSONArray(); + JSONObject error = new JSONObject(); + try { + if ( null == e.getMessage() ) { + error.put("error","No menu data"); + } else { + error.put("error",e.getMessage()); + } + jsonResponse.put(error); + response.getWriter().write(jsonResponse.toString()); + logger.error(EELFLoggerDelegate.errorLogger, "Error getting functional_menu: " + e.getMessage(),AlarmSeverityEnum.MAJOR); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + + } + + //-------------------------------------------------------------------------- + // Makes a synchronous call to ECOMP Portal to get the JSON file that + // contains the contents of the functional menu. The JSON file will be + // in the payload of the returned UEB message. + //-------------------------------------------------------------------------- + private String getFunctionalMenu(String userId) throws UebException + { + String returnString = null; + UebMsg funcMenuUebMsg = null; + UebMsg msg = new UebMsg(); + msg.putMsgType(UebMsgTypes.UEB_MSG_TYPE_GET_FUNC_MENU); + msg.putUserId(userId); + funcMenuUebMsg = UebManager.getInstance().requestReply(msg); + if (funcMenuUebMsg != null) { + if (funcMenuUebMsg.getPayload().startsWith("Error:")) { + logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenu received an error in UEB msg = " + funcMenuUebMsg.getPayload()); + } else { + returnString = funcMenuUebMsg.getPayload(); + } + } + + logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenu response: " + returnString); + + return returnString; + } + + private String getFunctionalMenuViaREST(String userId) { + String appName = ""; + String requestId = ""; + String appUserName = ""; + String decryptedPwd = ""; + + logger.info(EELFLoggerDelegate.debugLogger, "Making use of REST API communication and Requesting functional menu for user " + userId); + + App app = appService.getDefaultApp(); + if (app!=null) { + appName = app.getName(); + appUserName = app.getUsername(); + try{ + decryptedPwd = CipherUtil.decrypt(app.getAppPassword(), SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in WebServiceCallServiceImpl.get while decrypting the password. Details: " + e.toString()); + } + } else { + logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the app information from the database."); + appName = SystemProperties.SDK_NAME; + } + requestId = MDC.get(MDC_KEY_REQUEST_ID); + + String fnMenu = null; + try { + fnMenu = FunctionalMenuClient.getFunctionalMenu(userId, appName, requestId, appUserName, decryptedPwd); + }catch(Exception ex) { + fnMenu = "Failed to get functional menu: " + ex.toString(); + } + + logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenu response: {}", fnMenu); + + return fnMenu; + } +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FusionBaseController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FusionBaseController.java new file mode 100644 index 00000000..c7820115 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/FusionBaseController.java @@ -0,0 +1,135 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalsdk.core.domain.MenuData; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.interfaces.SecurityInterface; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.menu.MenuBuilder; +import org.openecomp.portalsdk.core.service.AppService; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.FnMenuService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.ModelAttribute; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +public abstract class FusionBaseController implements SecurityInterface{ + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FusionBaseController.class); + + @Override + public boolean isAccessible() { + return true; + } + + public boolean isRESTfulCall(){ + return true; + } + @Autowired + private FnMenuService fnMenuService; + + @Autowired + private MenuBuilder menuBuilder; + + @Autowired + private DataAccessService dataAccessService; + + @Autowired + AppService appService; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @ModelAttribute("menu") + public Map<String, Object> getMenu(HttpServletRequest request) { + HttpSession session = null; + Map<String, Object> model = new HashMap<String, Object>(); + try { + try { + String appName = appService.getDefaultAppName(); + if (appName==null || appName=="") { + appName = SystemProperties.SDK_NAME; + } + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, appName); + } catch (Exception e) { + } + + session = request.getSession(); + User user = UserUtils.getUserSession(request); + if(session!=null && user!=null){ + Set<MenuData> menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); + if(menuResult==null){ + Set appMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME),dataAccessService); + session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME), MenuBuilder.filterMenu(appMenu, request)); + menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); + } + model = setMenu(menuResult); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + } + return model; + } + + public Map<String, Object> setMenu(Set<MenuData> menuResult) throws Exception{ + ObjectMapper mapper = new ObjectMapper(); + List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>();; + List<MenuData> parentList = new ArrayList<MenuData>();; + Map<String, Object> model = new HashMap<String, Object>(); + try{ + fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult); + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + } + model.put("childItemList",childItemList!=null?mapper.writeValueAsString(childItemList):""); + model.put("parentList",parentList!=null?mapper.writeValueAsString(parentList):""); + return model; + } + + public MenuBuilder getMenuBuilder() { + return menuBuilder; + } + + public void setMenuBuilder(MenuBuilder menuBuilder) { + this.menuBuilder = menuBuilder; + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/LogoutController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/LogoutController.java new file mode 100644 index 00000000..57983621 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/LogoutController.java @@ -0,0 +1,110 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.ModelAndView; + +@Controller +@RequestMapping("/") +public class LogoutController extends UnRestrictedBaseController{ + + private User user; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LogoutController.class); + /** + * @param request + * @param response + * @return modelView + * + * globalLogout will invalid the current application session, then redirects to portal logout + */ + @RequestMapping(value = {"/logout.htm" }, method = RequestMethod.GET) + public ModelAndView globalLogout(HttpServletRequest request, HttpServletResponse response) { + ModelAndView modelView = null; + try{ + chatRoomLogout(request); + request.getSession().invalidate(); + String portalUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); + String portalDomain = portalUrl.substring(0, portalUrl.lastIndexOf('/')); + String redirectUrl = portalDomain+"/logout.htm"; + modelView = new ModelAndView("redirect:"+redirectUrl); + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Logout Error: " + e.getMessage(),AlarmSeverityEnum.MAJOR); + } + return modelView; + } + + /** + * @param request + * @param response + * @return modelView + * + * appLogout is a function that will invalid the current session (application logout) and redirects user to Portal. + */ + @RequestMapping(value = {"/app_logout.htm" }, method = RequestMethod.GET) + public ModelAndView appLogout(HttpServletRequest request, HttpServletResponse response) { + ModelAndView modelView = null; + try{ + chatRoomLogout(request); + modelView = new ModelAndView("redirect:"+PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL)); + UserUtils.clearUserSession(request); + request.getSession().invalidate(); + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Application Logout Error: " + e.getMessage(),AlarmSeverityEnum.MAJOR); + } + return modelView; + } + + + public void chatRoomLogout(HttpServletRequest request){ + request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest(); + setUser(UserUtils.getUserSession(request)); + // if(getUser()!=null){ + // Long login_IdLong = getUser().getId(); + // String name = getUser().getFirstName(); + // String login_IdStr = Long.toString(login_IdLong); + // } + //UserListName.getInstance().delUserName(name); + //UserListID.getInstance().delUserName(login_IdStr); + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/MenuListController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/MenuListController.java new file mode 100644 index 00000000..ee66a948 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/MenuListController.java @@ -0,0 +1,245 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.json.JSONObject; +import org.openecomp.portalsdk.core.domain.MenuData; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties; +import org.openecomp.portalsdk.core.restful.client.SharedContextRestClient; +import org.openecomp.portalsdk.core.restful.domain.SharedContext; +import org.openecomp.portalsdk.core.service.AppService; +import org.openecomp.portalsdk.core.service.FnMenuService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.fasterxml.jackson.databind.ObjectMapper; + + +@Controller +@RequestMapping("/") +public class MenuListController extends UnRestrictedBaseController{ + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MenuListController.class); + @Autowired + AppService appService; + @Autowired + FnMenuService fnMenuService; + @Autowired + SharedContextRestClient sharedContextRestClient; + /** + * + * Get Menu items and store into session. + * + * @param request + * @param response + */ + @SuppressWarnings("unchecked") + @RequestMapping(value = {"/get_menu" }, method = RequestMethod.GET) + public void ProfileSearch(HttpServletRequest request, HttpServletResponse response) { + logger.info("calling /get_menu.."); + try { + ObjectMapper mapper = new ObjectMapper(); + Set<MenuData> menuResult=null; + HttpSession session = request.getSession(); + List<List<MenuData>> childItemList = (List<List<MenuData>>) session.getAttribute(SystemProperties.LEFT_MENU_CHILDREND); + List<MenuData> parentList = (List<MenuData>) session.getAttribute(SystemProperties.LEFT_MENU_PARENT); + if(parentList==null || childItemList==null || parentList.size()==0 || childItemList.size()==0){ + childItemList=new ArrayList<List<MenuData>>(); + parentList = new ArrayList<MenuData>(); + menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); + fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult); + logger.info("storing leftmenu items into session"); + session.setAttribute(SystemProperties.LEFT_MENU_PARENT, parentList); + session.setAttribute(SystemProperties.LEFT_MENU_CHILDREND, childItemList); + } + String userName = (String) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(parentList),mapper.writeValueAsString(childItemList),userName); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + logger.info("done with /get_menu call without any errors"); + } catch (Exception e) { + logger.info("errors while calling /get_menu",e); + } + } + + /** + * + * Get app name from system.properties file. + * + * @param request + * @param response + */ + + @RequestMapping(value = {"/get_app_name" }, method = RequestMethod.GET) + public void getAppName(HttpServletRequest request, HttpServletResponse response) { + logger.info("calling /get_app_name."); + HttpSession session = request.getSession(true); + try { + // String appName = SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME); + String appName = (String) session.getAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)); + if(appName!=null && appName.equals("app_display_name")){ + appName = ""; + } + JsonMessage msg = new JsonMessage(appName); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + logger.info("done with /get_app_name call without any errors"); + } catch (Exception e) { + logger.error("errors while calling /get_app_name",e); + } + } + + @SuppressWarnings("unchecked") + @ModelAttribute("menu") + public Map<String, Object> getLeftMenuJSP(HttpServletRequest request) { + logger.info("invoking getting left menu"); + ObjectMapper mapper = new ObjectMapper(); + Map<String, Object> model = new HashMap<String, Object>(); + try { + HttpSession session = request.getSession(); + List<List<MenuData>> childItemList = (List<List<MenuData>>) session.getAttribute(SystemProperties.LEFT_MENU_CHILDREND); + List<MenuData> parentList = (List<MenuData>) session.getAttribute(SystemProperties.LEFT_MENU_PARENT); + if(parentList==null || childItemList==null){ + childItemList=new ArrayList<List<MenuData>>(); + parentList = new ArrayList<MenuData>(); + Set<MenuData> menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); + fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult); + session.setAttribute(SystemProperties.LEFT_MENU_PARENT, parentList); + session.setAttribute(SystemProperties.LEFT_MENU_CHILDREND, childItemList); + } + model.put("childItemList",mapper.writeValueAsString(childItemList)); + model.put("parentList",mapper.writeValueAsString(parentList)); + } catch (Exception e) { + logger.info("errors while getting left menu",e); + } + logger.info("done with getting left menu without any errors"); + return model; + } + + /** + * Answers requests for user information, which is fetched from the shared context at Portal. + * + * @param request + * @param response + * @return JSON block with user information. + */ + @RequestMapping(value = {"/get_userinfo" }, method = RequestMethod.GET) + public String getUserInfo(HttpServletRequest request, HttpServletResponse response) { + logger.info(EELFLoggerDelegate.debugLogger, "Getting shared context for user"); + try{ + String contextId= null; + if(request.getCookies()!=null){ + for(Cookie ck :request.getCookies()){ + if(ck.getName().equalsIgnoreCase("EPService")) + contextId = ck.getValue(); + } + } + logger.info(EELFLoggerDelegate.debugLogger, "ContextId is : " + contextId); + List<SharedContext> sharedContextRes = sharedContextRestClient.getUserContext(contextId); + logger.info(EELFLoggerDelegate.debugLogger, "Shared Context Response is : " + sharedContextRes); + Map<String, Object> model = new HashMap<String, Object>(); + for(SharedContext sharedContext: sharedContextRes){ + model.put(sharedContext.getCkey(), sharedContext.getCvalue()); + } + JSONObject j = new JSONObject(model); + response.getWriter().write(j.toString()); + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to get shared context for user" + e.getMessage()); + } + return null; + } + + /** + * Get User information from app sessions + * @param request + * @param response + */ + @RequestMapping(value = {"/get_topMenuInfo" }, method = RequestMethod.GET) + public void getTopMenu(HttpServletRequest request, HttpServletResponse response) { + + HttpSession session = request.getSession(); + try { + String userName = (String) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME)); + String firstName = (String) session.getAttribute(SystemProperties.FIRST_NAME); + String lastName = (String) session.getAttribute(SystemProperties.LAST_NAME); + User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); + Map<String,String> map = new HashMap<String,String>(); + String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); + String portalDomain = redirectUrl.substring(0, redirectUrl.lastIndexOf('/')); + String portalUrl = portalDomain + "/processSingleSignOn"; + String getAccessUrl = portalDomain + "/get_access"; + String email = user.getEmail(); + String contactUsLink = SystemProperties.getProperty(SystemProperties.CONTACT_US_LINK); + String userId = UserUtils.getUserIdFromCookie(request); + + map.put("portalUrl", portalUrl); + map.put("contactUsLink", contactUsLink); + map.put("userName", userName); + map.put("firstName", firstName); + map.put("lastName", lastName); + map.put("userid", userId); + map.put("email", email); + map.put("getAccessUrl",getAccessUrl); + JSONObject j = new JSONObject(map); + response.getWriter().write(j.toString()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to serialize JSON" + e.getMessage()); + } + + } + + @RequestMapping(value = {"/page_redirect" }, method = RequestMethod.GET) + public void pageRedirect(HttpServletRequest request, HttpServletResponse response) { + String pageToURL=null; + try { + String pageTo = request.getParameter("page"); + if(pageTo.equals("contact")) + pageToURL = SystemProperties.getProperty(SystemProperties.CONTACT_US_LINK); + else if(pageTo.equals("access")){ + String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); + String portalDomain = redirectUrl.substring(0, redirectUrl.lastIndexOf('/')); + pageToURL = portalDomain + "/get_access"; + } + response.getWriter().write(pageToURL); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to serialize JSON" + e.getMessage()); + } + } +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/PostSearchController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/PostSearchController.java new file mode 100644 index 00000000..fa5a1082 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/PostSearchController.java @@ -0,0 +1,219 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.portalsdk.core.command.PostSearchBean; +import org.openecomp.portalsdk.core.domain.Lookup; +import org.openecomp.portalsdk.core.domain.Profile; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.LdapService; +import org.openecomp.portalsdk.core.service.PostSearchService; +import org.openecomp.portalsdk.core.service.ProfileService; +import org.openecomp.portalsdk.core.service.UserProfileService; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class PostSearchController extends RestrictedBaseController { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostSearchController.class); + + @SuppressWarnings("rawtypes") + private static List sortByList = null; + + @Autowired + private PostSearchService postSearchService; + + @Autowired + LdapService ldapService; + + @Autowired + private ProfileService profileService; + + @Autowired + UserProfileService userProfileService; + + public UserProfileService getUserProfileService() { + return userProfileService; + } + + public void setUserProfileService(UserProfileService userProfileService) { + this.userProfileService = userProfileService; + } + + @RequestMapping(value = { "/post_search" }, method = RequestMethod.GET) + public ModelAndView welcome(HttpServletRequest request, + @ModelAttribute("postSearchBean") PostSearchBean postSearchBean) { + Map<String, Object> model = new HashMap<String, Object>(); + + ObjectMapper mapper = new ObjectMapper(); + try { + postSearchBean = new PostSearchBean(); + model.put("profileList", mapper.writeValueAsString(postSearchBean.getSearchResult())); + model.put("postSearchBean", mapper.writeValueAsString(postSearchBean)); + model.put("existingUsers", mapper.writeValueAsString(getExistingUsers())); + model.put("sortByList", mapper.writeValueAsString(getSortByList())); + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "welcome: failed to write JSON" + ex.getMessage()); + } + + return new ModelAndView(getViewName(), model); + } + + @RequestMapping(value = { "/post_search_sample" }, method = RequestMethod.GET) + public void getPostSearchProfile(HttpServletRequest request, HttpServletResponse response, + @ModelAttribute("postSearchBean") PostSearchBean postSearchBean) { + Map<String, Object> model = new HashMap<String, Object>(); + + ObjectMapper mapper = new ObjectMapper(); + try { + postSearchBean = new PostSearchBean(); + model.put("profileList", mapper.writeValueAsString(postSearchBean.getSearchResult())); + model.put("postSearchBean", mapper.writeValueAsString(postSearchBean)); + model.put("existingUsers", mapper.writeValueAsString(getExistingUsers())); + model.put("sortByList", mapper.writeValueAsString(getSortByList())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "getPostSearchProfile: failed to write JSON" + ex.getMessage()); + } + + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private HashMap getExistingUsers() { + HashMap existingUsers = new HashMap(); + + List<Profile> list = profileService.findAll(); + + if (list != null) { + Iterator<Profile> i = list.iterator(); + while (i.hasNext()) { + Profile user = i.next(); + String orgUserId = user.getOrgUserId(); + Long id = user.getId(); // id scalar + if (orgUserId != null) + existingUsers.put(orgUserId, id); + } + } + return existingUsers; + } + + @RequestMapping(value = { "/post_search/search" }, method = RequestMethod.POST) + public ModelAndView search(HttpServletRequest request, HttpServletResponse response) throws Exception { + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PostSearchBean postSearchBean = mapper.readValue(root.get("postSearchBean").toString(), + PostSearchBean.class); + + //postSearchBean.setSearchResult(loadSearchResultData(request, postSearchBean)); + List<User> users = loadSearchResultDataFromFnTableOrExt(request,postSearchBean); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(users); + JSONObject j = new JSONObject("{users: " + responseString + "}"); + + out.write(j.toString()); + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "search: failed to send search result" + ex.getMessage()); + } + + return null; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static List getSortByList() { + if (sortByList == null) { + sortByList = new ArrayList(); + sortByList.add(new Lookup("Last Name", "last_name")); + sortByList.add(new Lookup("First Name", "first_name")); + sortByList.add(new Lookup("HRID", "hrid")); + sortByList.add(new Lookup("SBCID", "sbcid")); + sortByList.add(new Lookup("Organization", "org_code")); + sortByList.add(new Lookup("Email", "email")); + } // if + + return sortByList; + } // getSortByList + + private List<User> loadSearchResultDataFromFnTableOrExt(HttpServletRequest request, PostSearchBean searchCriteria) + throws Exception { + return userProfileService.searchPost(searchCriteria.getUser(), searchCriteria.getSortBy1(), + searchCriteria.getSortBy2(), searchCriteria.getSortBy3(), searchCriteria.getPageNo(), + searchCriteria.getNewDataSize(), UserUtils.getUserSession(request).getId().intValue()); + } + + @RequestMapping(value = { "/post_search/process" }, method = RequestMethod.POST) + public ModelAndView process(HttpServletRequest request, HttpServletResponse response) throws Exception { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + JsonNode root = mapper.readTree(request.getReader()); + PostSearchBean postSearch = mapper.readValue(root.get("postSearchBean").toString(), PostSearchBean.class); + + postSearchService.process(request, postSearch); + List<User> users = loadSearchResultDataFromFnTableOrExt(request,postSearch); + + logger.info(EELFLoggerDelegate.auditLogger, "Import new user from webphone "); + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String userString = mapper.writeValueAsString(users); + JSONObject j = new JSONObject("{users: " + userString + ",existingUsers: " + + mapper.writeValueAsString(getExistingUsers()) + "}"); + + out.write(j.toString()); + + return null; + } +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ProfileController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ProfileController.java new file mode 100644 index 00000000..1fd7800f --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ProfileController.java @@ -0,0 +1,349 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.RoleService; +import org.openecomp.portalsdk.core.service.UserProfileService; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class ProfileController extends RestrictedBaseController { + + @Autowired + UserProfileService service; + @Autowired + RoleService roleService; + + String viewName; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProfileController.class); + + @RequestMapping(value = { "/profile" }, method = RequestMethod.GET) + public ModelAndView profile(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + + User profile = null; + Long profileId = null; + + if (request.getRequestURI().indexOf("self_profile.htm") > -1) { + profile = UserUtils.getUserSession(request); + profileId = profile.getId(); + } else { + profileId = Long.parseLong(request.getParameter("profile_id")); + profile = (User) service.getUser(request.getParameter("profile_id")); + } + + try { + model.put("stateList", mapper.writeValueAsString(getStates())); + model.put("countries", mapper.writeValueAsString(getCountries())); + model.put("timeZones", mapper.writeValueAsString(getTimeZones())); + model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles())); + model.put("profile", mapper.writeValueAsString(profile)); + model.put("profileId", mapper.writeValueAsString(profileId)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "profile: failed to write JSON" + e.getMessage()); + } + return new ModelAndView("profile", "model", model); + } + + @RequestMapping(value = { "/self_profile" }, method = RequestMethod.GET) + public ModelAndView self_profile(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + + User profile = null; + Long profileId = null; + + profile = UserUtils.getUserSession(request); + profileId = profile.getId(); + profile = (User) service.getUser(profileId.toString()); + + try { + model.put("stateList", mapper.writeValueAsString(getStates())); + model.put("countries", mapper.writeValueAsString(getCountries())); + model.put("timeZones", mapper.writeValueAsString(getTimeZones())); + model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles())); + model.put("profile", mapper.writeValueAsString(profile)); + model.put("profileId", mapper.writeValueAsString(profileId)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "self_profile: failed to write JSON" + e.getMessage()); + } + return new ModelAndView("profile", "model", model); + } + + @RequestMapping(value = { "/get_self_profile" }, method = RequestMethod.GET) + public void getSelfProfile(HttpServletRequest request, HttpServletResponse response) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + + User profile = null; + Long profileId = null; + + profile = UserUtils.getUserSession(request); + profileId = profile.getId(); + profile = (User) service.getUser(profileId.toString()); + + try { + model.put("stateList", mapper.writeValueAsString(getStates())); + model.put("countries", mapper.writeValueAsString(getCountries())); + model.put("timeZones", mapper.writeValueAsString(getTimeZones())); + model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles())); + model.put("profile", mapper.writeValueAsString(profile)); + model.put("profileId", mapper.writeValueAsString(profileId)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getSelfProfile: failed to write JSON" + e.getMessage()); + } + + } + + @RequestMapping(value = { "/get_profile" }, method = RequestMethod.GET) + public void GetUser(HttpServletRequest request, HttpServletResponse response) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + try { + User profile = null; + Long profileId = null; + if (request.getRequestURI().indexOf("self_profile.htm") > -1) { + profile = UserUtils.getUserSession(request); + profileId = profile.getId(); + } else { + profileId = Long.parseLong(request.getParameter("profile_id")); + profile = (User) service.getUser(request.getParameter("profile_id")); + } + model.put("stateList", mapper.writeValueAsString(getStates())); + model.put("countries", mapper.writeValueAsString(getCountries())); + model.put("timeZones", mapper.writeValueAsString(getTimeZones())); + model.put("availableRoles", mapper.writeValueAsString(getAvailableRoles())); + model.put("profile", mapper.writeValueAsString(profile)); + model.put("profileId", mapper.writeValueAsString(profileId)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "GetUser: failed to write JSON" + e.getMessage()); + } + } + + @RequestMapping(value = { "/profile/saveProfile" }, method = RequestMethod.POST) + public ModelAndView saveProfile(HttpServletRequest request, HttpServletResponse response) { + logger.info(EELFLoggerDelegate.debugLogger, "ProfileController.save"); + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + User user = mapper.readValue(root.get("profile").toString(), User.class); + + String selectedCountry = mapper.readValue(root.get("selectedCountry").toString(), String.class); + String selectedState = mapper.readValue(root.get("selectedState").toString(), String.class); + String selectedTimeZone = mapper.readValue(root.get("selectedTimeZone").toString(), String.class); + + Long profileId = Long.parseLong(request.getParameter("profile_id")); + + User domainUser = (User) service.getUser(request.getParameter("profile_id")); + // user.setRoles(domainUser.getRoles()); + user.setPseudoRoles(domainUser.getPseudoRoles()); + user.setUserApps(domainUser.getUserApps()); + if (!selectedCountry.equals("")) { + user.setCountry(selectedCountry); + } + if (!selectedState.equals("")) { + user.setState(selectedState); + } + if (!selectedTimeZone.equals("")) { + user.setTimeZoneId(Long.parseLong(selectedTimeZone)); + } + service.saveUser(user); + logger.info(EELFLoggerDelegate.auditLogger, "Save user's profile for user " + profileId); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + out.write("" + profileId); + return null; + } catch (Exception e) { + response.setCharacterEncoding("UTF-8"); + try { + request.setCharacterEncoding("UTF-8"); + } catch (UnsupportedEncodingException e1) { + + e1.printStackTrace(); + + } + PrintWriter out = null; + try { + out = response.getWriter(); + } catch (IOException e1) { + logger.error(EELFLoggerDelegate.errorLogger, "saveProfile: failed to get writer" + e1.getMessage()); + } + out.write(e.getMessage()); + return null; + } + } + + @RequestMapping(value = { "/profile/removeRole" }, method = RequestMethod.POST) + public ModelAndView removeRole(HttpServletRequest request, HttpServletResponse response) throws Exception { + + logger.info(EELFLoggerDelegate.debugLogger, "ProfileController.save"); + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + Role role = mapper.readValue(root.get("role").toString(), Role.class); + + // Long profileId = Long.parseLong(request.getParameter("profile_id")); + + User domainUser = (User) service.getUser(request.getParameter("profile_id")); + + domainUser.removeRole(role.getId()); + + service.saveUser(domainUser); + logger.info(EELFLoggerDelegate.auditLogger, "Remove role " + role.getId() + " from user " + request.getParameter("profile_id")); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + Map<String, Object> model = new HashMap<String, Object>(); + model.put("profile", mapper.writeValueAsString(domainUser)); + JSONObject j = new JSONObject(mapper.writeValueAsString(domainUser)); + + out.write(j.toString()); + + return null; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "removeRole" + e.getMessage()); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } + + @RequestMapping(value = { "/profile/addNewRole" }, method = RequestMethod.POST) + public ModelAndView addNewRole(HttpServletRequest request, HttpServletResponse response) throws Exception { + + logger.info(EELFLoggerDelegate.debugLogger, "ProfileController.save" ); + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + Role role = mapper.readValue(root.get("role").toString(), Role.class); + + // Long profileId = Long.parseLong(request.getParameter("profile_id")); + + User domainUser = (User) service.getUser(request.getParameter("profile_id")); + + domainUser.addRole(role); + + service.saveUser(domainUser); + logger.info(EELFLoggerDelegate.auditLogger, "Add new role " + role.getName() + " to user " + request.getParameter("profile_id")); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + Map<String, Object> model = new HashMap<String, Object>(); + model.put("profile", mapper.writeValueAsString(domainUser)); + JSONObject j = new JSONObject(mapper.writeValueAsString(domainUser)); + + out.write(j.toString()); + + return null; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addNewRole" + e.getMessage()); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } + + public String getViewName() { + return viewName; + } + + public void setViewName(String viewName) { + this.viewName = viewName; + } + + @SuppressWarnings("rawtypes") + public List getStates() { + return AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD"); + } + + @SuppressWarnings("rawtypes") + public List getCountries() { + return AppUtils.getLookupList("FN_LU_COUNTRY", "COUNTRY_CD", "COUNTRY", null, "COUNTRY"); + } + + @SuppressWarnings("rawtypes") + public List getTimeZones() { + return AppUtils.getLookupList("FN_LU_TIMEZONE", "TIMEZONE_ID", "TIMEZONE_NAME", null, "TIMEZONE_NAME"); + } + + @SuppressWarnings("rawtypes") + public List getAvailableRoles() { + return roleService.getAvailableRoles(); + } + +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ProfileSearchController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ProfileSearchController.java new file mode 100644 index 00000000..42ebd41e --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/ProfileSearchController.java @@ -0,0 +1,149 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.json.JSONObject; +import org.openecomp.portalsdk.core.domain.MenuData; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.FnMenuService; +import org.openecomp.portalsdk.core.service.UserProfileService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class ProfileSearchController extends RestrictedBaseController{ + @Autowired + UserProfileService service; + @Autowired + FnMenuService fnMenuService; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProfileSearchController.class); + @RequestMapping(value = {"/profile_search" }, method = RequestMethod.GET) + public ModelAndView ProfileSearch(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + List<User> profileList =null; + logger.info(EELFLoggerDelegate.applicationLogger, "Initiating ProfileSearch in ProfileSearchController"); + try { + profileList = service.findAll(); + model.putAll(setDashboardData(request)); + model.put("profileList", mapper.writeValueAsString(profileList)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.applicationLogger, "error while profile_search process in ProfileSearchController" + e.getMessage()); + } + return new ModelAndView(getViewName(),"model", model); + } + + @RequestMapping(value = {"/get_user" }, method = RequestMethod.GET) + public void GetUser(HttpServletRequest request, HttpServletResponse response) { + logger.info(EELFLoggerDelegate.applicationLogger, "Initiating get_user in ProfileSearchController"); + ObjectMapper mapper = new ObjectMapper(); + List<User> profileList =null; + try { + profileList = service.findAll(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(profileList)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.applicationLogger, "error while get_user process in ProfileSearchController" + e.getMessage()); + } + } + + @RequestMapping(value = {"/get_user_pagination" }, method = RequestMethod.GET) + public void getUserPagination(HttpServletRequest request, HttpServletResponse response) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + logger.info(EELFLoggerDelegate.applicationLogger, "Initiating get_user_pagination in ProfileSearchController"); + int pageNum = Integer.parseInt(request.getParameter("pageNum")); + int viewPerPage = Integer.parseInt(request.getParameter("viewPerPage")); + List<User> profileList =null; + try { + profileList = service.findAll(); + model.put("totalPage",(int) Math.ceil((double)profileList.size() / viewPerPage)); + profileList = profileList.subList(viewPerPage*(pageNum-1)<profileList.size()?viewPerPage*(pageNum-1):profileList.size(), viewPerPage*pageNum<profileList.size()?viewPerPage*pageNum:profileList.size()); + model.put("profileList", mapper.writeValueAsString(profileList)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.applicationLogger, "error while get_user_pagination process in ProfileSearchController" + e.getMessage()); + } + } + + + @SuppressWarnings("unchecked") + public Map<String, Object>setDashboardData(HttpServletRequest request) throws Exception{ + ObjectMapper mapper = new ObjectMapper(); + Map<String, Object> model = new HashMap<String, Object>(); + List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>(); + List<MenuData> parentList = new ArrayList<MenuData>(); + logger.info(EELFLoggerDelegate.applicationLogger, "Initiating setDashboardData in ProfileSearchController"); + HttpSession session = request.getSession(); + try{ + Set<MenuData> menuResult = (Set<MenuData>) session.getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); + fnMenuService.setMenuDataStructure(childItemList, parentList, menuResult); + }catch(Exception e){ + logger.error(EELFLoggerDelegate.applicationLogger, "error while setDashboardData process in ProfileSearchController" + e.getMessage()); + } + model.put("childItemList",mapper.writeValueAsString(childItemList)); + model.put("parentList",mapper.writeValueAsString(parentList)); + return model; + } + + @RequestMapping(value = {"/profile/toggleProfileActive" }, method = RequestMethod.GET) + public void toggleProfileActive(HttpServletRequest request, HttpServletResponse response) throws IOException { + try{ + logger.info(EELFLoggerDelegate.applicationLogger, "Initiating toggleProfileActive in ProfileSearchController"); + String userId = request.getParameter("profile_id"); + User user = (User)service.getUser(userId); + user.setActive(!user.getActive()); + service.saveUser(user); + logger.info(EELFLoggerDelegate.auditLogger, "Change active status for user " + user.getId() + " to " + user.getActive()); + ObjectMapper mapper = new ObjectMapper(); + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.write(mapper.writeValueAsString(user.getActive())); + }catch(Exception e){ + logger.error(EELFLoggerDelegate.applicationLogger, "error while toggleProfileActive process in ProfileSearchController" + e.getMessage()); + } + } +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedBaseController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedBaseController.java new file mode 100644 index 00000000..2b2e3426 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedBaseController.java @@ -0,0 +1,50 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +public class RestrictedBaseController extends FusionBaseController{ + + protected String viewName; + private String exceptionView; + @Override + public boolean isAccessible() { + return false; + } + @Override + public boolean isRESTfulCall(){ + return false; + } + protected String getViewName() { + return viewName; + } + protected void setViewName(String viewName) { + this.viewName = viewName; + } + + public String getExceptionView() { + return (exceptionView == null) ? "runtime_error_handler" : exceptionView; + } + + public void setExceptionView(String exceptionView) { + this.exceptionView = exceptionView; + } + + +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedRESTfulBaseController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedRESTfulBaseController.java new file mode 100644 index 00000000..d11c7d76 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RestrictedRESTfulBaseController.java @@ -0,0 +1,50 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +public class RestrictedRESTfulBaseController extends FusionBaseController{ + + protected String viewName; + private String exceptionView; + @Override + public boolean isAccessible() { + return false; + } + @Override + public boolean isRESTfulCall(){ + return true; + } + protected String getViewName() { + return viewName; + } + protected void setViewName(String viewName) { + this.viewName = viewName; + } + + public String getExceptionView() { + return (exceptionView == null) ? "runtime_error_handler" : exceptionView; + } + + public void setExceptionView(String exceptionView) { + this.exceptionView = exceptionView; + } + + +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleController.java new file mode 100644 index 00000000..0419e2b8 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleController.java @@ -0,0 +1,332 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.RoleService; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.ServletRequestUtils; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; + +@Controller +@RequestMapping("/") +public class RoleController extends RestrictedBaseController { + @Autowired + RoleService service; + + String viewName; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleController.class); + + @RequestMapping(value = { "/role" }, method = RequestMethod.GET) + public ModelAndView role(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + + Role role = service.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0))); + logger.info("role_id" + role.getId()); + try { + model.put("availableRoleFunctions", mapper.writeValueAsString(service.getRoleFunctions())); + model.put("availableRoles", mapper.writeValueAsString(service.getAvailableChildRoles(role.getId()))); + model.put("role", mapper.writeValueAsString(role)); + } catch (Exception e) { + logger.error("role: failed", e); + logger.error(EELFLoggerDelegate.errorLogger, "Unable to set the active profile" + e.getMessage()); + } + return new ModelAndView(getViewName(), model); + } + + @RequestMapping(value = { "/get_role" }, method = RequestMethod.GET) + public void getRole(HttpServletRequest request, HttpServletResponse response) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + + Role role = service.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0))); + logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + role.getId()); + try { + model.put("availableRoleFunctions", mapper.writeValueAsString(service.getRoleFunctions())); + model.put("availableRoles", mapper.writeValueAsString(service.getAvailableChildRoles(role.getId()))); + model.put("role", mapper.writeValueAsString(role)); + + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRole failed" + e.getMessage()); + } + + } + + @RequestMapping(value = { "/role/saveRole" }, method = RequestMethod.POST) + public ModelAndView saveRole(HttpServletRequest request, HttpServletResponse response) throws Exception { + + logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.save"); + logger.info(EELFLoggerDelegate.auditLogger, "RoleController.save"); + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + Role role = mapper.readValue(root.get("role").toString(), Role.class); + + List<Role> childRoles = mapper.readValue(root.get("childRoles").toString(), + TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class)); + + List<RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(), + TypeFactory.defaultInstance().constructCollectionType(List.class, RoleFunction.class)); + + Role domainRole = null; + if (role.getId() != null) { + logger.info(EELFLoggerDelegate.auditLogger, "updating existing role " + role.getId()); + domainRole = service.getRole(role.getId()); + + domainRole.setName(role.getName()); + domainRole.setPriority(role.getPriority()); + } else { + logger.info(EELFLoggerDelegate.auditLogger, "saving as new role"); + domainRole = new Role(); + domainRole.setName(role.getName()); + domainRole.setPriority(role.getPriority()); + if (role.getChildRoles().size() > 0) { + for (Object childRole : childRoles) { + domainRole.addChildRole((Role) childRole); + } + } + if (role.getRoleFunctions().size() > 0) { + for (Object roleFunction : roleFunctions) { + domainRole.addRoleFunction((RoleFunction) roleFunction); + } + } + } + + service.saveRole(domainRole); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(domainRole); + JSONObject j = new JSONObject("{role: " + responseString + "}"); + + out.write(j.toString()); + + return null; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed" + e.getMessage()); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } + + @RequestMapping(value = { "/role/removeRoleFunction" }, method = RequestMethod.POST) + public ModelAndView removeRoleFunction(HttpServletRequest request, HttpServletResponse response) throws Exception { + + logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction"); + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class); + + Role domainRole = service.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0))); + logger.info(EELFLoggerDelegate.auditLogger, "Remove role function " + roleFunction.getCode() + " from role " + ServletRequestUtils.getIntParameter(request, "role_id", 0)); + + domainRole.removeRoleFunction(roleFunction.getCode()); + + service.saveRole(domainRole); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(domainRole); + JSONObject j = new JSONObject("{role: " + responseString + "}"); + out.write(j.toString()); + + return null; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed" + e.getMessage()); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } + + @RequestMapping(value = { "/role/addRoleFunction" }, method = RequestMethod.POST) + public ModelAndView addRoleFunction(HttpServletRequest request, HttpServletResponse response) throws Exception { + + logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction"); + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class); + + Role domainRole = service.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0))); + + domainRole.addRoleFunction(roleFunction); + + service.saveRole(domainRole); + logger.info(EELFLoggerDelegate.auditLogger, "Add role function " + roleFunction.getCode() + " to role " + ServletRequestUtils.getIntParameter(request, "role_id", 0)); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(domainRole); + JSONObject j = new JSONObject("{role: " + responseString + "}"); + out.write(j.toString()); + + return null; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed" + e.getMessage()); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } + + @RequestMapping(value = { "/role/removeChildRole" }, method = RequestMethod.POST) + public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception { + + logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeChileRole"); + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class); + + Role domainRole = service.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0))); + + domainRole.removeChildRole(childRole.getId()); + logger.info(EELFLoggerDelegate.auditLogger, "remove child role " + childRole.getId() + " from role " + ServletRequestUtils.getIntParameter(request, "role_id", 0)); + + + service.saveRole(domainRole); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(domainRole); + JSONObject j = new JSONObject("{role: " + responseString + "}"); + out.write(j.toString()); + + return null; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "removeChildRole failed" + e.getMessage()); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } + + @RequestMapping(value = { "/role/addChildRole" }, method = RequestMethod.POST) + public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception { + + logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.addChileRole"); + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class); + + Role domainRole = service.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0))); + + domainRole.addChildRole(childRole); + + service.saveRole(domainRole); + logger.info(EELFLoggerDelegate.auditLogger, "Add child role " + childRole.getId() + " to role " + ServletRequestUtils.getIntParameter(request, "role_id", 0)); + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(domainRole); + JSONObject j = new JSONObject("{role: " + responseString + "}"); + out.write(j.toString()); + + return null; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addChildRole failed" + e.getMessage()); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } + + public String getViewName() { + return viewName; + } + + public void setViewName(String viewName) { + this.viewName = viewName; + } +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleFunctionListController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleFunctionListController.java new file mode 100644 index 00000000..3b9eed62 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleFunctionListController.java @@ -0,0 +1,184 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.RoleService; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class RoleFunctionListController extends RestrictedBaseController { + @Autowired + RoleService service; + + String viewName; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleFunctionListController.class); + + @RequestMapping(value = {"/role_function_list" }, method = RequestMethod.GET) + public ModelAndView welcome(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + + try { + model.put("availableRoleFunctions", mapper.writeValueAsString(service.getRoleFunctions())); + } catch (JsonGenerationException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return new ModelAndView(getViewName(),model); + } + + @RequestMapping(value = {"/get_role_functions" }, method = RequestMethod.GET) + public void getRoleFunctionList(HttpServletRequest request,HttpServletResponse response) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + + try { + model.put("availableRoleFunctions", mapper.writeValueAsString(service.getRoleFunctions())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (JsonGenerationException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + @RequestMapping(value = {"/role_function_list/saveRoleFunction" }, method = RequestMethod.POST) + public ModelAndView saveRoleFunction(HttpServletRequest request, + HttpServletResponse response) throws Exception { + + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + RoleFunction availableRoleFunction = mapper.readValue(root.get("availableRoleFunction").toString(), RoleFunction.class); + + RoleFunction domainRoleFunction = service.getRoleFunction(availableRoleFunction.getCode()); + + //role. toggle active ind + domainRoleFunction.setName(availableRoleFunction.getName()); + domainRoleFunction.setCode(availableRoleFunction.getCode()); + + service.saveRoleFunction(domainRoleFunction); + logger.info(EELFLoggerDelegate.auditLogger, "Save role function " + domainRoleFunction.getName()); + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(service.getRoleFunctions()); + JSONObject j = new JSONObject("{availableRoleFunctions: "+responseString+"}"); + + out.write(j.toString()); + + return null; + } catch (Exception e) { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } + + @RequestMapping(value = {"/role_function_list/removeRoleFunction" }, method = RequestMethod.POST) + public ModelAndView removeRoleFunction(HttpServletRequest request, + HttpServletResponse response) throws Exception { + + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + RoleFunction availableRoleFunction = mapper.readValue(root.get("availableRoleFunction").toString(), RoleFunction.class); + + RoleFunction domainRoleFunction = service.getRoleFunction(availableRoleFunction.getCode()); + + service.deleteRoleFunction(domainRoleFunction); + logger.info(EELFLoggerDelegate.auditLogger, "Remove role function " + domainRoleFunction.getName()); + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(service.getRoleFunctions()); + JSONObject j = new JSONObject("{availableRoleFunctions: "+responseString+"}"); + out.write(j.toString()); + + return null; + } catch (Exception e) { + System.out.println(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } + + public String getViewName() { + return viewName; + } + public void setViewName(String viewName) { + this.viewName = viewName; + } + + +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleListController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleListController.java new file mode 100644 index 00000000..78fbc19f --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/RoleListController.java @@ -0,0 +1,179 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.RoleService; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class RoleListController extends RestrictedBaseController { + @Autowired + RoleService service; + String viewName; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleListController.class); + + + @RequestMapping(value = {"/role_list" }, method = RequestMethod.GET) + public ModelAndView role(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + + try { + model.put("availableRoles", mapper.writeValueAsString(service.getAvailableRoles())); + } catch (JsonGenerationException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return new ModelAndView(getViewName(),model); + } + + @RequestMapping(value = {"/get_roles" }, method = RequestMethod.GET) + public void getRoles(HttpServletRequest request, HttpServletResponse response) { + Map<String, Object> model = new HashMap<String, Object>(); + ObjectMapper mapper = new ObjectMapper(); + + try { + model.put("availableRoles", mapper.writeValueAsString(service.getAvailableRoles())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (JsonGenerationException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + + @RequestMapping(value = {"/role_list/toggleRole" }, method = RequestMethod.POST) + public ModelAndView toggleRole(HttpServletRequest request, + HttpServletResponse response) throws Exception { + + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + Role role = mapper.readValue(root.get("role").toString(), Role.class); + + Role domainRole = service.getRole(role.getId()); + //role. toggle active ind + boolean active = domainRole.getActive(); + domainRole.setActive(!active); + + service.saveRole(domainRole); + logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId()); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(service.getAvailableRoles()); + JSONObject j = new JSONObject("{availableRoles: "+responseString+"}"); + + out.write(j.toString()); + + return null; + } catch (Exception e) { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } + + @RequestMapping(value = {"/role_list/removeRole" }, method = RequestMethod.POST) + public ModelAndView removeRole(HttpServletRequest request, + HttpServletResponse response) throws Exception { + + try { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + Role role = mapper.readValue(root.get("role").toString(), Role.class); + + Role domainRole = service.getRole(role.getId()); + + service.deleteDependcyRoleRecord(role.getId()); + service.deleteRole(domainRole); + logger.info(EELFLoggerDelegate.auditLogger, "Remove role " + domainRole.getId()); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(service.getAvailableRoles()); + JSONObject j = new JSONObject("{availableRoles: "+responseString+"}"); + out.write(j.toString()); + + return null; + } catch (Exception e) { + System.out.println(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + return null; + } + + } + + public String getViewName() { + return viewName; + } + public void setViewName(String viewName) { + this.viewName = viewName; + } +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/SingleSignOnController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/SingleSignOnController.java new file mode 100644 index 00000000..4a0fb6f7 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/SingleSignOnController.java @@ -0,0 +1,232 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalsdk.core.command.LoginBean; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.menu.MenuProperties; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalTimeoutHandler; +import org.openecomp.portalsdk.core.service.LoginService; +import org.openecomp.portalsdk.core.service.ProfileService; +import org.openecomp.portalsdk.core.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.util.WebUtils; + +@Controller +@RequestMapping("/") +public class SingleSignOnController extends UnRestrictedBaseController { + + private static final String EP_SERVICE = "EPService"; + private static final String USER_ID = "UserId"; + public static final String DEFAULT_SUCCESS_VIEW = "welcome"; + public static final String DEFAULT_FAILURE_VIEW = "login"; + public static final String ERROR_MESSAGE_KEY = "error"; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SingleSignOnController.class); + + @Autowired + ProfileService service; + @Autowired + private LoginService loginService; + String viewName; + private String welcomeView; + + public String getWelcomeView() { + return welcomeView; + } + + public void setWelcomeView(String welcomeView) { + this.welcomeView = welcomeView; + } + + /** + * Handles requests directed to the single sign-on page by the session + * timeout interceptor. + * + * @param request + * @return Redirect to an appropriate address + * @throws Exception + */ + @RequestMapping(value = { "/single_signon.htm" }, method = RequestMethod.GET) + public ModelAndView singleSignOnLogin(HttpServletRequest request) throws Exception { + + Map<String, String> model = new HashMap<String, String>(); + HashMap<String, String> additionalParamsMap = new HashMap<String, String>(); + LoginBean commandBean = new LoginBean(); + + // SessionTimeoutInterceptor sets these parameters + String forwardURL = URLDecoder.decode(request.getParameter("forwardURL"), "UTF-8"); + String redirectToPortal = request.getParameter("redirectToPortal"); + + if (isLoginCookieExist(request) && redirectToPortal == null) { + HttpSession session = null; + session = AppUtils.getSession(request); + User user = UserUtils.getUserSession(request); + if (session == null || user == null) { + String orgUserId = ""; + orgUserId = getUserIdFromCookie(request); + commandBean.setUserid(orgUserId); + commandBean = getLoginService().findUser(commandBean, + (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), + additionalParamsMap); + if (commandBean.getUser() == null) { + String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) + ? commandBean.getLoginErrorMessage() + : SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_NOT_FOUND; + model.put(ERROR_MESSAGE_KEY, SystemProperties.getProperty(loginErrorMessage)); + final String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL) + + "?noUserError=Yes"; + logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: user is null, redirect URL is {}", + redirectUrl); + return new ModelAndView("redirect:" + redirectUrl); + } else { + // store the user's information in the session + + UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), + commandBean.getBusinessDirectMenu(), ""); + initateSessionMgtHandler(request); + logger.debug(EELFLoggerDelegate.debugLogger, + "singleSignOnLogin: create new user session for expired user {}; user {} exists in the system", + commandBean.getUser().getOrgUserId()); + return new ModelAndView("redirect:" + forwardURL); + } + } // user is null or session is null + else { + // both user and session are non-null. + logger.info(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: redirecting to the forwardURL {}", + forwardURL); + return new ModelAndView("redirect:" + forwardURL); + } + + } else { + /* + * Login cookie not found, or redirect-to-portal parameter was found. + * + * Redirect the user to the portal with a suitable return URL. The + * forwardURL parameter that arrives as a parameter is a partial + * (not absolute) request path for a page in the application. The + * challenge here is to compute the correct absolute path for the + * original request so the portal can redirect the user back to the + * right place. + */ + String returnToAppUrl = null; + if (SystemProperties.containsProperty(SystemProperties.APP_BASE_URL)) { + // New feature: + // application can publish a base URL in system.properties + String appUrl = SystemProperties.getProperty(SystemProperties.APP_BASE_URL); + returnToAppUrl = appUrl + (appUrl.endsWith("/") ? "" : "/") + forwardURL; + logger.debug(EELFLoggerDelegate.debugLogger, + "singleSignOnLogin: using app base URL {} and redirectURL {}", appUrl, returnToAppUrl); + } else { + // Be backward compatible with applications that don't need this + // feature. + // This is the controller for the single_signon.htm page, so the + // replace + // should always find the specified token. + returnToAppUrl = ((HttpServletRequest) request).getRequestURL().toString().replace("single_signon.htm", + forwardURL); + logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: computed redirectURL {}", returnToAppUrl); + } + final String encodedReturnToAppUrl = URLEncoder.encode(returnToAppUrl, "UTF-8"); + // Also send the application's UEB key so Portal can block URL + // reflection attacks. + final String uebAppKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); + final String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); + final String portalUrl = url.substring(0, url.lastIndexOf('/')) + "/processSingleSignOn"; + final String redirectUrl = portalUrl + "?uebAppKey=" + uebAppKey + "&redirectUrl=" + encodedReturnToAppUrl; + logger.debug(EELFLoggerDelegate.debugLogger, "singleSignOnLogin: portal-bound redirect URL is {}", + redirectUrl); + return new ModelAndView("redirect:" + redirectUrl); + } + } + + protected void initateSessionMgtHandler(HttpServletRequest request) { + String portalJSessionId = getPortalJSessionId(request); + String jSessionId = getJessionId(request); + PortalTimeoutHandler.sessionCreated(portalJSessionId, jSessionId, AppUtils.getSession(request)); + } + + public boolean isLoginCookieExist(HttpServletRequest request) { + Cookie ep = WebUtils.getCookie(request, EP_SERVICE); + return (ep != null); + } + + public static String getUserIdFromCookie(HttpServletRequest request) throws Exception { + String userId = ""; + Cookie[] cookies = request.getCookies(); + Cookie userIdcookie = null; + if (cookies != null) + for (Cookie cookie : cookies) + if (cookie.getName().equals(USER_ID)) + userIdcookie = cookie; + if(userIdcookie!=null){ + userId = CipherUtil.decrypt(userIdcookie.getValue(), + SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } + return userId; + + } + + public String getPortalJSessionId(HttpServletRequest request) { + Cookie ep = WebUtils.getCookie(request, EP_SERVICE); + return ep.getValue(); + + } + + public String getJessionId(HttpServletRequest request) { + return request.getSession().getId(); + } + + public String getViewName() { + return viewName; + } + + public void setViewName(String viewName) { + this.viewName = viewName; + } + + public LoginService getLoginService() { + return loginService; + } + + public void setLoginService(LoginService loginService) { + this.loginService = loginService; + } + +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/UnRestrictedBaseController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/UnRestrictedBaseController.java new file mode 100644 index 00000000..78bf4c51 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/UnRestrictedBaseController.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +public class UnRestrictedBaseController extends FusionBaseController{ + protected String viewName; + + @Override + public boolean isAccessible() { + return true; + } + @Override + public boolean isRESTfulCall(){ + return false; + } + protected String getViewName() { + return viewName; + } + + protected void setViewName(String viewName) { + this.viewName = viewName; + } +} diff --git a/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/UsageListController.java b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/UsageListController.java new file mode 100644 index 00000000..c5616575 --- /dev/null +++ b/ecomp-sdk/quantum/src/main/java/org/openecomp/portalsdk/core/controller/UsageListController.java @@ -0,0 +1,163 @@ +/*- + * ================================================================================ + * eCOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalsdk.core.controller; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.portalsdk.core.command.UserRowBean; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.UsageUtils; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +@Controller +@RequestMapping("/") +public class UsageListController extends RestrictedBaseController { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UsageListController.class); + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @RequestMapping(value = { "/usage_list" }, method = RequestMethod.GET) + public ModelAndView usageList(HttpServletRequest request) { + Map<String, Object> model = new HashMap<String, Object>(); + + HttpSession httpSession = request.getSession(); + HashMap activeUsers = (HashMap) httpSession.getServletContext().getAttribute("activeUsers"); + if (activeUsers.size() == 0) { + activeUsers.put(httpSession.getId(), httpSession); + httpSession.getServletContext().setAttribute("activeUsers", activeUsers); + } + ArrayList<UserRowBean> rows = UsageUtils.getActiveUsers(activeUsers); + JSONArray ja = new JSONArray(); + try { + for (UserRowBean userRowBean : rows) { + JSONObject jo = new JSONObject(); + jo.put("id", userRowBean.getId()); + jo.put("lastName", userRowBean.getLastName()); + jo.put("email", userRowBean.getEmail()); + jo.put("lastAccess", userRowBean.getLastAccess()); + jo.put("remaining", userRowBean.getRemaining()); + jo.put("sessionId", userRowBean.getSessionId()); + if (!(httpSession.getId().equals(userRowBean.getSessionId()))) { + jo.put("delete", "yes"); + } else { + jo.put("delete", "no"); + } + ja.put(jo); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "usageList 1: failed" + e.getMessage()); + } + + model.put("model", ja); + + return new ModelAndView(getViewName(), model); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @RequestMapping(value = { "/get_usage_list" }, method = RequestMethod.GET) + public void usageList(HttpServletRequest request, HttpServletResponse response) { + HttpSession httpSession = request.getSession(); + HashMap activeUsers = (HashMap) httpSession.getServletContext().getAttribute("activeUsers"); + if (activeUsers.size() == 0) { + activeUsers.put(httpSession.getId(), httpSession); + httpSession.getServletContext().setAttribute("activeUsers", activeUsers); + } + ArrayList<UserRowBean> rows = UsageUtils.getActiveUsers(activeUsers); + JSONArray ja = new JSONArray(); + try { + for (UserRowBean userRowBean : rows) { + JSONObject jo = new JSONObject(); + jo.put("id", userRowBean.getId()); + jo.put("lastName", userRowBean.getLastName()); + jo.put("email", userRowBean.getEmail()); + jo.put("lastAccess", userRowBean.getLastAccess()); + jo.put("remaining", userRowBean.getRemaining()); + jo.put("sessionId", userRowBean.getSessionId()); + if (!(httpSession.getId().equals(userRowBean.getSessionId()))) { + jo.put("delete", "yes"); + } else { + jo.put("delete", "no"); + } + ja.put(jo); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "usageList 2: failed" + e.getMessage()); + } + JsonMessage msg; + try { + msg = new JsonMessage(ja.toString()); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "usageList 3: failed" + e.getMessage()); + } + + } + + @SuppressWarnings("rawtypes") + @RequestMapping(value = { "/usage_list/removeSession" }, method = RequestMethod.GET) + public void removeSession(HttpServletRequest request, HttpServletResponse response) throws Exception { + HashMap activeUsers = (HashMap) request.getSession().getServletContext().getAttribute("activeUsers"); + UserRowBean data = new UserRowBean(); + data.setSessionId(request.getParameter("deleteSessionId")); + UsageUtils.getActiveUsersAfterDelete(activeUsers, data); + + HttpSession httpSession = request.getSession(); + ArrayList<UserRowBean> rows = UsageUtils.getActiveUsers(activeUsers); + JSONArray ja = new JSONArray(); + try { + for (UserRowBean userRowBean : rows) { + JSONObject jo = new JSONObject(); + jo.put("id", userRowBean.getId()); + jo.put("lastName", userRowBean.getLastName()); + jo.put("email", userRowBean.getEmail()); + jo.put("lastAccess", userRowBean.getLastAccess()); + jo.put("remaining", userRowBean.getRemaining()); + jo.put("sessionId", userRowBean.getSessionId()); + if (!(httpSession.getId().equals(userRowBean.getSessionId()))) { + jo.put("delete", "yes"); + } else { + jo.put("delete", "no"); + } + ja.put(jo); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "removeSession: failed" + e.getMessage()); + } + + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.write(ja.toString()); + } + +} |