From: Dominik Mizyn Date: Wed, 15 Jan 2020 14:53:11 +0000 (+0100) Subject: SharedContextRestController up X-Git-Tag: 3.2.0~37^2~2 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=portal.git;a=commitdiff_plain;h=f7e300301a4a5f01585677657b96a80338cdf03d SharedContextRestController up SharedContextRestController up with all needed services Issue-ID: PORTAL-710 Change-Id: Ia11ca8d2fda65b6d0a435d4b14e6b61638ed9f65 Signed-off-by: Dominik Mizyn --- diff --git a/portal-BE/src/main/java/org/onap/portal/configuration/DBInitializingBean.java b/portal-BE/src/main/java/org/onap/portal/configuration/DBInitializingBean.java index 3f5b3883..7f928990 100644 --- a/portal-BE/src/main/java/org/onap/portal/configuration/DBInitializingBean.java +++ b/portal-BE/src/main/java/org/onap/portal/configuration/DBInitializingBean.java @@ -82,8 +82,6 @@ import org.onap.portal.service.user.FnUserService; import org.onap.portal.service.userRole.FnUserRoleService; import org.onap.portal.service.widgetCatalog.EpWidgetCatalogService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import java.math.BigInteger; @@ -1234,18 +1232,18 @@ public class DBInitializingBean implements org.springframework.beans.factory.Ini // fn_shared_context table - FnSharedContext sharedContext1 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_FIRST_NAME").cvalue("Jimmy").build(); - FnSharedContext sharedContext2 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_LAST_NAME").cvalue("Hendrix").build(); - FnSharedContext sharedContext3 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_EMAIL").cvalue("admin@onap.org").build(); - FnSharedContext sharedContext4 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_ORG_USERID").cvalue("jh0003").build(); - FnSharedContext sharedContext5 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_FIRST_NAME").cvalue("Demo").build(); - FnSharedContext sharedContext6 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_LAST_NAME").cvalue("User").build(); - FnSharedContext sharedContext7 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_EMAIL").cvalue("demo@openecomp.org").build(); - FnSharedContext sharedContext8 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_ORG_USERID").cvalue("demo").build(); - FnSharedContext sharedContext9 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_FIRST_NAME").cvalue("Demo").build(); - FnSharedContext sharedContext10 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_LAST_NAME").cvalue("User").build(); - FnSharedContext sharedContext11 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_EMAIL").cvalue("demo@openecomp.org").build(); - FnSharedContext sharedContext12 = FnSharedContext.builder().createTime(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_ORG_USERID").cvalue("demo").build(); + FnSharedContext sharedContext1 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_FIRST_NAME").cvalue("Jimmy").build(); + FnSharedContext sharedContext2 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_LAST_NAME").cvalue("Hendrix").build(); + FnSharedContext sharedContext3 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_EMAIL").cvalue("admin@onap.org").build(); + FnSharedContext sharedContext4 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("b999771d~2d60~4638~a670~d47d17219157").ckey("USER_ORG_USERID").cvalue("jh0003").build(); + FnSharedContext sharedContext5 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_FIRST_NAME").cvalue("Demo").build(); + FnSharedContext sharedContext6 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_LAST_NAME").cvalue("User").build(); + FnSharedContext sharedContext7 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_EMAIL").cvalue("demo@openecomp.org").build(); + FnSharedContext sharedContext8 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("29cc8f94~5a7d~41f8~b359~432bb903a718").ckey("USER_ORG_USERID").cvalue("demo").build(); + FnSharedContext sharedContext9 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_FIRST_NAME").cvalue("Demo").build(); + FnSharedContext sharedContext10 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_LAST_NAME").cvalue("User").build(); + FnSharedContext sharedContext11 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_EMAIL").cvalue("demo@openecomp.org").build(); + FnSharedContext sharedContext12 = FnSharedContext.builder().created(LocalDateTime.now()).contextId("7e3ced0a~52a3~492a~be53~2885d2df5a43").ckey("USER_ORG_USERID").cvalue("demo").build(); List sharedContexts = new ArrayList<>(Arrays.asList(sharedContext1, sharedContext2, sharedContext3, sharedContext4, sharedContext5, sharedContext6, sharedContext7, sharedContext8, sharedContext9, sharedContext10, sharedContext11, sharedContext12)); diff --git a/portal-BE/src/main/java/org/onap/portal/controller/SharedContextRestController.java b/portal-BE/src/main/java/org/onap/portal/controller/SharedContextRestController.java new file mode 100644 index 00000000..85425462 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/SharedContextRestController.java @@ -0,0 +1,264 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portal.controller; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.annotations.ApiOperation; +import java.io.IOException; +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.onap.portal.domain.db.fn.FnSharedContext; +import org.onap.portal.domain.dto.ecomp.SharedContext; +import org.onap.portal.exception.NotValidDataException; +import org.onap.portal.logging.aop.EPAuditLog; +import org.onap.portal.service.sharedContext.FnSharedContextService; +import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portal.utils.PortalConstants; +import org.onap.portal.validation.DataValidator; +import org.onap.portal.validation.SecureString; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +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.RequestParam; +import org.springframework.web.bind.annotation.RestController; + + +@Configuration +@RestController +@RequestMapping(PortalConstants.REST_AUX_API + "/context") +@EnableAspectJAutoProxy +@EPAuditLog +public class SharedContextRestController { + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class); + private static final ObjectMapper mapper = new ObjectMapper(); + + private final FnSharedContextService contextService; + private final DataValidator dataValidator; + + @Autowired + public SharedContextRestController(FnSharedContextService contextService, + DataValidator dataValidator) { + this.contextService = contextService; + this.dataValidator = dataValidator; + } + + @ApiOperation(value = "Gets a value for the specified context and key.", response = SharedContext.class) + @RequestMapping(value = { "/get" }, method = RequestMethod.GET, produces = "application/json") + public String getContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey) + throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "getContext for ID " + context_id + ", key " + ckey); + if (context_id == null || ckey == null) + throw new Exception("Received null for context_id and/or ckey"); + SecureString secureContextId = new SecureString(context_id); + SecureString secureCKey = new SecureString(ckey); + + if(!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey)){ + throw new NotValidDataException("Received not valid for context_id and/or ckey"); + } + + FnSharedContext context = contextService.getFnSharedContext(context_id, ckey); + String jsonResponse; + if (context == null) + jsonResponse = convertResponseToJSON(context); + else + jsonResponse = mapper.writeValueAsString(context); + + return jsonResponse; + } + + @ApiOperation(value = "Gets user information for the specified context.", response = SharedContext.class, responseContainer = "List") + @RequestMapping(value = { "/get_user" }, method = RequestMethod.GET, produces = "application/json") + public String getUserContext(HttpServletRequest request, @RequestParam String context_id) throws Exception { + + logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id); + if (context_id == null) + throw new Exception("Received null for context_id"); + SecureString secureContextId = new SecureString(context_id); + if (!dataValidator.isValid(secureContextId)) + throw new NotValidDataException("context_id is not valid"); + + List listSharedContext = new ArrayList<>(); + FnSharedContext firstNameContext = contextService.getFnSharedContext(context_id, + EPCommonSystemProperties.USER_FIRST_NAME); + FnSharedContext lastNameContext = contextService.getFnSharedContext(context_id, + EPCommonSystemProperties.USER_LAST_NAME); + FnSharedContext emailContext = contextService.getFnSharedContext(context_id, EPCommonSystemProperties.USER_EMAIL); + FnSharedContext orgUserIdContext = contextService.getFnSharedContext(context_id, + EPCommonSystemProperties.USER_ORG_USERID); + if (firstNameContext != null) + listSharedContext.add(firstNameContext); + if (lastNameContext != null) + listSharedContext.add(lastNameContext); + if (emailContext != null) + listSharedContext.add(emailContext); + if (orgUserIdContext != null) + listSharedContext.add(orgUserIdContext); + return convertResponseToJSON(listSharedContext); + } + + @ApiOperation(value = "Tests for presence of the specified key in the specified context.") + @RequestMapping(value = { "/check" }, method = RequestMethod.GET, produces = "application/json") + public String checkContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey) + throws Exception { + + logger.debug(EELFLoggerDelegate.debugLogger, "checkContext for " + context_id + ", key " + ckey); + if (context_id == null || ckey == null) + throw new Exception("Received null for contextId and/or key"); + + SecureString secureContextId = new SecureString(context_id); + SecureString secureCKey = new SecureString(ckey); + + if (!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey)) + throw new NotValidDataException("Not valid data for contextId and/or key"); + + String response = null; + FnSharedContext context = contextService.getFnSharedContext(context_id, ckey); + if (context != null) + response = "exists"; + + return convertResponseToJSON(response); + } + + @ApiOperation(value = "Removes the specified key in the specified context.") + @RequestMapping(value = { "/remove" }, method = RequestMethod.GET, produces = "application/json") + public String removeContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey) + throws Exception { + + logger.debug(EELFLoggerDelegate.debugLogger, "removeContext for " + context_id + ", key " + ckey); + if (context_id == null || ckey == null) + throw new Exception("Received null for contextId and/or key"); + + SecureString secureContextId = new SecureString(context_id); + SecureString secureCKey = new SecureString(ckey); + + if (!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey)) + throw new NotValidDataException("Not valid data for contextId and/or key"); + + FnSharedContext context = contextService.getFnSharedContext(context_id, ckey); + String response = null; + if (context != null) { + contextService.delete(context); + response = "removed"; + } + + return convertResponseToJSON(response); + } + + @ApiOperation(value = "Clears all key-value pairs in the specified context.") + @RequestMapping(value = { "/clear" }, method = RequestMethod.GET, produces = "application/json") + public String clearContext(HttpServletRequest request, @RequestParam String contextId) throws Exception { + + logger.debug(EELFLoggerDelegate.debugLogger, "clearContext for " + contextId); + if (contextId == null) + throw new Exception("clearContext: Received null for contextId"); + + SecureString secureContextId = new SecureString(contextId); + + if (!dataValidator.isValid(secureContextId)) + throw new NotValidDataException("Not valid data for contextId"); + + int count = contextService.deleteSharedContexts(contextId); + return convertResponseToJSON(Integer.toString(count)); + } + + @ApiOperation(value = "Sets a context value for the specified context and key. Creates the context if no context with the specified ID-key pair exists, overwrites the value if it exists already.") + @RequestMapping(value = { "/set" }, method = RequestMethod.POST, produces = "application/json") + public String setContext(HttpServletRequest request, @RequestBody String userJson) throws Exception { + if (userJson !=null){ + SecureString secureUserJson = new SecureString(userJson); + if (!dataValidator.isValid(secureUserJson)) + throw new NotValidDataException("Not valid data for userJson"); + } + + @SuppressWarnings("unchecked") + Map userData = mapper.readValue(userJson, Map.class); + // Use column names as JSON tags + final String contextId = (String) userData.get("context_id"); + final String key = (String) userData.get("ckey"); + final String value = (String) userData.get("cvalue"); + if (contextId == null || key == null) + throw new Exception("setContext: received null for contextId and/or key"); + + logger.debug(EELFLoggerDelegate.debugLogger, "setContext: ID " + contextId + ", key " + key + "->" + value); + String response; + FnSharedContext existing = contextService.getFnSharedContext(contextId, key); + if (existing == null) { + contextService.addFnSharedContext(contextId, key, value); + } else { + existing.setCvalue(value); + contextService.save(existing); + } + response = existing == null ? "added" : "replaced"; + return convertResponseToJSON(response); + } + + private String convertResponseToJSON(String responseBody) throws JsonProcessingException { + Map responseMap = new HashMap<>(); + responseMap.put("response", responseBody); + return mapper.writeValueAsString(responseMap); + } + + private String convertResponseToJSON(List contextList) throws JsonProcessingException { + return mapper.writeValueAsString(contextList); + } + + private String convertResponseToJSON(FnSharedContext context) throws JsonProcessingException { + Map responseMap = new HashMap<>(); + responseMap.put("response", context); + return mapper.writeValueAsString(responseMap); + } + + @ExceptionHandler(Exception.class) + protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException { + logger.error(EELFLoggerDelegate.errorLogger, "handleBadRequest caught exception", e); + response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage()); + } + +} + diff --git a/portal-BE/src/main/java/org/onap/portal/controller/TicketEventController.java b/portal-BE/src/main/java/org/onap/portal/controller/TicketEventController.java index 1e8945b0..8610af23 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/TicketEventController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/TicketEventController.java @@ -64,6 +64,7 @@ import org.onap.portal.service.epNotification.EpNotificationService; import org.onap.portal.service.user.FnUserService; import org.onap.portal.utils.EPCommonSystemProperties; import org.onap.portal.utils.PortalConstants; +import org.onap.portal.validation.DataValidator; import org.onap.portal.validation.SecureString; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; @@ -86,14 +87,16 @@ public class TicketEventController { private static final String EVENT_DATE = "eventDate"; private final ObjectMapper objectMapper = new ObjectMapper(); - private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); + private final DataValidator dataValidator; private final FnUserService fnUserService; private final EpNotificationService epNotificationService; @Autowired - public TicketEventController(final FnUserService fnUserService, + public TicketEventController(final DataValidator dataValidator, + final FnUserService fnUserService, final EpNotificationService epNotificationService) { + this.dataValidator = dataValidator; this.fnUserService = fnUserService; this.epNotificationService = epNotificationService; } @@ -108,16 +111,10 @@ public class TicketEventController { logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson); PortalRestResponse portalResponse = new PortalRestResponse<>(); - if (ticketEventJson != null) { - SecureString secureString = new SecureString(ticketEventJson); - Validator validator = VALIDATOR_FACTORY.getValidator(); - - Set> constraintViolations = validator.validate(secureString); - if (!constraintViolations.isEmpty()) { - portalResponse.setStatus(PortalRestStatusEnum.ERROR); - portalResponse.setMessage("Data is not valid"); - return portalResponse; - } + if(!dataValidator.isValid(ticketEventJson)){ + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Data is not valid"); + return portalResponse; } try { diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnSharedContext.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnSharedContext.java index ca16d343..a348ef43 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnSharedContext.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnSharedContext.java @@ -42,17 +42,17 @@ package org.onap.portal.domain.db.fn; import java.io.Serializable; import java.time.LocalDateTime; +import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.SequenceGenerator; +import javax.persistence.NamedNativeQueries; +import javax.persistence.NamedNativeQuery; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; -import javax.validation.constraints.PastOrPresent; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; @@ -60,6 +60,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.validator.constraints.SafeHtml; +import org.onap.portal.domain.db.DomainVo; /* CREATE TABLE `fn_shared_context` ( @@ -73,25 +74,32 @@ CREATE TABLE `fn_shared_context` ( ) */ +@NamedQueries({ + @NamedQuery( + name = "FnSharedContext.getByContextId", + query = "FROM FnSharedContext WHERE contextId = :contextId"), + @NamedQuery( + name = "FnSharedContext.getByContextIdAndCkey", + query = "FROM FnSharedContext WHERE contextId = :contextId and ckey = :ckey") +}) + +@NamedNativeQueries({ + @NamedNativeQuery( + name = "FnSharedContext.deleteByCreated", + query = "delete FnSharedContext where created < :created" + ) +}) + @Table(name = "fn_shared_context", uniqueConstraints ={ @UniqueConstraint(columnNames = {"context_Id", "ckey"}) }) @NoArgsConstructor @AllArgsConstructor -@Builder @Getter @Setter @Entity -public class FnSharedContext implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id", nullable = false, length = 11, columnDefinition = "int(11) AUTO_INCREMENT") - @Digits(integer = 11, fraction = 0) - private Long id; - @Column(name = "create_time", nullable = false, columnDefinition = "timestamp DEFAULT current_timestamp() ON UPDATE current_timestamp()") - @PastOrPresent - @NotNull - private LocalDateTime createTime; +public class FnSharedContext extends DomainVo implements Serializable { + @Column(name = "context_id", length = 64, nullable = false) @Size(max = 64) @SafeHtml @@ -107,4 +115,19 @@ public class FnSharedContext implements Serializable { @SafeHtml @NotNull private String cvalue; + + @Builder + public FnSharedContext(@Digits(integer = 11, fraction = 0) Long id, + LocalDateTime created, LocalDateTime modified, Long rowNum, Serializable auditUserId, + DomainVo createdId, DomainVo modifiedId, Set fnUsersCreatedId, + Set fnUsersModifiedId, + @Size(max = 64) @NotNull String contextId, + @Size(max = 128) @NotNull String ckey, + @Size(max = 1024) @NotNull String cvalue) { + super(id, created, modified, rowNum, auditUserId, createdId, modifiedId, fnUsersCreatedId, + fnUsersModifiedId); + this.contextId = contextId; + this.ckey = ckey; + this.cvalue = cvalue; + } } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java index 277b04d8..6800b0c5 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java @@ -523,7 +523,6 @@ public class FnUser extends DomainVo implements UserDetails, Serializable { } @Builder - public FnUser(@Digits(integer = 11, fraction = 0) Long id, LocalDateTime created, LocalDateTime modified, Long rowNum, Serializable auditUserId, DomainVo createdId, DomainVo modifiedId, Set fnUsersCreatedId, Set fnUsersModifiedId, FnOrg orgId, diff --git a/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextDao.java b/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextDao.java index 8faac5b6..df251027 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextDao.java +++ b/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextDao.java @@ -40,8 +40,13 @@ package org.onap.portal.service.sharedContext; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; import org.onap.portal.domain.db.fn.FnSharedContext; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @@ -49,4 +54,11 @@ import org.springframework.transaction.annotation.Transactional; @Transactional interface FnSharedContextDao extends JpaRepository { + @Query + Optional> getByContextId(@Param("contextId") final String contextId); + @Query + Optional> getByContextIdAndCkey(@Param("contextId") final String contextId, @Param("ckey") final String ckey); + @Query + void deleteByCreated(@Param("created") final LocalDateTime created); + } diff --git a/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextService.java b/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextService.java index 7a427ae9..ee0be613 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/sharedContext/FnSharedContextService.java @@ -1,22 +1,128 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ package org.onap.portal.service.sharedContext; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Optional; import org.onap.portal.domain.db.fn.FnSharedContext; +import org.onap.portal.logging.aop.EPMetricsLog; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; -import java.util.List; @Service +@Transactional +@EnableAspectJAutoProxy +@EPMetricsLog public class FnSharedContextService { - private final FnSharedContextDao fnSharedContextDao; + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnSharedContextService.class); + + private final FnSharedContextDao fnSharedContextDao; + + @Autowired + public FnSharedContextService(final FnSharedContextDao fnSharedContextDao) { + this.fnSharedContextDao = fnSharedContextDao; + } + + public List getSharedContexts(String contextId) { + return fnSharedContextDao.getByContextId(contextId).orElse(new ArrayList<>()); + } + + public FnSharedContext getFnSharedContext(String contextId, String ckey) { + FnSharedContext context = null; + Optional> contexts = fnSharedContextDao.getByContextIdAndCkey(contextId, ckey); + if (contexts.isPresent() && contexts.get().size() == 1) { + context = contexts.get().get(0); + } + return context; + } + + public FnSharedContext addFnSharedContext(String contextId, String key, String value) { + return this.save(new FnSharedContext(contextId, key, value)); + } + + + public FnSharedContext save(FnSharedContext context) { + return this.fnSharedContextDao.saveAndFlush(context); + } + + public List saveAll(List fnSharedContexts){ + return fnSharedContextDao.saveAll(fnSharedContexts); + } + + public void delete(FnSharedContext context) { + this.fnSharedContextDao.delete(context); + } + + public int deleteSharedContexts(String contextId) { + // Uses an inefficient method to avoid a where clause + // that could be used to mount a SQL injection attack. + List contexts = getSharedContexts(contextId); + if (contexts == null) + return 0; + + logger.debug(EELFLoggerDelegate.debugLogger, "deleteFnSharedContexts: count is " + contexts.size()); + for (FnSharedContext sc : contexts) + this.delete(sc); + + return contexts.size(); + } - @Autowired - public FnSharedContextService(FnSharedContextDao fnSharedContextDao) { - this.fnSharedContextDao = fnSharedContextDao; - } + public void expireFnSharedContexts(int ageInSeconds) { + Date expiredDateTime = new Date(System.currentTimeMillis() - ageInSeconds * 1000); + logger.debug(EELFLoggerDelegate.debugLogger, + "expireFnSharedContexts: expire time is " + expiredDateTime.toString()); + this.fnSharedContextDao.deleteByCreated(convertToLocalDateTimeViaInstant(expiredDateTime)); + } - public List saveAll(List sharedContexts) { - return fnSharedContextDao.saveAll(sharedContexts); - } + private LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) { + return dateToConvert.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + } }