diff options
author | Christopher Lott (Christopher) (cl778h) <clott@vm-ep-dev2.client.research.att.com> | 2017-06-12 09:49:00 -0400 |
---|---|---|
committer | Christopher Lott (cl778h) <clott@research.att.com> | 2017-06-12 13:42:43 -0400 |
commit | 627badaf69987c01811c477219fd943757a635f5 (patch) | |
tree | 97df9449a411d1ecf830cc76d8afd6f9b5677bda /ecomp-portal-BE-common/src/main | |
parent | ba838f2e13f1e8050c75e68bd3733d56d8f416d5 (diff) |
[PORTAL-16 PORTAL-18] Widget ms; staging
Remove staging repositories from poms.
Add widget microservice code base.
Add portal unit tests.
Repair defects.
Normalize line endings.
Change-Id: Ia5e48da2a3141b352439ecd548cddf918f4df585
Signed-off-by: Christopher Lott (cl778h) <clott@research.att.com>
Diffstat (limited to 'ecomp-portal-BE-common/src/main')
208 files changed, 25831 insertions, 23151 deletions
diff --git a/ecomp-portal-BE-common/src/main/java/jarutil/ExtractJar.java b/ecomp-portal-BE-common/src/main/java/jarutil/ExtractJar.java index 76d4b181..e8f828f0 100644 --- a/ecomp-portal-BE-common/src/main/java/jarutil/ExtractJar.java +++ b/ecomp-portal-BE-common/src/main/java/jarutil/ExtractJar.java @@ -1,204 +1,204 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package jarutil;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.Writer;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.jar.JarEntry;
-import java.util.jar.JarInputStream;
-
-public class ExtractJar {
-
- /**
- * @param args
- */
-
- public static int bufferSize = 8192;
- public static String JARFILE = "raptor_upgrade.jar";
-
- public static void main(String[] args) throws Exception {
- if(args.length > 0 && args[0]!=null && args[0].length()>0)
- extractFilesFromJar(args[0]);
- else {
- System.out.println("Current Directory is taken as webapp path");
- String currentDir = new File(".").getAbsolutePath();
- extractFilesFromJar(currentDir);
- }
- }
-
- public static void readJar(File jarFile) throws Exception{
- JarInputStream in = new JarInputStream(new FileInputStream(jarFile));
- ArrayList entries = new ArrayList( );
- JarEntry je;
- while((je=in.getNextJarEntry( ))!=null){
- if( je.isDirectory() == false ) {
- if(je.getName().startsWith("att/raptor/config/")) {
- //while((je=in.getNextJarEntry( ))!=null) {
- System.out.println(je.getName() + " " + je.getTime());
- //}
-
- }
- }
- }
- in.close( );
- }
-
- public static void extractFilesFromJar(String directory) throws IOException{
- //JarFile jar = new JarFile(jarFile);
- Class clazz = ExtractJar.class;
- String classContainer = clazz.getProtectionDomain().getCodeSource().getLocation().toString();
- //System.out.println("classContainer ---------> " + classContainer);
- URL jarUrl = clazz.getProtectionDomain().getCodeSource().getLocation();
-
- JarInputStream entryStream = new JarInputStream(jarUrl.openStream());
- JarEntry entry;
- while(true) {
- entry = entryStream.getNextJarEntry();
- if(entry == null)
- break;
- if(entry.getName().indexOf("jarutil") < 0) {
- System.out.println(entry.getName());
- File file=new File(directory,entry.getName());
- if(entry.isDirectory()) {
- if (!file.exists())
- file.mkdirs();
- } else {
- // make directory (some jars don't list dirs)
- File dir = new File(file.getParent());
- if (!dir.exists())
- dir.mkdirs();
- if(file.exists()) file.delete();
- // Make file
- FileOutputStream fout = new FileOutputStream(file);
- copy(entryStream,fout);
- fout.close();
-
- // touch the file.
- if (entry.getTime()>=0)
- file.setLastModified(entry.getTime());
- }
-
- }
- entryStream.closeEntry();
- }
- entryStream.close();
- System.out.println("************************************************");
- System.out.println("* *");
- System.out.println("* *");
- System.out.println("* RAPTOR SETUP COMPLETE. *");
- System.out.println("* *");
- System.out.println("* Thank you for upgrading. *");
- System.out.println("* *");
- System.out.println("************************************************");
- }
-
-
- public static void copy(InputStream in, OutputStream out, long byteCount)
- throws IOException {
- byte buffer[] = new byte[bufferSize];
- int len=bufferSize;
- if (byteCount>=0) {
- while (byteCount>0) {
- if (byteCount<bufferSize)
- len=in.read(buffer,0,(int)byteCount);
- else
- len=in.read(buffer,0,bufferSize);
- if (len==-1)
- break;
-
- byteCount -= len;
- out.write(buffer,0,len);
- }
- } else {
- while (true) {
- len=in.read(buffer,0,bufferSize);
- if (len<0 )
- break;
- out.write(buffer,0,len);
- }
- }
- }
-
-/* ------------------------------------------------------------------- */
-/** Copy Reader to Writer for byteCount bytes or until EOF or exception.
-*/
- public static void copy(Reader in, Writer out, long byteCount)
- throws IOException {
- char buffer[] = new char[bufferSize];
- int len=bufferSize;
- if (byteCount>=0) {
- while (byteCount>0) {
- if (byteCount<bufferSize)
- len=in.read(buffer,0,(int)byteCount);
- else
- len=in.read(buffer,0,bufferSize);
-
- if (len==-1)
- break;
- byteCount -= len;
- out.write(buffer,0,len);
- }
- } else {
- while (true) {
- len=in.read(buffer,0,bufferSize);
- if (len==-1)
- break;
- out.write(buffer,0,len);
- }
- }
- }
-
- /* ------------------------------------------------------------------- */
- /** Copy Stream in to Stream out until EOF or exception.
- */
- public static void copy(InputStream in, OutputStream out)
- throws IOException
- {
- copy(in,out,-1);
- }
-
- // Deletes all files and subdirectories under dir.
- // Returns true if all deletions were successful.
- // If a deletion fails, the method stops attempting to delete and returns false.
- public static boolean deleteDir(File dir) {
- if (dir.isDirectory()) {
- String[] children = dir.list();
- for (int i=0; i<children.length; i++) {
- boolean success = deleteDir(new File(dir, children[i]));
- if (!success) {
- return false;
- }
- }
- }
-
- // The directory is now empty so delete it
- return dir.delete();
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package jarutil; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; +import java.net.URL; +import java.util.ArrayList; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; + +public class ExtractJar { + + /** + * @param args + */ + + public static int bufferSize = 8192; + public static String JARFILE = "raptor_upgrade.jar"; + + public static void main(String[] args) throws Exception { + if(args.length > 0 && args[0]!=null && args[0].length()>0) + extractFilesFromJar(args[0]); + else { + System.out.println("Current Directory is taken as webapp path"); + String currentDir = new File(".").getAbsolutePath(); + extractFilesFromJar(currentDir); + } + } + + public static void readJar(File jarFile) throws Exception{ + JarInputStream in = new JarInputStream(new FileInputStream(jarFile)); + ArrayList entries = new ArrayList( ); + JarEntry je; + while((je=in.getNextJarEntry( ))!=null){ + if( je.isDirectory() == false ) { + if(je.getName().startsWith("att/raptor/config/")) { + //while((je=in.getNextJarEntry( ))!=null) { + System.out.println(je.getName() + " " + je.getTime()); + //} + + } + } + } + in.close( ); + } + + public static void extractFilesFromJar(String directory) throws IOException{ + //JarFile jar = new JarFile(jarFile); + Class clazz = ExtractJar.class; + String classContainer = clazz.getProtectionDomain().getCodeSource().getLocation().toString(); + //System.out.println("classContainer ---------> " + classContainer); + URL jarUrl = clazz.getProtectionDomain().getCodeSource().getLocation(); + + JarInputStream entryStream = new JarInputStream(jarUrl.openStream()); + JarEntry entry; + while(true) { + entry = entryStream.getNextJarEntry(); + if(entry == null) + break; + if(entry.getName().indexOf("jarutil") < 0) { + System.out.println(entry.getName()); + File file=new File(directory,entry.getName()); + if(entry.isDirectory()) { + if (!file.exists()) + file.mkdirs(); + } else { + // make directory (some jars don't list dirs) + File dir = new File(file.getParent()); + if (!dir.exists()) + dir.mkdirs(); + if(file.exists()) file.delete(); + // Make file + FileOutputStream fout = new FileOutputStream(file); + copy(entryStream,fout); + fout.close(); + + // touch the file. + if (entry.getTime()>=0) + file.setLastModified(entry.getTime()); + } + + } + entryStream.closeEntry(); + } + entryStream.close(); + System.out.println("************************************************"); + System.out.println("* *"); + System.out.println("* *"); + System.out.println("* RAPTOR SETUP COMPLETE. *"); + System.out.println("* *"); + System.out.println("* Thank you for upgrading. *"); + System.out.println("* *"); + System.out.println("************************************************"); + } + + + public static void copy(InputStream in, OutputStream out, long byteCount) + throws IOException { + byte buffer[] = new byte[bufferSize]; + int len=bufferSize; + if (byteCount>=0) { + while (byteCount>0) { + if (byteCount<bufferSize) + len=in.read(buffer,0,(int)byteCount); + else + len=in.read(buffer,0,bufferSize); + if (len==-1) + break; + + byteCount -= len; + out.write(buffer,0,len); + } + } else { + while (true) { + len=in.read(buffer,0,bufferSize); + if (len<0 ) + break; + out.write(buffer,0,len); + } + } + } + +/* ------------------------------------------------------------------- */ +/** Copy Reader to Writer for byteCount bytes or until EOF or exception. +*/ + public static void copy(Reader in, Writer out, long byteCount) + throws IOException { + char buffer[] = new char[bufferSize]; + int len=bufferSize; + if (byteCount>=0) { + while (byteCount>0) { + if (byteCount<bufferSize) + len=in.read(buffer,0,(int)byteCount); + else + len=in.read(buffer,0,bufferSize); + + if (len==-1) + break; + byteCount -= len; + out.write(buffer,0,len); + } + } else { + while (true) { + len=in.read(buffer,0,bufferSize); + if (len==-1) + break; + out.write(buffer,0,len); + } + } + } + + /* ------------------------------------------------------------------- */ + /** Copy Stream in to Stream out until EOF or exception. + */ + public static void copy(InputStream in, OutputStream out) + throws IOException + { + copy(in,out,-1); + } + + // Deletes all files and subdirectories under dir. + // Returns true if all deletions were successful. + // If a deletion fails, the method stops attempting to delete and returns false. + public static boolean deleteDir(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + for (int i=0; i<children.length; i++) { + boolean success = deleteDir(new File(dir, children[i])); + if (!success) { + return false; + } + } + } + + // The directory is now empty so delete it + return dir.delete(); + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/NotificationCleanup.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/NotificationCleanup.java new file mode 100644 index 00000000..d525d9bc --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/NotificationCleanup.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.config; + +import java.util.TimerTask; + +import org.openecomp.portalapp.portal.service.UserNotificationService; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public class NotificationCleanup extends TimerTask { + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(NotificationCleanup.class); + + @Override + public void run() { + logger.debug(EELFLoggerDelegate.debugLogger, "run: cleaning the ep-notification table"); + UserNotificationService notificationService = NotificationCleanupConfig.getApplicationContext() + .getBean(UserNotificationService.class); + notificationService.deleteNotificationsFromEpUserNotificationTable(); + notificationService.deleteNotificationsFromEpRoleNotificationTable(); + notificationService.deleteNotificationsFromEpNotificationTable(); + } + +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/NotificationCleanupConfig.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/NotificationCleanupConfig.java new file mode 100644 index 00000000..90e5ecf8 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/NotificationCleanupConfig.java @@ -0,0 +1,62 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.config; + +import java.util.Timer; +import java.util.TimerTask; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class NotificationCleanupConfig implements ApplicationContextAware { + + // Once every 10 minutes should be adequate + public final static int CLEANUP_PERIOD_MINUTES = 10; + + private static ApplicationContext applicationContext; + + public void setApplicationContext(ApplicationContext context) throws BeansException { + applicationContext = context; + } + + public static ApplicationContext getApplicationContext() { + return applicationContext; + + } + + @PostConstruct + public void StartSchedular() { + TimerTask task = new NotificationCleanup(); + Timer timer = new Timer(); + timer.schedule(task, 1000, CLEANUP_PERIOD_MINUTES * 60 * 1000); + } + + @Bean + public NotificationCleanupConfig getConfig() { + return new NotificationCleanupConfig(); + } + +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/SwaggerConfig.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/SwaggerConfig.java index 7082fe78..7d2c0503 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/SwaggerConfig.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/SwaggerConfig.java @@ -1,58 +1,58 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.config;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-import springfox.documentation.builders.ApiInfoBuilder;
-import springfox.documentation.builders.PathSelectors;
-import springfox.documentation.builders.RequestHandlerSelectors;
-import springfox.documentation.service.ApiInfo;
-import springfox.documentation.spi.DocumentationType;
-import springfox.documentation.spring.web.plugins.Docket;
-import springfox.documentation.swagger2.annotations.EnableSwagger2;
-
-@Configuration
-@EnableSwagger2
-public class SwaggerConfig {
-
- @Bean
- public Docket api(){
- return new Docket(DocumentationType.SWAGGER_2)
- .select()
- .apis(RequestHandlerSelectors.any())
- .paths(PathSelectors.regex("/auxapi/.*"))
- .build()
- .apiInfo(apiInfo());
- }
-
- private ApiInfo apiInfo() {
- return new ApiInfoBuilder()
- .title("ECOMP Portal API Documentation")
- .description("ECOMP Portal API Documentation")
- .version("1.2.6")
- .termsOfServiceUrl("http://terms-of-services.url")
- .license("LICENSE")
- .licenseUrl("http://url-to-license.com")
- .build();
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Configuration +@EnableSwagger2 +public class SwaggerConfig { + + @Bean + public Docket api(){ + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.regex("/auxapi/.*")) + .build() + .apiInfo(apiInfo()); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("ECOMP Portal API Documentation") + .description("ECOMP Portal API Documentation") + .version("1.2.6") + .termsOfServiceUrl("http://terms-of-services.url") + .license("LICENSE") + .licenseUrl("http://url-to-license.com") + .build(); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/SwaggerMVCConfig.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/SwaggerMVCConfig.java index 7e2d4540..ff59d42a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/SwaggerMVCConfig.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/SwaggerMVCConfig.java @@ -1,37 +1,37 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.config;
-
-import org.springframework.context.annotation.Configuration;
-import org.springframework.web.servlet.config.annotation.EnableWebMvc;
-import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
-import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
-
-@Configuration
-@EnableWebMvc
-public class SwaggerMVCConfig extends WebMvcConfigurerAdapter {
-
- @Override
- public void addResourceHandlers(ResourceHandlerRegistry registry) {
- registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
- registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +public class SwaggerMVCConfig extends WebMvcConfigurerAdapter { + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/externalsystemapproval/model/ExternalSystemRoleApproval.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/externalsystemapproval/model/ExternalSystemRoleApproval.java index f958d2b5..72d67379 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/externalsystemapproval/model/ExternalSystemRoleApproval.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/externalsystemapproval/model/ExternalSystemRoleApproval.java @@ -1,41 +1,38 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.externalsystemapproval.model;
-
-import java.io.Serializable;
-
-
-public class ExternalSystemRoleApproval implements Serializable{
-
-
- private static final long serialVersionUID = 6048830318039958615L;
-
- private String roleName ;
-
- public String getRoleName() {
- return roleName;
- }
-
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.externalsystemapproval.model; + +import java.io.Serializable; + +public class ExternalSystemRoleApproval implements Serializable { + + private static final long serialVersionUID = 6048830318039958615L; + + private String roleName; + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/externalsystemapproval/model/ExternalSystemUser.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/externalsystemapproval/model/ExternalSystemUser.java index f3ccd14a..38787b53 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/externalsystemapproval/model/ExternalSystemUser.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/externalsystemapproval/model/ExternalSystemUser.java @@ -1,74 +1,74 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.externalsystemapproval.model;
-
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class ExternalSystemUser {
-
- private String loginId;
-
- private String applicationName;
-
- private String myloginrequestId;
-
- private List<ExternalSystemRoleApproval> roles;
-
- public ExternalSystemUser() {
- roles = new ArrayList<ExternalSystemRoleApproval>();
- }
-
- public String getApplicationName() {
- return applicationName;
- }
-
- public void setApplicationName(String applicationName) {
- this.applicationName = applicationName;
- }
-
- public String getLoginId() {
- return loginId;
- }
-
- public void setLoginId(String loginId) {
- this.loginId = loginId;
- }
-
- public List<ExternalSystemRoleApproval> getRoles() {
- return roles;
- }
-
- public void setRoles(List<ExternalSystemRoleApproval> roles) {
- this.roles = roles;
- }
-
- public String getMyloginrequestId() {
- return myloginrequestId;
- }
-
- public void setMyloginrequestId(String myloginrequestId) {
- this.myloginrequestId = myloginrequestId;
- }
-
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.externalsystemapproval.model; + + +import java.util.ArrayList; +import java.util.List; + +public class ExternalSystemUser { + + private String loginId; + + private String applicationName; + + private String myloginrequestId; + + private List<ExternalSystemRoleApproval> roles; + + public ExternalSystemUser() { + roles = new ArrayList<ExternalSystemRoleApproval>(); + } + + public String getApplicationName() { + return applicationName; + } + + public void setApplicationName(String applicationName) { + this.applicationName = applicationName; + } + + public String getLoginId() { + return loginId; + } + + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + public List<ExternalSystemRoleApproval> getRoles() { + return roles; + } + + public void setRoles(List<ExternalSystemRoleApproval> roles) { + this.roles = roles; + } + + public String getMyloginrequestId() { + return myloginrequestId; + } + + public void setMyloginrequestId(String myloginrequestId) { + this.myloginrequestId = myloginrequestId; + } + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/lm/FusionLicenseManagerImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/lm/FusionLicenseManagerImpl.java index e932995f..8979b3f1 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/lm/FusionLicenseManagerImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/lm/FusionLicenseManagerImpl.java @@ -1,88 +1,88 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.lm;
-
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.ServletContext;
-
-import org.openecomp.portalsdk.core.lm.FusionLicenseManager;
-import org.springframework.stereotype.Component;
-
-/*
- * Please note that this class is not being used; its a dummy stub to have a qualifying bean for the interface.
- */
-
-@Component
-public class FusionLicenseManagerImpl implements FusionLicenseManager {
-
- @Override
- public void initKeyStoreParam() {
-
- }
-
- @Override
- public void initCipherParam() {
-
- }
-
- @Override
- public void initLicenseParam() {
-
- }
-
- @Override
- public void doInitWork() {
-
- }
-
- @Override
- public int installLicense() {
- return 0;
- }
-
- @Override
- public synchronized int verifyLicense(ServletContext context) {
- return 0;
- }
-
- @Override
- public void generateLicense(Map<String, String> clientInfoMap, List<String> ipAddressList) throws Exception {
-
- }
-
- @Override
- public String nvl(String s) {
- return null;
- }
-
- @Override
- public Date getExpiredDate() {
- return null;
- }
-
- @Override
- public void setExpiredDate(Date expiredDate) {
-
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.lm; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletContext; + +import org.openecomp.portalsdk.core.lm.FusionLicenseManager; +import org.springframework.stereotype.Component; + +/* + * Please note that this class is not being used; its a dummy stub to have a qualifying bean for the interface. + */ + +@Component +public class FusionLicenseManagerImpl implements FusionLicenseManager { + + @Override + public void initKeyStoreParam() { + + } + + @Override + public void initCipherParam() { + + } + + @Override + public void initLicenseParam() { + + } + + @Override + public void doInitWork() { + + } + + @Override + public int installLicense() { + return 0; + } + + @Override + public synchronized int verifyLicense(ServletContext context) { + return 0; + } + + @Override + public void generateLicense(Map<String, String> clientInfoMap, List<String> ipAddressList) throws Exception { + + } + + @Override + public String nvl(String s) { + return null; + } + + @Override + public Date getExpiredDate() { + return null; + } + + @Override + public void setExpiredDate(Date expiredDate) { + + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java index a799f496..5260a47d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java @@ -25,18 +25,10 @@ import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -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.logging.logic.EELFLoggerDelegate; - import org.openecomp.portalapp.controller.EPRestrictedBaseController; import org.openecomp.portalapp.portal.domain.EPApp; import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem; import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; import org.openecomp.portalapp.portal.service.AdminRolesService; import org.openecomp.portalapp.portal.service.EPAppService; @@ -44,28 +36,40 @@ import org.openecomp.portalapp.portal.service.PersUserAppService; import org.openecomp.portalapp.portal.transport.AppCatalogPersonalization; import org.openecomp.portalapp.portal.transport.FieldsValidator; import org.openecomp.portalapp.portal.utils.EcompPortalUtils; -import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem; import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +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; @RestController @org.springframework.context.annotation.Configuration @EnableAspectJAutoProxy @EPAuditLog public class AppCatalogController extends EPRestrictedBaseController { - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppCatalogController.class); + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppCatalogController.class); @Autowired - AdminRolesService adminRolesService; + private AdminRolesService adminRolesService; @Autowired - EPAppService appService; + private EPAppService appService; @Autowired - PersUserAppService persUserAppService; + private PersUserAppService persUserAppService; /** * RESTful service method to fetch all enabled applications, with details * about which are accessible to the current user, selected by the current * user. * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @throws IOException If sendError fails * @return List of items suitable for display */ @RequestMapping(value = { "/portalApi/appCatalog" }, method = RequestMethod.GET, produces = "application/json") @@ -81,10 +85,10 @@ public class AppCatalogController extends EPRestrictedBaseController { appCatalog = appService.getAdminAppCatalog(user); else appCatalog = appService.getUserAppCatalog(user); - EcompPortalUtils.logAndSerializeObject(logger,"/portalApi/getAppCatalog", "GET result =", appCatalog); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getAppCatalog", "GET result =", appCatalog); } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed in getAppCatalog", e); + logger.error(EELFLoggerDelegate.errorLogger, "getAppCatalog failed", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } return appCatalog; @@ -95,11 +99,13 @@ public class AppCatalogController extends EPRestrictedBaseController { * catalog. * * @param request - * @param selectRequest + * HttpServletRequest + * @param persRequest * JSON with data including application ID * @param response + * HttpServletResponse * @return FieldsValidator - * @throws IOException + * @throws IOException If sendError fails */ @RequestMapping(value = { "/portalApi/appCatalog" }, method = RequestMethod.PUT, produces = "application/json") public FieldsValidator putAppCatalogSelection(HttpServletRequest request, @@ -114,7 +120,7 @@ public class AppCatalogController extends EPRestrictedBaseController { persUserAppService.setPersUserAppValue(user, app, persRequest.getSelect(), persRequest.getPending()); } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed in putAppCatalogSelection", e); + logger.error(EELFLoggerDelegate.errorLogger, "putAppCatalogSelection failed", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } result.httpStatusCode = new Long(HttpServletResponse.SC_OK); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java index 9b476e05..7e781049 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java @@ -63,8 +63,8 @@ public class AppContactUsController extends EPRestrictedBaseController { * Answers a JSON object with three items from the system.properties file: * user self-help ticket URL, email for feedback, and Portal info link. * - * @param request - * @return + * @param request HttpServletRequest + * @return PortalRestResponse */ @RequestMapping(value = "/feedback", method = RequestMethod.GET, produces = "application/json") public PortalRestResponse<String> getPortalDetails(HttpServletRequest request) { @@ -91,8 +91,8 @@ public class AppContactUsController extends EPRestrictedBaseController { * Answers the contents of the contact-us table, extended with the * application name. * - * @param request - * @return + * @param request HttpServletRequest + * @return PortalRestResponse<List<AppContactUsItem>> */ @RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json") public PortalRestResponse<List<AppContactUsItem>> getAppContactUsList(HttpServletRequest request) { @@ -113,8 +113,8 @@ public class AppContactUsController extends EPRestrictedBaseController { * Answers a list of objects, one per application, extended with available * data on how to contact that app's organization (possibly none). * - * @param request - * @return + * @param request HttpServletRequest + * @return PortalRestResponse<List<AppContactUsItem>> */ @RequestMapping(value = "/allapps", method = RequestMethod.GET, produces = "application/json") public PortalRestResponse<List<AppContactUsItem>> getAppsAndContacts(HttpServletRequest request) { @@ -145,8 +145,8 @@ public class AppContactUsController extends EPRestrictedBaseController { * Answers a list of objects with category-application-function details. Not * all applications participate in the functional menu. * - * @param request - * @return + * @param request HttpServletRequest + * @return PortalRestResponse<List<AppCategoryFunctionsItem>> */ @RequestMapping(value = "/functions", method = RequestMethod.GET, produces = "application/json") public PortalRestResponse<List<AppCategoryFunctionsItem>> getAppCategoryFunctions(HttpServletRequest request) { @@ -171,8 +171,8 @@ public class AppContactUsController extends EPRestrictedBaseController { /** * Accepts a new application's contact us details. * - * @param contactUs - * @return + * @param contactUs AppContactUsItem + * @return PortalRestResponse<String> */ @RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json") public PortalRestResponse<String> save(@RequestBody AppContactUsItem contactUs) { @@ -206,8 +206,8 @@ public class AppContactUsController extends EPRestrictedBaseController { * Deletes the specified application's contact-us details entry from the * table. * - * @param id - * @return + * @param id app ID + * @return PortalRestResponse<String> */ @RequestMapping(value = "/delete/{appid}", method = RequestMethod.POST, produces = "application/json") public PortalRestResponse<String> delete(@PathVariable("appid") Long id) { diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java index 7a05d676..2c1da820 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java @@ -80,7 +80,11 @@ public class AppsController extends EPRestrictedBaseController { * RESTful service method to fetch all Applications available to current * user * - * @return + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return List<EcompApp> */ @RequestMapping(value = { "/portalApi/userApps" }, method = RequestMethod.GET, produces = "application/json") public List<EcompApp> getUserApps(HttpServletRequest request, HttpServletResponse response) { @@ -105,7 +109,13 @@ public class AppsController extends EPRestrictedBaseController { * RESTful service method to fetch all applications accessible to the * current user, with personalizations. * - * @return + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return List<EcompApp> + * @throws IOException + * if sendError fails */ @RequestMapping(value = { "/portalApi/persUserApps" }, method = RequestMethod.GET, produces = "application/json") public List<EcompApp> getPersUserApps(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -134,7 +144,11 @@ public class AppsController extends EPRestrictedBaseController { * RESTful service method to fetch applications for which the current user * is an Administrator * - * @return + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return List<AppIdAndNameTransportModel> */ @RequestMapping(value = { "/portalApi/adminApps" }, method = RequestMethod.GET, produces = "application/json") public List<AppIdAndNameTransportModel> getAdminApps(HttpServletRequest request, HttpServletResponse response) { @@ -159,7 +173,11 @@ public class AppsController extends EPRestrictedBaseController { * RESTful service method to fetch Applications for user who is super admin * and/or app admin. * - * @return + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return List<AppIdAndNameTransportModel> */ @RequestMapping(value = { "/portalApi/appsForSuperAdminAndAccountAdmin" }, method = RequestMethod.GET, produces = "application/json") @@ -186,6 +204,10 @@ public class AppsController extends EPRestrictedBaseController { /** * RESTful service method to fetch left menu items from the user's session. * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse * @return JSON with left menu */ @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -254,18 +276,21 @@ public class AppsController extends EPRestrictedBaseController { return ecompApps; } - /* - * This method sends the user apps manual sort preference Data to service - * - * @request: HTTP servlet request + /** + * Sets the user apps manual sort preference * - * @response: HTTP servlet response + * @param request + * HTTP servlet request + * @param response + * HTTP servlet response + * @param epAppsManualPref + * sort pref + * @return FieldsValidator */ @RequestMapping(value = { "/portalApi/saveUserAppsSortingManual" }, method = RequestMethod.PUT, produces = "application/json") public FieldsValidator putUserAppsSortingManual(HttpServletRequest request, - @RequestBody List<EPAppsManualPreference> epAppsManualPref, HttpServletResponse response) - throws IOException { + @RequestBody List<EPAppsManualPreference> epAppsManualPref, HttpServletResponse response) { FieldsValidator fieldsValidator = null; try { EPUser user = EPUserUtils.getUserSession(request); @@ -316,13 +341,16 @@ public class AppsController extends EPRestrictedBaseController { return fieldsValidator; } - /* - * This method is being called to delete the user app manual sort preference - * record - * - * @request: HTTP servlet request + /** + * Deletes the user app manual sort preference record * - * @response: HTTP servlet response + * @param request + * HTTP servlet request + * @param response + * HTTP servlet response + * @param delManualAppData + * data to delete + * @return FieldsValidator */ @RequestMapping(value = { "/portalApi/UpdateUserAppsSortManual" }, method = RequestMethod.PUT, produces = "application/json") @@ -389,7 +417,11 @@ public class AppsController extends EPRestrictedBaseController { * Administrator user. Attention: Users which have Super Administrator roles * only are not included! * - * @return + * @param request + * HTTP servlet request + * @param response + * HTTP servlet response + * @return List<AdminUserApplications> */ @RequestMapping(value = { "/portalApi/accountAdmins" }, method = RequestMethod.GET, produces = "application/json") public List<AdminUserApplications> getAppsAdministrators(HttpServletRequest request, HttpServletResponse response) { @@ -432,10 +464,11 @@ public class AppsController extends EPRestrictedBaseController { * regardless of enabled status. * * @param request + * HTTP servlet request * @param response + * HTTP servlet response * @return List of applications */ - // This API returns @RequestMapping(value = { "/portalApi/allAvailableApps" }, method = RequestMethod.GET, produces = "application/json") public List<AppsResponse> getAllApps(HttpServletRequest request, HttpServletResponse response) { @@ -458,8 +491,10 @@ public class AppsController extends EPRestrictedBaseController { /** * * @param request + * HTTP servlet request * @param response - * @return + * HTTP servlet response + * @return List of applications */ @RequestMapping(value = { "/portalApi/appsFullList" }, method = RequestMethod.GET, produces = "application/json") public List<EcompApp> getAppsFullList(HttpServletRequest request, HttpServletResponse response) { @@ -477,8 +512,10 @@ public class AppsController extends EPRestrictedBaseController { /** * * @param request + * HTTP servlet request * @param response - * @return + * HTTP servlet response + * @return UserRoles */ @RequestMapping(value = { "/portalApi/userProfile" }, method = RequestMethod.GET, produces = "application/json") public UserRoles getUserProfile(HttpServletRequest request, HttpServletResponse response) { @@ -502,8 +539,10 @@ public class AppsController extends EPRestrictedBaseController { /** * * @param request + * HTTP servlet request * @param appId - * @return + * application ID + * @return List<LocalRole> */ @RequestMapping(value = { "/portalApi/appRoles/{appId}" }, method = { RequestMethod.GET }, produces = "application/json") @@ -522,8 +561,10 @@ public class AppsController extends EPRestrictedBaseController { /** * * @param request + * HTTP servlet request * @param response - * @return + * HTTP servlet response + * @return List<OnboardingApp> */ @RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.GET, produces = "application/json") public List<OnboardingApp> getOnboardingApps(HttpServletRequest request, HttpServletResponse response) { @@ -547,9 +588,12 @@ public class AppsController extends EPRestrictedBaseController { /** * * @param request - * @param modifiedOnboardingApp + * HTTP servlet request * @param response - * @return + * HTTP servlet response + * @param modifiedOnboardingApp + * app to update + * @return FieldsValidator */ @RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.PUT, produces = "application/json") public FieldsValidator putOnboardingApp(HttpServletRequest request, @@ -576,9 +620,12 @@ public class AppsController extends EPRestrictedBaseController { /** * * @param request - * @param newOnboardingApp + * HTTP servlet request * @param response - * @return + * HTTP servlet response + * @param newOnboardingApp + * app to add + * @return FieldsValidator */ @RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.POST, produces = "application/json") public FieldsValidator postOnboardingApp(HttpServletRequest request, @RequestBody OnboardingApp newOnboardingApp, @@ -606,9 +653,12 @@ public class AppsController extends EPRestrictedBaseController { * REST endpoint to process a request to delete an on-boarded application. * * @param request - * @param appId + * HTTP servlet request * @param response - * @return + * HTTP servlet response + * @param appId + * ID of app to delete + * @return FieldsValidator */ @RequestMapping(value = { "/portalApi/onboardingApps/{appId}" }, method = { RequestMethod.DELETE }, produces = "application/json") @@ -637,7 +687,9 @@ public class AppsController extends EPRestrictedBaseController { * Gets the application thumbnail image; sets status 404 if none exists. * * @param request - * HttpServletRequest + * HTTP servlet request + * @param response + * HTTP servlet response * @param appId * Application ID * @return Bytes with the app thumbnail image; null if not available. diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java index fa49d5b2..774eb3ee 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java @@ -1,374 +1,374 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.AdminRolesService;
-import org.openecomp.portalapp.portal.service.EPAppService;
-import org.openecomp.portalapp.portal.service.PortalAdminService;
-import org.openecomp.portalapp.portal.service.UserService;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.OnboardingApp;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalapp.portal.utils.PortalConstants;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.swagger.annotations.ApiOperation;
-
-/**
- * Processes requests from external systems (i.e., not the front-end web UI).
- * First use case is ECOMP Controller, which has to create an admin and onboard
- * itself upon launch of a fresh Portal.
- *
- * Listens on the "auxapi" path prefix. Provides alternate implementations of
- * methods in several existing controllers because an EPUser object is not
- * available in the session for these requests.
- *
- * Checks credentials sent via HTTP Basic Authentication. The Portal's basic
- * HTTP authentication system requires that the user names and endpoints are
- * registered together.
- */
-@RestController
-@RequestMapping(PortalConstants.REST_AUX_API)
-@Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class AppsControllerExternalRequest implements BasicAuthenticationController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsControllerExternalRequest.class);
-
- private static final String ONBOARD_APP = "/onboardApp";
-
- // Where is this used?
- public boolean isAuxRESTfulCall() {
- return true;
- }
-
- /**
- * For testing whether a user is a superadmin.
- */
- @Autowired
- private AdminRolesService adminRolesService;
-
- /**
- * For onboarding or updating an app
- */
- @Autowired
- private EPAppService appService;
-
- /**
- * For promoting a user to Portal admin
- */
- @Autowired
- private PortalAdminService portalAdminService;
-
- /**
- * For creating a new user
- */
- @Autowired
- private UserService userService;
-
- /**
- * Creates a new user as a Portal administrator.
- *
- * <PRE>
- {
- "loginId" : "abc123",
- "loginPwd": "",
- "email":"ecomp@controller"
- }
- * </PRE>
- *
- * @param request
- * HttpServletRequest
- * @param epUser
- * User details; the email and orgUserId fields are mandatory
- * @param response
- * HttpServletResponse
- * @return PortalRestResponse with success or failure
- */
- @ApiOperation(value = "Creates a new user as a Portal administrator.", response = PortalRestResponse.class)
- @RequestMapping(value = "/portalAdmin", method = RequestMethod.POST, produces = "application/json")
- @ResponseBody
- public PortalRestResponse<String> postPortalAdmin(HttpServletRequest request, HttpServletResponse response,
- @RequestBody EPUser epUser) {
- EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "request", epUser);
- PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
-
- // Check mandatory fields.
- if (epUser.getEmail() == null || epUser.getEmail().trim().length() == 0 //
- || epUser.getLoginId() == null || epUser.getLoginId().trim().length() == 0 //
- || epUser.getLoginPwd() == null) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Missing required field: email, loginId, or loginPwd");
- return portalResponse;
- }
-
- try {
- // Check for existing user; create if not found.
- List<EPUser> userList = userService.getUserByUserId(epUser.getOrgUserId());
- if (userList == null || userList.size() == 0) {
- // Create user with first, last names etc.; do check for
- // duplicates.
- String userCreateResult = userService.saveNewUser(epUser, "Yes");
- if (!"success".equals(userCreateResult)) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(userCreateResult);
- return portalResponse;
- }
- }
-
- // Check for Portal admin status; promote if not.
- if (adminRolesService.isSuperAdmin(epUser)) {
- portalResponse.setStatus(PortalRestStatusEnum.OK);
- } else {
- FieldsValidator fv = portalAdminService.createPortalAdmin(epUser.getOrgUserId());
- if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- portalResponse.setStatus(PortalRestStatusEnum.OK);
- } else {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(fv.toString());
- }
- }
- } catch (Exception ex) {
- // Uncaught exceptions yield 404 and an empty error page
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(ex.toString());
- }
-
- EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "response", portalResponse);
- return portalResponse;
- }
-
- /**
- * Gets the specified application that is on-boarded in Portal.
- *
- * @param request
- * HttpServletRequest
- * @param appId
- * Application ID to get
- * @param response
- * httpServletResponse
- * @return OnboardingApp objects
- */
- @ApiOperation(value = "Gets the specified application that is on-boarded in Portal.", response = OnboardingApp.class)
- @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.GET, produces = "application/json")
- @ResponseBody
- public OnboardingApp getOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("appId") Long appId) {
- EPApp epApp = appService.getApp(appId);
- OnboardingApp obApp = new OnboardingApp();
- appService.createOnboardingFromApp(epApp, obApp);
- EcompPortalUtils.logAndSerializeObject(logger, "getOnboardAppExternal", "response", obApp);
- return obApp;
- }
-
- /**
- * Adds a new application to Portal. The My Logins App Owner in the request
- * must be the organization user ID of a person who is a Portal
- * administrator.
- *
- * <pre>
- * {
- "myLoginsAppOwner" : "abc123",
- "name": "dashboard",
- "url": "http://k8s/something",
- "restUrl" : "http://aic.att.com",
- "restrictedApp" : true,
- "isOpen" : true,
- "isEnabled": false
- }
- * </pre>
- *
- * @param request
- * HttpServletRequest
- * @param response
- * httpServletResponse
- * @param newOnboardApp
- * Message with details about the app to add
- * @return PortalRestResponse
- */
- @ApiOperation(value = "Adds a new application to Portal.", response = PortalRestResponse.class)
- @RequestMapping(value = { ONBOARD_APP }, method = RequestMethod.POST, produces = "application/json")
- @ResponseBody
- public PortalRestResponse<String> postOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
- @RequestBody OnboardingApp newOnboardApp) {
- EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "request", newOnboardApp);
- PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
-
- // Validate fields
- if (newOnboardApp.id != null) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Unexpected field: id");
- return portalResponse;
- }
- if (newOnboardApp.name == null || newOnboardApp.name.trim().length() == 0 //
- || newOnboardApp.url == null || newOnboardApp.url.trim().length() == 0 //
- || newOnboardApp.restUrl == null || newOnboardApp.restUrl.trim().length() == 0
- || newOnboardApp.myLoginsAppOwner == null || newOnboardApp.myLoginsAppOwner.trim().length() == 0
- || newOnboardApp.restrictedApp == null //
- || newOnboardApp.isOpen == null //
- || newOnboardApp.isEnabled == null) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(
- "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner");
- return portalResponse;
- }
-
- try {
- List<EPUser> userList = userService.getUserByUserId(newOnboardApp.myLoginsAppOwner);
- if (userList == null || userList.size() != 1) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Failed to find user: " + newOnboardApp.myLoginsAppOwner);
- return portalResponse;
- }
-
- EPUser epUser = userList.get(0);
- // Check for Portal admin status
- if (! adminRolesService.isSuperAdmin(epUser)) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("User lacks Portal admin role: " + epUser.getLoginId());
- return portalResponse;
- }
-
- newOnboardApp.normalize();
- FieldsValidator fv = appService.addOnboardingApp(newOnboardApp, epUser);
- if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- portalResponse.setStatus(PortalRestStatusEnum.OK);
- } else {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(fv.toString());
- }
- } catch (Exception ex) {
- // Uncaught exceptions yield 404 and an empty error page
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(ex.toString());
- }
- EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "response", portalResponse);
- return portalResponse;
- }
-
- /**
- * Updates information about an on-boarded application in Portal. The My
- * Logins App Owner in the request must be the organization user ID of a
- * person who is a Portal administrator.
- * <pre>
- {
- "id" : 123,
- "myLoginsAppOwner" : "abc123",
- "name": "dashboard",
- "url": "http://k8s/something",
- "restUrl" : "http://aic.att.com",
- "restrictedApp" : true,
- "isOpen" : true,
- "isEnabled": false
- }
- </pre>
- * @param request
- * HttpServletRequest
- * @param response
- * httpServletResponse
- * @param appId
- * application id
- * @param oldOnboardApp
- * Message with details about the app to add
- * @return PortalRestResponse
- */
- @ApiOperation(value = "Updates information about an on-boarded application in Portal.", response = PortalRestResponse.class)
- @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.PUT, produces = "application/json")
- @ResponseBody
- public PortalRestResponse<String> putOnboardAppExternal(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("appId") Long appId, @RequestBody OnboardingApp oldOnboardApp) {
- EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "request", oldOnboardApp);
- PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
- // Validate fields.
- if (oldOnboardApp.id == null || !appId.equals(oldOnboardApp.id)) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Unexpected value for field: id");
- return portalResponse;
- }
- if (oldOnboardApp.name == null || oldOnboardApp.name.trim().length() == 0 //
- || oldOnboardApp.url == null || oldOnboardApp.url.trim().length() == 0 //
- || oldOnboardApp.restUrl == null || oldOnboardApp.restUrl.trim().length() == 0
- || oldOnboardApp.myLoginsAppOwner == null || oldOnboardApp.myLoginsAppOwner.trim().length() == 0
- || oldOnboardApp.restrictedApp == null //
- || oldOnboardApp.isOpen == null //
- || oldOnboardApp.isEnabled == null) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(
- "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner");
- return portalResponse;
- }
-
- try {
- List<EPUser> userList = userService.getUserByUserId(oldOnboardApp.myLoginsAppOwner);
- if (userList == null || userList.size() != 1) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("Failed to find user: " + oldOnboardApp.myLoginsAppOwner);
- return portalResponse;
- }
-
- EPUser epUser = userList.get(0);
- // Check for Portal admin status
- if (! adminRolesService.isSuperAdmin(epUser)) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage("User lacks Portal admin role: " + epUser.getLoginId());
- return portalResponse;
- }
-
- oldOnboardApp.normalize();
- FieldsValidator fv = appService.modifyOnboardingApp(oldOnboardApp, epUser);
- if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- portalResponse.setStatus(PortalRestStatusEnum.OK);
- } else {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(fv.toString());
- }
- } catch (Exception ex) {
- // Uncaught exceptions yield 404 and an empty error page
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(ex.toString());
- }
- EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "response", portalResponse);
- return portalResponse;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.EPAppService; +import org.openecomp.portalapp.portal.service.PortalAdminService; +import org.openecomp.portalapp.portal.service.UserService; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.OnboardingApp; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.annotations.ApiOperation; + +/** + * Processes requests from external systems (i.e., not the front-end web UI). + * First use case is ECOMP Controller, which has to create an admin and onboard + * itself upon launch of a fresh Portal. + * + * Listens on the "auxapi" path prefix. Provides alternate implementations of + * methods in several existing controllers because an EPUser object is not + * available in the session for these requests. + * + * Checks credentials sent via HTTP Basic Authentication. The Portal's basic + * HTTP authentication system requires that the user names and endpoints are + * registered together. + */ +@RestController +@RequestMapping(PortalConstants.REST_AUX_API) +@Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class AppsControllerExternalRequest implements BasicAuthenticationController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsControllerExternalRequest.class); + + private static final String ONBOARD_APP = "/onboardApp"; + + // Where is this used? + public boolean isAuxRESTfulCall() { + return true; + } + + /** + * For testing whether a user is a superadmin. + */ + @Autowired + private AdminRolesService adminRolesService; + + /** + * For onboarding or updating an app + */ + @Autowired + private EPAppService appService; + + /** + * For promoting a user to Portal admin + */ + @Autowired + private PortalAdminService portalAdminService; + + /** + * For creating a new user + */ + @Autowired + private UserService userService; + + /** + * Creates a new user as a Portal administrator. + * + * <PRE> + { + "loginId" : "abc123", + "loginPwd": "", + "email":"ecomp@controller" + } + * </PRE> + * + * @param request + * HttpServletRequest + * @param epUser + * User details; the email and orgUserId fields are mandatory + * @param response + * HttpServletResponse + * @return PortalRestResponse with success or failure + */ + @ApiOperation(value = "Creates a new user as a Portal administrator.", response = PortalRestResponse.class) + @RequestMapping(value = "/portalAdmin", method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public PortalRestResponse<String> postPortalAdmin(HttpServletRequest request, HttpServletResponse response, + @RequestBody EPUser epUser) { + EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "request", epUser); + PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); + + // Check mandatory fields. + if (epUser.getEmail() == null || epUser.getEmail().trim().length() == 0 // + || epUser.getLoginId() == null || epUser.getLoginId().trim().length() == 0 // + || epUser.getLoginPwd() == null) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Missing required field: email, loginId, or loginPwd"); + return portalResponse; + } + + try { + // Check for existing user; create if not found. + List<EPUser> userList = userService.getUserByUserId(epUser.getOrgUserId()); + if (userList == null || userList.size() == 0) { + // Create user with first, last names etc.; do check for + // duplicates. + String userCreateResult = userService.saveNewUser(epUser, "Yes"); + if (!"success".equals(userCreateResult)) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage(userCreateResult); + return portalResponse; + } + } + + // Check for Portal admin status; promote if not. + if (adminRolesService.isSuperAdmin(epUser)) { + portalResponse.setStatus(PortalRestStatusEnum.OK); + } else { + FieldsValidator fv = portalAdminService.createPortalAdmin(epUser.getOrgUserId()); + if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { + portalResponse.setStatus(PortalRestStatusEnum.OK); + } else { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage(fv.toString()); + } + } + } catch (Exception ex) { + // Uncaught exceptions yield 404 and an empty error page + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage(ex.toString()); + } + + EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "response", portalResponse); + return portalResponse; + } + + /** + * Gets the specified application that is on-boarded in Portal. + * + * @param request + * HttpServletRequest + * @param appId + * Application ID to get + * @param response + * httpServletResponse + * @return OnboardingApp objects + */ + @ApiOperation(value = "Gets the specified application that is on-boarded in Portal.", response = OnboardingApp.class) + @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public OnboardingApp getOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId) { + EPApp epApp = appService.getApp(appId); + OnboardingApp obApp = new OnboardingApp(); + appService.createOnboardingFromApp(epApp, obApp); + EcompPortalUtils.logAndSerializeObject(logger, "getOnboardAppExternal", "response", obApp); + return obApp; + } + + /** + * Adds a new application to Portal. The My Logins App Owner in the request + * must be the organization user ID of a person who is a Portal + * administrator. + * + * <pre> + * { + "myLoginsAppOwner" : "abc123", + "name": "dashboard", + "url": "http://k8s/something", + "restUrl" : "http://aic.att.com", + "restrictedApp" : true, + "isOpen" : true, + "isEnabled": false + } + * </pre> + * + * @param request + * HttpServletRequest + * @param response + * httpServletResponse + * @param newOnboardApp + * Message with details about the app to add + * @return PortalRestResponse + */ + @ApiOperation(value = "Adds a new application to Portal.", response = PortalRestResponse.class) + @RequestMapping(value = { ONBOARD_APP }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public PortalRestResponse<String> postOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, + @RequestBody OnboardingApp newOnboardApp) { + EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "request", newOnboardApp); + PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); + + // Validate fields + if (newOnboardApp.id != null) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Unexpected field: id"); + return portalResponse; + } + if (newOnboardApp.name == null || newOnboardApp.name.trim().length() == 0 // + || newOnboardApp.url == null || newOnboardApp.url.trim().length() == 0 // + || newOnboardApp.restUrl == null || newOnboardApp.restUrl.trim().length() == 0 + || newOnboardApp.myLoginsAppOwner == null || newOnboardApp.myLoginsAppOwner.trim().length() == 0 + || newOnboardApp.restrictedApp == null // + || newOnboardApp.isOpen == null // + || newOnboardApp.isEnabled == null) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage( + "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner"); + return portalResponse; + } + + try { + List<EPUser> userList = userService.getUserByUserId(newOnboardApp.myLoginsAppOwner); + if (userList == null || userList.size() != 1) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Failed to find user: " + newOnboardApp.myLoginsAppOwner); + return portalResponse; + } + + EPUser epUser = userList.get(0); + // Check for Portal admin status + if (! adminRolesService.isSuperAdmin(epUser)) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("User lacks Portal admin role: " + epUser.getLoginId()); + return portalResponse; + } + + newOnboardApp.normalize(); + FieldsValidator fv = appService.addOnboardingApp(newOnboardApp, epUser); + if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { + portalResponse.setStatus(PortalRestStatusEnum.OK); + } else { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage(fv.toString()); + } + } catch (Exception ex) { + // Uncaught exceptions yield 404 and an empty error page + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage(ex.toString()); + } + EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "response", portalResponse); + return portalResponse; + } + + /** + * Updates information about an on-boarded application in Portal. The My + * Logins App Owner in the request must be the organization user ID of a + * person who is a Portal administrator. + * <pre> + { + "id" : 123, + "myLoginsAppOwner" : "abc123", + "name": "dashboard", + "url": "http://k8s/something", + "restUrl" : "http://aic.att.com", + "restrictedApp" : true, + "isOpen" : true, + "isEnabled": false + } + </pre> + * @param request + * HttpServletRequest + * @param response + * httpServletResponse + * @param appId + * application id + * @param oldOnboardApp + * Message with details about the app to add + * @return PortalRestResponse + */ + @ApiOperation(value = "Updates information about an on-boarded application in Portal.", response = PortalRestResponse.class) + @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.PUT, produces = "application/json") + @ResponseBody + public PortalRestResponse<String> putOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId, @RequestBody OnboardingApp oldOnboardApp) { + EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "request", oldOnboardApp); + PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); + // Validate fields. + if (oldOnboardApp.id == null || !appId.equals(oldOnboardApp.id)) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Unexpected value for field: id"); + return portalResponse; + } + if (oldOnboardApp.name == null || oldOnboardApp.name.trim().length() == 0 // + || oldOnboardApp.url == null || oldOnboardApp.url.trim().length() == 0 // + || oldOnboardApp.restUrl == null || oldOnboardApp.restUrl.trim().length() == 0 + || oldOnboardApp.myLoginsAppOwner == null || oldOnboardApp.myLoginsAppOwner.trim().length() == 0 + || oldOnboardApp.restrictedApp == null // + || oldOnboardApp.isOpen == null // + || oldOnboardApp.isEnabled == null) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage( + "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner"); + return portalResponse; + } + + try { + List<EPUser> userList = userService.getUserByUserId(oldOnboardApp.myLoginsAppOwner); + if (userList == null || userList.size() != 1) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Failed to find user: " + oldOnboardApp.myLoginsAppOwner); + return portalResponse; + } + + EPUser epUser = userList.get(0); + // Check for Portal admin status + if (! adminRolesService.isSuperAdmin(epUser)) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("User lacks Portal admin role: " + epUser.getLoginId()); + return portalResponse; + } + + oldOnboardApp.normalize(); + FieldsValidator fv = appService.modifyOnboardingApp(oldOnboardApp, epUser); + if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { + portalResponse.setStatus(PortalRestStatusEnum.OK); + } else { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage(fv.toString()); + } + } catch (Exception ex) { + // Uncaught exceptions yield 404 and an empty error page + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage(ex.toString()); + } + EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "response", portalResponse); + return portalResponse; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java index 705c9008..8d6b8e63 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AuditLogController.java @@ -1,106 +1,106 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-import org.openecomp.portalsdk.core.domain.AuditLog;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.AuditService;
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.util.EPUserUtils;
-
-@RestController
-@RequestMapping("/portalApi/auditLog")
-public class AuditLogController extends EPRestrictedBaseController {
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
-
- @Autowired
- private AuditService auditService;
-
- /**
- * Store audit log of the specified access type.
- *
- * @param request
- * @param affectedAppId
- * @param type
- * @param comment
- */
- @RequestMapping(value = "/store", method = RequestMethod.GET, produces = "application/json")
- public void auditLog(HttpServletRequest request, @RequestParam String affectedAppId, @RequestParam String type,
- @RequestParam String comment) {
- logger.debug(EELFLoggerDelegate.debugLogger, "auditLog: appId {}, type {], comment {}",
- affectedAppId, type, comment);
- String cd_type = null;
- try {
- EPUser user = EPUserUtils.getUserSession(request);
- /* Check type of Activity CD */
- if (type.equals("app")) {
- cd_type = AuditLog.CD_ACTIVITY_APP_ACCESS;
- } else if (type.equals("tab")) {
- cd_type = AuditLog.CD_ACTIVITY_TAB_ACCESS;
- } else if (type.equals("functional")) {
- cd_type = AuditLog.CD_ACTIVITY_FUNCTIONAL_ACCESS;
- } else if (type.equals("leftMenu")) {
- cd_type = AuditLog.CD_ACTIVITY_LEFT_MENU_ACCESS;
- } else {
- logger.error(EELFLoggerDelegate.errorLogger, "Storing auditLog failed! Activity CD type is not correct.");
- }
- /* Store the audit log only if it contains valid Activity CD */
- if (cd_type != null) {
- AuditLog auditLog = new AuditLog();
- auditLog.setActivityCode(cd_type);
- /*
- * Check affectedAppId and comment and see if these two values are
- * valid
- */
- if (comment != null && !comment.equals("") && !comment.equals("undefined"))
- auditLog.setComments(comment);
- if (affectedAppId != null && !affectedAppId.equals("") && !affectedAppId.equals("undefined"))
- auditLog.setAffectedRecordId(affectedAppId);
- long userId = EPUserUtils.getUserId(request);
- auditLog.setUserId(userId);
- auditService.logActivity(auditLog, null);
-
- // Log file
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("AuditLogController.auditLog",
- cd_type, user.getOrgUserId(), affectedAppId, comment));
- MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "auditLog failed", e);
- }
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import javax.servlet.http.HttpServletRequest; + +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import org.openecomp.portalsdk.core.domain.AuditLog; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.AuditService; +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.util.EPUserUtils; + +@RestController +@RequestMapping("/portalApi/auditLog") +public class AuditLogController extends EPRestrictedBaseController { + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class); + + @Autowired + private AuditService auditService; + + /** + * Store audit log of the specified access type. + * + * @param request + * @param affectedAppId + * @param type + * @param comment + */ + @RequestMapping(value = "/store", method = RequestMethod.GET, produces = "application/json") + public void auditLog(HttpServletRequest request, @RequestParam String affectedAppId, @RequestParam String type, + @RequestParam String comment) { + logger.debug(EELFLoggerDelegate.debugLogger, "auditLog: appId {}, type {], comment {}", + affectedAppId, type, comment); + String cd_type = null; + try { + EPUser user = EPUserUtils.getUserSession(request); + /* Check type of Activity CD */ + if (type.equals("app")) { + cd_type = AuditLog.CD_ACTIVITY_APP_ACCESS; + } else if (type.equals("tab")) { + cd_type = AuditLog.CD_ACTIVITY_TAB_ACCESS; + } else if (type.equals("functional")) { + cd_type = AuditLog.CD_ACTIVITY_FUNCTIONAL_ACCESS; + } else if (type.equals("leftMenu")) { + cd_type = AuditLog.CD_ACTIVITY_LEFT_MENU_ACCESS; + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Storing auditLog failed! Activity CD type is not correct."); + } + /* Store the audit log only if it contains valid Activity CD */ + if (cd_type != null) { + AuditLog auditLog = new AuditLog(); + auditLog.setActivityCode(cd_type); + /* + * Check affectedAppId and comment and see if these two values are + * valid + */ + if (comment != null && !comment.equals("") && !comment.equals("undefined")) + auditLog.setComments(comment); + if (affectedAppId != null && !affectedAppId.equals("") && !affectedAppId.equals("undefined")) + auditLog.setAffectedRecordId(affectedAppId); + long userId = EPUserUtils.getUserId(request); + auditLog.setUserId(userId); + auditService.logActivity(auditLog, null); + + // Log file + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("AuditLogController.auditLog", + cd_type, user.getOrgUserId(), affectedAppId, comment)); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "auditLog failed", e); + } + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BEPropertyReaderController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BEPropertyReaderController.java index a7b3f1a1..5be6614c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BEPropertyReaderController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BEPropertyReaderController.java @@ -1,46 +1,46 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import javax.servlet.http.HttpServletRequest;
-
-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;
-
-import org.openecomp.portalsdk.core.controller.FusionBaseController;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalapp.portal.domain.BEProperty;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-
-@RestController
-@RequestMapping("/portalApi/properties")
-public class BEPropertyReaderController extends FusionBaseController{
- @RequestMapping(value = "/readProperty", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<BEProperty> readProperty(HttpServletRequest request, @RequestParam String key) {
- try {
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", new BEProperty(key, SystemProperties.getProperty(key)));
- } catch (Exception e) {
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import javax.servlet.http.HttpServletRequest; + +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; + +import org.openecomp.portalsdk.core.controller.FusionBaseController; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalapp.portal.domain.BEProperty; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; + +@RestController +@RequestMapping("/portalApi/properties") +public class BEPropertyReaderController extends FusionBaseController{ + @RequestMapping(value = "/readProperty", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<BEProperty> readProperty(HttpServletRequest request, @RequestParam String key) { + try { + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", new BEProperty(key, SystemProperties.getProperty(key))); + } catch (Exception e) { + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null); + } + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthAccountController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthAccountController.java index f23054bd..c16fa78f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthAccountController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthAccountController.java @@ -24,13 +24,12 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -@SuppressWarnings("unchecked") @RestController @org.springframework.context.annotation.Configuration @EnableAspectJAutoProxy @EPAuditLog -public class BasicAuthAccountController extends EPRestrictedBaseController{ - +public class BasicAuthAccountController extends EPRestrictedBaseController { + @Autowired private BasicAuthAccountService basicAuthAccountService; @@ -38,69 +37,99 @@ public class BasicAuthAccountController extends EPRestrictedBaseController{ private AdminRolesService adminRolesService; /** - * Saves Basic Authentication account for external systems - * @param BasicAuthCredentials + * Saves Basic Authentication account for external systems + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @param newBasicAuthAccount + * BasicAuthCredentials * @return Id of the newly created account - */ - + * @throws Exception + * on failure + */ @RequestMapping(value = { "/portalApi/basicAuthAccount" }, method = RequestMethod.POST) public PortalRestResponse<String> createBasicAuthAccount(HttpServletRequest request, HttpServletResponse response, @RequestBody BasicAuthCredentials newBasicAuthAccount) throws Exception { - + EPUser user = EPUserUtils.getUserSession(request); - if (!adminRolesService.isSuperAdmin(user)){ - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Authorization Required", "Admin Only Operation! "); + if (!adminRolesService.isSuperAdmin(user)) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Authorization Required", + "Admin Only Operation! "); } - - if(newBasicAuthAccount == null){ + + if (newBasicAuthAccount == null) { return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", "newBasicAuthAccount cannot be null or empty"); } long accountId = basicAuthAccountService.saveBasicAuthAccount(newBasicAuthAccount); - + List<Long> endpointIdList = new ArrayList<>(); try { - for(EPEndpoint ep: newBasicAuthAccount.getEndpoints()){ + for (EPEndpoint ep : newBasicAuthAccount.getEndpoints()) { endpointIdList.add(basicAuthAccountService.saveEndpoints(ep)); } - for(Long endpointId: endpointIdList){ + for (Long endpointId : endpointIdList) { basicAuthAccountService.saveEndpointAccount(accountId, endpointId); } } catch (Exception e) { return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); } - + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); } - + /** - * Returns list of all BasicAuthCredentials in the system + * Returns list of all BasicAuthCredentials in the system + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse * @return List<BasicAuthCredentials> + * @throws Exception + * on failure */ - + @RequestMapping(value = { "/portalApi/basicAuthAccount" }, method = RequestMethod.GET) - public PortalRestResponse<List<BasicAuthCredentials>> getBasicAuthAccount(HttpServletRequest request, HttpServletResponse response) - throws Exception { - + public PortalRestResponse<List<BasicAuthCredentials>> getBasicAuthAccount(HttpServletRequest request, + HttpServletResponse response) throws Exception { + EPUser user = EPUserUtils.getUserSession(request); - if (!adminRolesService.isSuperAdmin(user)){ - return new PortalRestResponse<List<BasicAuthCredentials>>(PortalRestStatusEnum.ERROR, "UnAuthorized! Admin Only Operation", new ArrayList<>()); + if (!adminRolesService.isSuperAdmin(user)) { + return new PortalRestResponse<List<BasicAuthCredentials>>(PortalRestStatusEnum.ERROR, + "UnAuthorized! Admin Only Operation", new ArrayList<>()); } - return new PortalRestResponse<List<BasicAuthCredentials>>(PortalRestStatusEnum.OK, "Success", basicAuthAccountService.getAccountData()); + return new PortalRestResponse<List<BasicAuthCredentials>>(PortalRestStatusEnum.OK, "Success", + basicAuthAccountService.getAccountData()); } - + /** * Updates an existing BasicAuthCredentials account + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @param accountId + * account ID + * @param newBasicAuthAccount + * BasicAuthCredentials + * @return PortalRestResponse<String> + * @throws Exception + * on failure */ - @RequestMapping(value = { "/portalApi/basicAuthAccount/{accountId}" }, method = RequestMethod.PUT) public PortalRestResponse<String> updateAccount(HttpServletRequest request, HttpServletResponse response, - @PathVariable("accountId") long accountId, @RequestBody BasicAuthCredentials newBasicAuthAccount) throws Exception { - + @PathVariable("accountId") long accountId, @RequestBody BasicAuthCredentials newBasicAuthAccount) + throws Exception { + EPUser user = EPUserUtils.getUserSession(request); - if (!adminRolesService.isSuperAdmin(user)){ - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Authorization Required", "Admin Only Operation! "); + if (!adminRolesService.isSuperAdmin(user)) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Authorization Required", + "Admin Only Operation! "); } if (newBasicAuthAccount == null) { @@ -114,21 +143,30 @@ public class BasicAuthAccountController extends EPRestrictedBaseController{ } return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); } - + /** * deletes an existing BasicAuthCredentials account + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @param accountId + * account ID + * @return PortalRestResponse<String> + * @throws Exception + * on failure */ - @RequestMapping(value = { "/portalApi/basicAuthAccount/{accountId}" }, method = RequestMethod.DELETE) public PortalRestResponse<String> deleteAccount(HttpServletRequest request, HttpServletResponse response, @PathVariable("accountId") long accountId) throws Exception { - + EPUser user = EPUserUtils.getUserSession(request); - if (!adminRolesService.isSuperAdmin(user)){ - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Authorization Required", "Admin Only Operation! "); + if (!adminRolesService.isSuperAdmin(user)) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Authorization Required", + "Admin Only Operation! "); } - try { basicAuthAccountService.deleteEndpointAccout(accountId); } catch (Exception e) { @@ -136,6 +174,5 @@ public class BasicAuthAccountController extends EPRestrictedBaseController{ } return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); } - - + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthenticationController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthenticationController.java index d9bdf3dc..874edad0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthenticationController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/BasicAuthenticationController.java @@ -1,28 +1,28 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-/**
- * Marker interface to indicate that requests to this controller present HTTP
- * Basic Authentication credentials.
- */
-public interface BasicAuthenticationController {
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +/** + * Marker interface to indicate that requests to this controller present HTTP + * Basic Authentication credentials. + */ +public interface BasicAuthenticationController { + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ConsulClientController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ConsulClientController.java index 8db94849..808220c5 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ConsulClientController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ConsulClientController.java @@ -1,90 +1,95 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.service.ConsulHealthService;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import com.orbitz.consul.ConsulException;
-import com.orbitz.consul.model.health.ServiceHealth;
-
-import io.searchbox.client.config.exception.NoServerConfiguredException;
-
-@RestController
-@RequestMapping("/portalApi/consul")
-public class ConsulClientController extends EPRestrictedBaseController {
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulClientController.class);
-
- @Autowired
- private ConsulHealthService consulHealthService;
- //Get location of a healthy node running our service
- @RequestMapping(value = { "/service/{service}" }, method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<String> getServiceLocation(HttpServletRequest request, HttpServletResponse response, @PathVariable("service") String service) {
-
- try{
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Success!", consulHealthService.getServiceLocation(service));
- }
- catch(NoServerConfiguredException e){
- logger.error(logger.errorLogger, "No healthy service exception!");
- return new PortalRestResponse<String>(PortalRestStatusEnum.WARN, "Warning!", "No healthy service exception!");
- }
- catch(ConsulException e){
- logger.error(logger.errorLogger, "Couldn't connect ot consul - Is consul running?");
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Error!", "Couldn't connect ot consul - Is consul running?");
- }
- }
-
- @RequestMapping(value = { "/service/healthy/{service}" }, method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<List<ServiceHealth>> getAllHealthyNodes(HttpServletRequest request, HttpServletResponse response, @PathVariable("service") String service) {
- try{
- return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.OK, "Success!", consulHealthService.getAllHealthyNodes(service));
- }
- catch(ConsulException e){
- logger.error(logger.errorLogger, "Couldn't connect to consul - shouldn't break anything.");
- return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.ERROR,"Error!", new ArrayList<>());
- }
- }
-
- @RequestMapping(value = { "/service/all/{service}" }, method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<List<ServiceHealth>> getAllNodes(HttpServletRequest request, HttpServletResponse response, @PathVariable("service") String service) {
- try{
- return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.OK, "Success!", consulHealthService.getAllNodes(service));
- }
- catch(ConsulException e){
- logger.error(logger.errorLogger, "Couldn't connect to consul - shouldn't break anything.");
- return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.ERROR,"Error!", new ArrayList<>());
- }
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.service.ConsulHealthService; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import com.orbitz.consul.ConsulException; +import com.orbitz.consul.model.health.ServiceHealth; + +import io.searchbox.client.config.exception.NoServerConfiguredException; + +@RestController +@RequestMapping("/portalApi/consul") +public class ConsulClientController extends EPRestrictedBaseController { + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulClientController.class); + + @Autowired + private ConsulHealthService consulHealthService; + + // Get location of a healthy node running our service + @RequestMapping(value = { "/service/{service}" }, method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<String> getServiceLocation(HttpServletRequest request, HttpServletResponse response, + @PathVariable("service") String service) { + + try { + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Success!", + consulHealthService.getServiceLocation(service, null)); + } catch (NoServerConfiguredException e) { + logger.error(logger.errorLogger, "No healthy service exception!"); + return new PortalRestResponse<String>(PortalRestStatusEnum.WARN, "Warning!", + "No healthy service exception!"); + } catch (ConsulException e) { + logger.error(logger.errorLogger, "Couldn't connect ot consul - Is consul running?"); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "Error!", + "Couldn't connect ot consul - Is consul running?"); + } + } + + @RequestMapping(value = { "/service/healthy/{service}" }, method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<List<ServiceHealth>> getAllHealthyNodes(HttpServletRequest request, + HttpServletResponse response, @PathVariable("service") String service) { + try { + return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.OK, "Success!", + consulHealthService.getAllHealthyNodes(service)); + } catch (ConsulException e) { + logger.error(logger.errorLogger, "Couldn't connect to consul - shouldn't break anything."); + return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.ERROR, "Error!", new ArrayList<>()); + } + } + + @RequestMapping(value = { "/service/all/{service}" }, method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<List<ServiceHealth>> getAllNodes(HttpServletRequest request, HttpServletResponse response, + @PathVariable("service") String service) { + try { + return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.OK, "Success!", + consulHealthService.getAllNodes(service)); + } catch (ConsulException e) { + logger.error(logger.errorLogger, "Couldn't connect to consul - shouldn't break anything."); + return new PortalRestResponse<List<ServiceHealth>>(PortalRestStatusEnum.ERROR, "Error!", new ArrayList<>()); + } + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java index 290a5ffc..81a61d57 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java @@ -1,385 +1,385 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EcompAuditLog;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.service.DashboardSearchService;
-import org.openecomp.portalapp.portal.transport.CommonWidget;
-import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalapp.util.EPUserUtils;
-import org.openecomp.portalsdk.core.domain.AuditLog;
-import org.openecomp.portalsdk.core.domain.support.CollaborateList;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.AuditService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-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;
-
-/**
- * Controller supplies data to Angular services on the dashboard page.
- */
-@Configuration
-@RestController
-@RequestMapping("/portalApi/dashboard")
-public class DashboardController extends EPRestrictedBaseController {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
-
- @Autowired
- private DashboardSearchService searchService;
- @Autowired
- private AuditService auditService;
-
- public enum WidgetCategory {
- EVENTS, NEWS, IMPORTANTRESOURCES;
- }
-
- /**
- * Validates the resource type parameter.
- *
- * @param resourceType
- * @return True if known in the enum WidgetCategory, else false.
- */
- private boolean isValidResourceType(String resourceType) {
- if (resourceType == null)
- return false;
- for (WidgetCategory wc : WidgetCategory.values())
- if (wc.name().equals(resourceType))
- return true;
- return false;
- }
-
- /**
- * Gets all widgets of the specified resource type.
- * In iteration 41 (when widget will utilized service onboarding), this method can be removed, instead we will use CommonWidgetController.java (basic auth based)
- *
- * @param request
- * @param resourceType
- * Request parameter.
- * @return Rest response wrapped around a CommonWidgetMeta object.
- */
- @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
- @RequestParam String resourceType) {
- if (!isValidResourceType(resourceType))
- return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.ERROR,
- "Unexpected resource type " + resourceType, null);
- return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success",
- searchService.getWidgetData(resourceType));
- }
-
-
- /**
- * Saves a batch of events, news or resources.
- *
- * @param commonWidgetMeta
- * read from POST body.
- * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
- */
- @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
- logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
- if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals(""))
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
- "Category cannot be null or empty");
- if (!isValidResourceType(commonWidgetMeta.getCategory()))
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
- "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
- // validate dates
- for (CommonWidget cw : commonWidgetMeta.getItems()) {
- String err = validateCommonWidget(cw);
- if (err != null)
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
- }
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
- searchService.saveWidgetDataBulk(commonWidgetMeta));
- }
-
- /**
- * Saves one: event, news or resource
- *
- * @param commonWidget
- * read from POST body
- * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
- */
- @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) {
- logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
- if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals(""))
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
- "Category cannot be null or empty");
- String err = validateCommonWidget(commonWidget);
- if (err != null)
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
- searchService.saveWidgetData(commonWidget));
- }
-
- /**
- * Used by the validate function
- */
- private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
-
- /**
- * Validates the content of a common widget.
- *
- * @param cw
- * @return null on success; an error message if validation fails.
- * @throws Exception
- */
- private String validateCommonWidget(CommonWidget cw) {
- if (!isValidResourceType(cw.getCategory()))
- return "Invalid category: " + cw.getCategory();
- if (cw.getTitle() == null || cw.getTitle().trim().length() == 0)
- return "Title is missing";
- if (cw.getHref() == null || cw.getHref().trim().length() == 0)
- return "HREF is missing";
- if (!cw.getHref().toLowerCase().startsWith("http"))
- return "HREF does not start with http";
- if (cw.getSortOrder() == null)
- return "Sort order is null";
- if (WidgetCategory.EVENTS.name().equals(cw.getCategory())) {
- if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0)
- return "Date is missing";
- try {
- yearMonthDayFormat.setLenient(false);
- Date date = yearMonthDayFormat.parse(cw.getEventDate());
- if (date == null)
- return "Failed to parse date " + cw.getEventDate();
- } catch (ParseException ex) {
- return ex.toString();
- }
- }
- return null;
- }
-
- /**
- * Deletes one: event, news or resource
- *
- * @param commonWidget
- * read from POST body
- * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
- */
- @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
- searchService.deleteWidgetData(commonWidget));
- }
-
- /**
- * Searches all portal for the input string.
- *
- * @param request
- * @param searchString
- * @return Rest response wrapped around a Map of String to List of Search
- * Result Item.
- */
- @EPAuditLog
- @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
- @RequestParam String searchString) {
-
- if (searchString != null)
- searchString = searchString.trim();
- EPUser user = EPUserUtils.getUserSession(request);
- try {
- if (user == null) {
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
- "searchPortal: User object is null? - check logs",
- new HashMap<String, List<SearchResultItem>>());
- } else if (searchString == null || searchString.length() == 0) {
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
- new HashMap<String, List<SearchResultItem>>());
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
- user.getLoginId(), searchString);
- Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
- searchString);
- /*Audit log the search*/
- AuditLog auditLog = new AuditLog();
- auditLog.setUserId(user.getId());
- auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_SEARCH);
- auditLog.setComments(searchString);
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- auditService.logActivity(auditLog, null);
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
- logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("DashboardController.PortalRestResponse",
- EcompAuditLog.CD_ACTIVITY_SEARCH, user.getOrgUserId(), null, searchString));
- MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
- MDC.remove(SystemProperties.MDC_TIMER);
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
- new HashMap<String, List<SearchResultItem>>());
- }
- }
-
- /**
- * Gets all active users.
- *
- * TODO: should only the superuser be allowed to use this API?
- *
- * @param request
- * @return Rest response wrapped around a list of String
- */
- @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json")
- public List<String> getActiveUsers(HttpServletRequest request) {
- List<String> activeUsers = null;
- List<String> onlineUsers = new ArrayList<>();
- try {
- EPUser user = EPUserUtils.getUserSession(request);
- String userId = user.getOrgUserId();
-
- activeUsers = searchService.getRelatedUsers(userId);
- HashSet<String> usersSet = CollaborateList.getInstance().getAllUserName();
- for (String users : activeUsers) {
- if (usersSet.contains(users)) {
- onlineUsers.add(users);
- }
- }
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
- }
- return onlineUsers;
- }
-
- /**
- * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
- *
- * @param request
- * @return Rest response wrapped around a number that is the number of milliseconds.
- */
- @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
- try {
- String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE);
- String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION);
- Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
- Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
- Map<String, String> results = new HashMap<String,String>();
- results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
- results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
- /**
- * Gets the window width threshold for collapsing right menu from system.properties.
- *
- * @param request
- * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
- */
- @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
- try {
- String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);
- Integer windowWidth = Integer.valueOf(windowWidthString);
- Map<String, String> results = new HashMap<String,String>();
- results.put("windowWidth", String.valueOf(windowWidth));
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
-
- /**
- * Gets the window width threshold for collapsing left menu from system.properties.
- *
- * @param request
- * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
- */
- @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
- try {
- String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);
- Integer windowWidth = Integer.valueOf(windowWidthString);
- Map<String, String> results = new HashMap<String,String>();
- results.put("windowWidth", String.valueOf(windowWidth));
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
- /**
- * Gets only those users that are 'related' to the currently logged-in user.
- *
- * @param request
- * @return Rest response wrapped around a List of String
- */
- @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
- EPUser user = EPUserUtils.getUserSession(request);
- try {
- if (user == null) {
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
- new ArrayList<>());
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
- searchService.getRelatedUsers(user.getLoginId()));
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
- new ArrayList<>());
- }
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EcompAuditLog; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.service.DashboardSearchService; +import org.openecomp.portalapp.portal.transport.CommonWidget; +import org.openecomp.portalapp.portal.transport.CommonWidgetMeta; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.domain.AuditLog; +import org.openecomp.portalsdk.core.domain.support.CollaborateList; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.AuditService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +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; + +/** + * Controller supplies data to Angular services on the dashboard page. + */ +@Configuration +@RestController +@RequestMapping("/portalApi/dashboard") +public class DashboardController extends EPRestrictedBaseController { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class); + + @Autowired + private DashboardSearchService searchService; + @Autowired + private AuditService auditService; + + public enum WidgetCategory { + EVENTS, NEWS, IMPORTANTRESOURCES; + } + + /** + * Validates the resource type parameter. + * + * @param resourceType + * @return True if known in the enum WidgetCategory, else false. + */ + private boolean isValidResourceType(String resourceType) { + if (resourceType == null) + return false; + for (WidgetCategory wc : WidgetCategory.values()) + if (wc.name().equals(resourceType)) + return true; + return false; + } + + /** + * Gets all widgets of the specified resource type. + * In iteration 41 (when widget will utilized service onboarding), this method can be removed, instead we will use CommonWidgetController.java (basic auth based) + * + * @param request + * @param resourceType + * Request parameter. + * @return Rest response wrapped around a CommonWidgetMeta object. + */ + @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request, + @RequestParam String resourceType) { + if (!isValidResourceType(resourceType)) + return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.ERROR, + "Unexpected resource type " + resourceType, null); + return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success", + searchService.getWidgetData(resourceType)); + } + + + /** + * Saves a batch of events, news or resources. + * + * @param commonWidgetMeta + * read from POST body. + * @return Rest response wrapped around a String; e.g., "success" or "ERROR" + */ + @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) { + logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta); + if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR", + "Category cannot be null or empty"); + if (!isValidResourceType(commonWidgetMeta.getCategory())) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + "Unexpected resource type " + commonWidgetMeta.getCategory(), null); + // validate dates + for (CommonWidget cw : commonWidgetMeta.getItems()) { + String err = validateCommonWidget(cw); + if (err != null) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null); + } + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", + searchService.saveWidgetDataBulk(commonWidgetMeta)); + } + + /** + * Saves one: event, news or resource + * + * @param commonWidget + * read from POST body + * @return Rest response wrapped around a String; e.g., "success" or "ERROR" + */ + @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) { + logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget); + if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals("")) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR", + "Category cannot be null or empty"); + String err = validateCommonWidget(commonWidget); + if (err != null) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null); + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", + searchService.saveWidgetData(commonWidget)); + } + + /** + * Used by the validate function + */ + private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd"); + + /** + * Validates the content of a common widget. + * + * @param cw + * @return null on success; an error message if validation fails. + * @throws Exception + */ + private String validateCommonWidget(CommonWidget cw) { + if (!isValidResourceType(cw.getCategory())) + return "Invalid category: " + cw.getCategory(); + if (cw.getTitle() == null || cw.getTitle().trim().length() == 0) + return "Title is missing"; + if (cw.getHref() == null || cw.getHref().trim().length() == 0) + return "HREF is missing"; + if (!cw.getHref().toLowerCase().startsWith("http")) + return "HREF does not start with http"; + if (cw.getSortOrder() == null) + return "Sort order is null"; + if (WidgetCategory.EVENTS.name().equals(cw.getCategory())) { + if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0) + return "Date is missing"; + try { + yearMonthDayFormat.setLenient(false); + Date date = yearMonthDayFormat.parse(cw.getEventDate()); + if (date == null) + return "Failed to parse date " + cw.getEventDate(); + } catch (ParseException ex) { + return ex.toString(); + } + } + return null; + } + + /** + * Deletes one: event, news or resource + * + * @param commonWidget + * read from POST body + * @return Rest response wrapped around a String; e.g., "success" or "ERROR" + */ + @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) { + logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget); + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", + searchService.deleteWidgetData(commonWidget)); + } + + /** + * Searches all portal for the input string. + * + * @param request + * @param searchString + * @return Rest response wrapped around a Map of String to List of Search + * Result Item. + */ + @EPAuditLog + @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request, + @RequestParam String searchString) { + + if (searchString != null) + searchString = searchString.trim(); + EPUser user = EPUserUtils.getUserSession(request); + try { + if (user == null) { + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, + "searchPortal: User object is null? - check logs", + new HashMap<String, List<SearchResultItem>>()); + } else if (searchString == null || searchString.length() == 0) { + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null", + new HashMap<String, List<SearchResultItem>>()); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'", + user.getLoginId(), searchString); + Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(), + searchString); + /*Audit log the search*/ + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_SEARCH); + auditLog.setComments(searchString); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + auditService.logActivity(auditLog, null); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("DashboardController.PortalRestResponse", + EcompAuditLog.CD_ACTIVITY_SEARCH, user.getOrgUserId(), null, searchString)); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.", + new HashMap<String, List<SearchResultItem>>()); + } + } + + /** + * Gets all active users. + * + * TODO: should only the superuser be allowed to use this API? + * + * @param request + * @return Rest response wrapped around a list of String + */ + @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json") + public List<String> getActiveUsers(HttpServletRequest request) { + List<String> activeUsers = null; + List<String> onlineUsers = new ArrayList<>(); + try { + EPUser user = EPUserUtils.getUserSession(request); + String userId = user.getOrgUserId(); + + activeUsers = searchService.getRelatedUsers(userId); + HashSet<String> usersSet = CollaborateList.getInstance().getAllUserName(); + for (String users : activeUsers) { + if (usersSet.contains(users)) { + onlineUsers.add(users); + } + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e); + } + return onlineUsers; + } + + /** + * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds. + * + * @param request + * @return Rest response wrapped around a number that is the number of milliseconds. + */ + @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) { + try { + String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE); + String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION); + Integer rateInMiliSec = Integer.valueOf(updateRate)*1000; + Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000; + Map<String, String> results = new HashMap<String,String>(); + results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec)); + results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec)); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null); + } + } + + /** + * Gets the window width threshold for collapsing right menu from system.properties. + * + * @param request + * @return Rest response wrapped around a number that is the window width threshold to collapse right menu. + */ + @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) { + try { + String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU); + Integer windowWidth = Integer.valueOf(windowWidthString); + Map<String, String> results = new HashMap<String,String>(); + results.put("windowWidth", String.valueOf(windowWidth)); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null); + } + } + + + /** + * Gets the window width threshold for collapsing left menu from system.properties. + * + * @param request + * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu. + */ + @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) { + try { + String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU); + Integer windowWidth = Integer.valueOf(windowWidthString); + Map<String, String> results = new HashMap<String,String>(); + results.put("windowWidth", String.valueOf(windowWidth)); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null); + } + } + + /** + * Gets only those users that are 'related' to the currently logged-in user. + * + * @param request + * @return Rest response wrapped around a List of String + */ + @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) { + EPUser user = EPUserUtils.getUserSession(request); + try { + if (user == null) { + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs", + new ArrayList<>()); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId()); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + searchService.getRelatedUsers(user.getLoginId())); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.", + new ArrayList<>()); + } + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java index 41da3357..ac1b9254 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java @@ -1,206 +1,206 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController;
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EPRole;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.AdminRolesService;
-import org.openecomp.portalapp.portal.service.EPLoginService;
-import org.openecomp.portalapp.portal.service.EPRoleService;
-import org.openecomp.portalapp.portal.service.FunctionalMenuService;
-import org.openecomp.portalapp.portal.service.UserNotificationService;
-import org.openecomp.portalapp.portal.transport.EpNotificationItem;
-import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalapp.portal.utils.PortalConstants;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
-import org.slf4j.MDC;
-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.ResponseBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.swagger.annotations.ApiOperation;
-
-@RestController
-@RequestMapping(PortalConstants.REST_AUX_API)
-@Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppsRestfulController.class);
-
- @Autowired
- private FunctionalMenuService functionalMenuService;
-
- @Autowired
- private EPLoginService epLoginService;
-
- @Autowired
- private AdminRolesService adminRolesService;
-
- @Autowired
- private UserNotificationService userNotificationService;
-
- @Autowired
- private EPRoleService epRoleService;
-
- @ApiOperation(value = "Creates a Portal user notification for roles identified in the content from an external application.", response = PortalAPIResponse.class)
- @RequestMapping(value = { "/publishNotification" }, method = RequestMethod.POST, produces = "application/json")
- @ResponseBody
- public PortalAPIResponse publishNotification(HttpServletRequest request,
- @RequestBody EpNotificationItem notificationItem) throws Exception {
- String appKey = request.getHeader("uebkey");
- EPApp app = findEpApp(appKey);
- List<Long> postRoleIds = new ArrayList<Long>();
- for (Long roleId : notificationItem.getRoleIds()) {
- EPRole role = epRoleService.getRole(app.getId(), roleId);
- if (role != null)
- postRoleIds.add(role.getId());
- }
-
- // --- recreate the user notification object with the POrtal Role Ids
- EpNotificationItem postItem = new EpNotificationItem();
- postItem.setRoleIds(postRoleIds);
- postItem.setIsForAllRoles("N");
- postItem.setIsForOnlineUsers("N");
- postItem.setActiveYn("Y");
- postItem.setPriority(notificationItem.getPriority());
- postItem.setMsgHeader(notificationItem.getMsgHeader());
- postItem.setMsgDescription(notificationItem.getMsgDescription());
- postItem.setStartTime(notificationItem.getStartTime());
- postItem.setEndTime(notificationItem.getEndTime());
- postItem.setCreatedDate(Calendar.getInstance().getTime());
- // default creator to 1 for now
- postItem.setCreatorId(PortalConstants.DEFAULT_NOTIFICATION_CREATOR);
- // ----
-
- try {
- userNotificationService.saveNotification(postItem);
- } catch (Exception e) {
- return new PortalAPIResponse(false, e.getMessage());
- }
-
- PortalAPIResponse response = new PortalAPIResponse(true, "success");
- return response;
- }
-
- private EPApp findEpApp(String uebKey) {
- List<?> list = null;
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where ueb_key = '" + uebKey + "'");
- list = getDataAccessService().getList(EPApp.class, criteria.toString(), null, null);
- return (list == null || list.size() == 0) ? null : (EPApp) list.get(0);
- }
-
- @ApiOperation(value = "Gets favorite items within the functional menu for the current user.", response = FavoritesFunctionalMenuItemJson.class, responseContainer="List")
- @RequestMapping(value = { "/getFavorites" }, method = RequestMethod.GET, produces = "application/json")
- public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- String loginId = "";
- String userAgent = "";
- List<FavoritesFunctionalMenuItemJson> favorites = null;
-
- loginId = request.getHeader(EPCommonSystemProperties.MDC_LOGIN_ID);
- userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
-
- EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
- logger.info(EELFLoggerDelegate.errorLogger,
- "getFavorites request was received from " + userAgent + " for the user " + loginId + ".");
- if (epUser == null || epUser.getId() == null) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "No User record found for the LoginId '" + loginId + "' in the database.");
- throw new Exception("Received null for Login-Id.");
- } else {
- favorites = functionalMenuService.getFavoriteItems(epUser.getId());
- FieldsValidator fieldsValidator = new FieldsValidator();
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
-
- EcompPortalUtils.logAndSerializeObject(logger, "/getFavorites", "result = ", favorites);
- }
-
- return favorites;
- }
-
- @ApiOperation(value = "Gets functional menu items appropriate for the current user.", response = FunctionalMenuItem.class, responseContainer="List")
- @RequestMapping(value = {
- "/functionalMenuItemsForUser" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- String loginId = "";
- String userAgent = "";
- List<FunctionalMenuItem> fnMenuItems = null;
-
- loginId = request.getHeader("LoginId");
- userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
-
- EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
- logger.info(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemsForUser request was received from "
- + userAgent + " for the user " + loginId + ".");
- if (epUser == null || epUser.getId() == null) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "No User record found for the LoginId '" + loginId + "' in the database.");
- throw new Exception("Received null for Login-Id.");
- } else if (adminRolesService.isSuperAdmin(epUser)) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()");
- fnMenuItems = functionalMenuService.getFunctionalMenuItems();
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()");
- fnMenuItems = functionalMenuService.getFunctionalMenuItemsForUser(epUser.getOrgUserId());
- }
-
- FieldsValidator fieldsValidator = new FieldsValidator();
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
-
- EcompPortalUtils.logAndSerializeObject(logger, "/functionalMenuItemsForUser", "result = ", fnMenuItems);
-
- return fnMenuItems;
- }
-
- @ExceptionHandler(Exception.class)
- protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
- logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
- response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.EPLoginService; +import org.openecomp.portalapp.portal.service.EPRoleService; +import org.openecomp.portalapp.portal.service.FunctionalMenuService; +import org.openecomp.portalapp.portal.service.UserNotificationService; +import org.openecomp.portalapp.portal.transport.EpNotificationItem; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse; +import org.slf4j.MDC; +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.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.annotations.ApiOperation; + +@RestController +@RequestMapping(PortalConstants.REST_AUX_API) +@Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppsRestfulController.class); + + @Autowired + private FunctionalMenuService functionalMenuService; + + @Autowired + private EPLoginService epLoginService; + + @Autowired + private AdminRolesService adminRolesService; + + @Autowired + private UserNotificationService userNotificationService; + + @Autowired + private EPRoleService epRoleService; + + @ApiOperation(value = "Creates a Portal user notification for roles identified in the content from an external application.", response = PortalAPIResponse.class) + @RequestMapping(value = { "/publishNotification" }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public PortalAPIResponse publishNotification(HttpServletRequest request, + @RequestBody EpNotificationItem notificationItem) throws Exception { + String appKey = request.getHeader("uebkey"); + EPApp app = findEpApp(appKey); + List<Long> postRoleIds = new ArrayList<Long>(); + for (Long roleId : notificationItem.getRoleIds()) { + EPRole role = epRoleService.getRole(app.getId(), roleId); + if (role != null) + postRoleIds.add(role.getId()); + } + + // --- recreate the user notification object with the POrtal Role Ids + EpNotificationItem postItem = new EpNotificationItem(); + postItem.setRoleIds(postRoleIds); + postItem.setIsForAllRoles("N"); + postItem.setIsForOnlineUsers("N"); + postItem.setActiveYn("Y"); + postItem.setPriority(notificationItem.getPriority()); + postItem.setMsgHeader(notificationItem.getMsgHeader()); + postItem.setMsgDescription(notificationItem.getMsgDescription()); + postItem.setStartTime(notificationItem.getStartTime()); + postItem.setEndTime(notificationItem.getEndTime()); + postItem.setCreatedDate(Calendar.getInstance().getTime()); + // default creator to 1 for now + postItem.setCreatorId(PortalConstants.DEFAULT_NOTIFICATION_CREATOR); + // ---- + + try { + userNotificationService.saveNotification(postItem); + } catch (Exception e) { + return new PortalAPIResponse(false, e.getMessage()); + } + + PortalAPIResponse response = new PortalAPIResponse(true, "success"); + return response; + } + + private EPApp findEpApp(String uebKey) { + List<?> list = null; + StringBuffer criteria = new StringBuffer(); + criteria.append(" where ueb_key = '" + uebKey + "'"); + list = getDataAccessService().getList(EPApp.class, criteria.toString(), null, null); + return (list == null || list.size() == 0) ? null : (EPApp) list.get(0); + } + + @ApiOperation(value = "Gets favorite items within the functional menu for the current user.", response = FavoritesFunctionalMenuItemJson.class, responseContainer="List") + @RequestMapping(value = { "/getFavorites" }, method = RequestMethod.GET, produces = "application/json") + public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request, + HttpServletResponse response) throws Exception { + String loginId = ""; + String userAgent = ""; + List<FavoritesFunctionalMenuItemJson> favorites = null; + + loginId = request.getHeader(EPCommonSystemProperties.MDC_LOGIN_ID); + userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME); + + EPUser epUser = epLoginService.findUserWithoutPwd(loginId); + logger.info(EELFLoggerDelegate.errorLogger, + "getFavorites request was received from " + userAgent + " for the user " + loginId + "."); + if (epUser == null || epUser.getId() == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "No User record found for the LoginId '" + loginId + "' in the database."); + throw new Exception("Received null for Login-Id."); + } else { + favorites = functionalMenuService.getFavoriteItems(epUser.getId()); + FieldsValidator fieldsValidator = new FieldsValidator(); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + + EcompPortalUtils.logAndSerializeObject(logger, "/getFavorites", "result = ", favorites); + } + + return favorites; + } + + @ApiOperation(value = "Gets functional menu items appropriate for the current user.", response = FunctionalMenuItem.class, responseContainer="List") + @RequestMapping(value = { + "/functionalMenuItemsForUser" }, method = RequestMethod.GET, produces = "application/json") + public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(HttpServletRequest request, + HttpServletResponse response) throws Exception { + String loginId = ""; + String userAgent = ""; + List<FunctionalMenuItem> fnMenuItems = null; + + loginId = request.getHeader("LoginId"); + userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME); + + EPUser epUser = epLoginService.findUserWithoutPwd(loginId); + logger.info(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemsForUser request was received from " + + userAgent + " for the user " + loginId + "."); + if (epUser == null || epUser.getId() == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "No User record found for the LoginId '" + loginId + "' in the database."); + throw new Exception("Received null for Login-Id."); + } else if (adminRolesService.isSuperAdmin(epUser)) { + logger.debug(EELFLoggerDelegate.debugLogger, + "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()"); + fnMenuItems = functionalMenuService.getFunctionalMenuItems(); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, + "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()"); + fnMenuItems = functionalMenuService.getFunctionalMenuItemsForUser(epUser.getOrgUserId()); + } + + FieldsValidator fieldsValidator = new FieldsValidator(); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + + EcompPortalUtils.logAndSerializeObject(logger, "/functionalMenuItemsForUser", "result = ", fnMenuItems); + + return fnMenuItems; + } + + @ExceptionHandler(Exception.class) + protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException { + logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e); + response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage()); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java index de71766d..490a1829 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java @@ -1,555 +1,662 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.cxf.transport.http.HTTPException;
-import org.json.JSONObject;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-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.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.UserProfileService;
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.SharedContext;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.AdminRolesService;
-import org.openecomp.portalapp.portal.service.EPAuditService;
-import org.openecomp.portalapp.portal.service.FunctionalMenuService;
-import org.openecomp.portalapp.portal.service.SearchService;
-import org.openecomp.portalapp.portal.service.SharedContextService;
-import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRole;
-import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRolesList;
-import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItem;
-import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuItemWithRoles;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalapp.util.EPUserUtils;
-
-/**
- * Supports menus at the top of the Portal app landing page.
- */
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class FunctionalMenuController extends EPRestrictedBaseController {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuController.class);
-
- @Autowired
- AdminRolesService adminRolesService;
- @Autowired
- FunctionalMenuService functionalMenuService;
- @Autowired
- SharedContextService sharedContextService;
- @Autowired
- UserProfileService service;
- @Autowired
- SearchService searchService;
- @Autowired
- EPAuditService epAuditService;
-
- /**
- * RESTful service method to fetch all the FunctionalMenuItems.
- *
- * @return List of FunctionalMenuItem objects
- */
- @RequestMapping(value = { "/portalApi/functionalMenu" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getMenuItems(HttpServletRequest request, HttpServletResponse response) {
- // TODO: should only the superuser be allowed to use this API?
- List<FunctionalMenuItem> menuItems = null;
- try {
- menuItems = functionalMenuService.getFunctionalMenuItems();
- functionalMenuService.assignHelpURLs(menuItems);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenu", "result =", menuItems);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling functionalMenu. Details: " + EcompPortalUtils.getStackTrace(e));
- }
- return menuItems;
- }
-
- /**
- * RESTful service method to fetch all the FunctionalMenuItems, both active
- * and inactive, for the EditFunctionalMenu feature. Can only be accessed by
- * the portal admin.
- *
- * @return List of FunctionalMenuItem objects
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuForEditing" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getMenuItemsForEditing(HttpServletRequest request, HttpServletResponse response) {
- // TODO: should only the superuser be allowed to use this API?
- EPUser user = EPUserUtils.getUserSession(request);
- List<FunctionalMenuItem> menuItems = null;
- try {
- if (!adminRolesService.isSuperAdmin(user)) {
- EcompPortalUtils.setBadPermissions(user, response, "getFunctionalMenuItemDetails");
- } else {
- menuItems = functionalMenuService.getFunctionalMenuItems(true);
- }
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForEditing", "result =", menuItems);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling functionalMenuForEditing. Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
- return menuItems;
- }
-
- /**
- * RESTful service method to fetch all the FunctionalMenuItems, active
- *, for the Functional menu in notification Tree feature.
- *
- * @return List of FunctionalMenuItem objects
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuForNotificationTree" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getMenuItemsForNotifications(HttpServletRequest request, HttpServletResponse response) {
- // TODO: should only the superuser be allowed to use this API?
- EPUser user = EPUserUtils.getUserSession(request);
- List<FunctionalMenuItem> menuItems = null;
- try {
- menuItems = functionalMenuService.getFunctionalMenuItemsForNotificationTree(true);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForNotificationTree", "result =", menuItems);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling functionalMenuForNotifications. Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
- return menuItems;
- }
-
- /**
- * RESTful service method to fetch all FunctionalMenuItems associated with
- * an application.
- *
- * @return List of FunctionalMenuItem objects
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuForApp/{appId}" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getMenuItemsForApp(HttpServletRequest request, @PathVariable("appId") Integer appId)
- throws HTTPException {
- // TODO: should only the superuser be allowed to use this API?
- List<FunctionalMenuItem> menuItems = null;
- try {
- menuItems = functionalMenuService.getFunctionalMenuItemsForApp(appId);
- functionalMenuService.assignHelpURLs(menuItems);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForApp/" + appId, "result =", menuItems);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling functionalMenuForApp. Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
- return menuItems;
- }
-
- /**
- * RESTful service method to fetch all FunctionalMenuItems associated with
- * the applications and roles that a user has access to.
- *
- * @return List of FunctionalMenuItem objects
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuForUser/{orgUserId}" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getMenuItemsForUser(HttpServletRequest request,
- @PathVariable("orgUserId") String orgUserId) throws HTTPException {
- // TODO: should only the superuser be allowed to use this API?
- List<FunctionalMenuItem> menuItems = null;
- try {
- menuItems = functionalMenuService.getFunctionalMenuItemsForUser(orgUserId);
- functionalMenuService.assignHelpURLs(menuItems);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForUser/" + orgUserId, "result =", menuItems);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling functionalMenuForUser. Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
-
- return menuItems;
- }
-
- /**
- * RESTful service method to fetch all FunctionalMenuItems associated with
- * the applications and roles that the authenticated user has access to.
- *
- * @return List of FunctionalMenuItem objects
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuForAuthUser" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuItem> getMenuItemsForAuthUser(HttpServletRequest request, HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- List<FunctionalMenuItem> menuItems = null;
- try {
- if (user == null) {
- EcompPortalUtils.setBadPermissions(user, response, "getMenuItemsForAuthUser");
- } else if (adminRolesService.isSuperAdmin(user)) {
- menuItems = functionalMenuService.getFunctionalMenuItems();
- } else {
- // calculate the menu items
- String orgUserId = user.getOrgUserId();
- menuItems = functionalMenuService.getFunctionalMenuItemsForUser(orgUserId);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForUser/" + orgUserId, "result =",
- menuItems);
- }
- functionalMenuService.assignHelpURLs(menuItems);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling getMenuItemsForAuthUser. Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
- return menuItems;
- }
-
- /**
- * RESTful service method to fetch the details for a functional menu item.
- * Requirement: you must be the Ecomp portal super admin user.
- *
- * @return FunctionalMenuItem object
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuItemDetails/{menuId}" }, method = RequestMethod.GET, produces = "application/json")
- public FunctionalMenuItem getFunctionalMenuItemDetails(HttpServletRequest request,
- @PathVariable("menuId") Integer menuId, HttpServletResponse response) throws HTTPException {
- // TODO: return FunctionalMenuItemJson
- // TODO: modify FunctionalMenuItem to not include the transient fields
- FunctionalMenuItem menuItem = null;
- try {
- EPUser user = EPUserUtils.getUserSession(request);
- if (!adminRolesService.isSuperAdmin(user)) {
- EcompPortalUtils.setBadPermissions(user, response, "getFunctionalMenuItemDetails");
- } else {
- menuItem = functionalMenuService.getFunctionalMenuItemDetails(menuId);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItemDetails/" + menuId, "result =",
- menuItem);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while calling functionalMenuItemDetails. Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
-
- return menuItem;
- }
-
- /**
- * RESTful service method to create a new menu item.
- *
- * Requirement: you must be the Ecomp portal super admin user.
- */
- @RequestMapping(value = { "/portalApi/functionalMenuItem" }, method = RequestMethod.POST)
- public FieldsValidator createFunctionalMenuItem(HttpServletRequest request,
- @RequestBody FunctionalMenuItemWithRoles menuItemJson, HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
- if (!adminRolesService.isSuperAdmin(user)) {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "FunctionalMenuController.createFunctionalMenuItem bad permissions");
- EcompPortalUtils.setBadPermissions(user, response, "createFunctionalMenuItem");
- } else {
- fieldsValidator = functionalMenuService.createFunctionalMenuItem(menuItemJson);
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "POST result =",
- response.getStatus());
- }
-
- return fieldsValidator;
- }
-
- /**
- * RESTful service method to update an existing menu item
- *
- * Requirement: you must be the Ecomp portal super admin user.
- *
- * @return FieldsValidator
- */
- @RequestMapping(value = { "/portalApi/functionalMenuItem" }, method = RequestMethod.PUT)
- public FieldsValidator editFunctionalMenuItem(HttpServletRequest request,
- @RequestBody FunctionalMenuItemWithRoles menuItemJson, HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
- if (!adminRolesService.isSuperAdmin(user)) {
- EcompPortalUtils.setBadPermissions(user, response, "editFunctionalMenuItem");
- } else {
- fieldsValidator = functionalMenuService.editFunctionalMenuItem(menuItemJson);
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "PUT result =",
- response.getStatus());
- }
-
- return fieldsValidator;
- }
-
- /**
- * RESTful service method to delete a menu item
- *
- * @return FieldsValidator
- */
- @RequestMapping(value = { "/portalApi/functionalMenuItem/{menuId}" }, method = RequestMethod.DELETE)
- public FieldsValidator deleteFunctionalMenuItem(HttpServletRequest request, @PathVariable("menuId") Long menuId,
- HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
- if (!adminRolesService.isSuperAdmin(user)) {
- EcompPortalUtils.setBadPermissions(user, response, "deleteFunctionalMenuItem");
- } else {
- fieldsValidator = functionalMenuService.deleteFunctionalMenuItem(menuId);
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "DELETE result =",
- response.getStatus());
- }
-
- return fieldsValidator;
- }
-
- /**
- * RESTful service to regenerate table
- *
- * @param request
- * @param response
- *
- * @return FieldsValidator
- */
- @RequestMapping(value = { "/portalApi/regenerateFunctionalMenuAncestors" }, method = RequestMethod.GET)
- public FieldsValidator regenerateAncestorTable(HttpServletRequest request, HttpServletResponse response) {
- // TODO: should only the superuser be allowed to use this API?
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
-
- if (!adminRolesService.isSuperAdmin(user)) {
- EcompPortalUtils.setBadPermissions(user, response, "deleteFunctionalMenuItem");
- } else {
- fieldsValidator = functionalMenuService.regenerateAncestorTable();
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/regenerateAncestorTable", "GET result =",
- response.getStatus());
- }
-
- return fieldsValidator;
- }
-
- /**
- * RESful service to set a favorite item.
- *
- * @return FieldsValidator
- */
- @RequestMapping(value = { "/portalApi/setFavoriteItem" }, method = RequestMethod.POST)
- public FieldsValidator addFavoriteItem(HttpServletRequest request,
- @RequestBody FavoritesFunctionalMenuItem menuItemJson, HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
- menuItemJson.userId = user.getId();
- fieldsValidator = functionalMenuService.setFavoriteItem(menuItemJson);
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/setFavoriteItem", "Post result =", response.getStatus());
-
- return fieldsValidator;
- }
-
- /**
- * RESTful service to get favorites for the current user as identified in
- * the session
- *
- * @return List of FavoritesFunctionalMenuItemJson
- */
- @RequestMapping(value = {
- "/portalApi/getFavoriteItems" }, method = RequestMethod.GET, produces = "application/json")
- public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request,
- HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- List<FavoritesFunctionalMenuItemJson> favorites = functionalMenuService.getFavoriteItems(user.getId());
- FieldsValidator fieldsValidator = new FieldsValidator();
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getFavoriteItems", "GET result =", response.getStatus());
- return favorites;
- }
-
- /**
- * RESTful service to delete a favorite menu item for the current user as
- * identified in the session.
- *
- * @return FieldsValidator
- */
- @RequestMapping(value = { "/portalApi/removeFavoriteItem/{menuId}" }, method = RequestMethod.DELETE)
- public FieldsValidator deleteFavoriteItem(HttpServletRequest request, @PathVariable("menuId") Long menuId,
- HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
- Long userId = user.getId();
- fieldsValidator = functionalMenuService.removeFavoriteItem(userId, menuId);
- response.setStatus(fieldsValidator.httpStatusCode.intValue());
- EcompPortalUtils.logAndSerializeObject(logger, "/deleteFavoriteItem", "DELETE result =", response.getStatus());
-
- return fieldsValidator;
- }
-
- /**
- * RESTful service to get user information: user's first and last names, ATT
- * UID, email and last-login. (Actually has nothing to do with the real
- * functional menu.) First attempts to get the information from the Tomcat
- * session (i.e., the CSP cookie); if that fails, calls the shared context
- * service to read the information from the database. Gives back what it
- * found, any of which may be null, as a JSON collection.
- *
- * @return JSON collection of key-value pairs shown below.
- */
- @RequestMapping(value = {
- "/portalApi/functionalMenuStaticInfo" }, method = RequestMethod.GET, produces = "application/json")
- public String getFunctionalMenuStaticInfo(HttpServletRequest request, HttpServletResponse response) {
-
- // Get user details from session
- logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuStaticInfo: getting user info");
- String fnMenuStaticResponse = null;
- try {
- String orgUserIdStr = null, firstNameStr = null, lastNameStr = null, emailStr = null, lastLogin = null;
- EPUser user = EPUserUtils.getUserSession(request);
- firstNameStr = user.getFirstName();
- lastNameStr = user.getLastName();
- orgUserIdStr = user.getOrgUserId();
- emailStr = user.getEmail();
- if (emailStr == null || emailStr.equals("")) {
- EPUser userResult = searchService.searchUserByUserId(orgUserIdStr);
- emailStr = userResult.getEmail();
- }
- SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ssZ");
- Date lastLoginDate = user.getLastLoginDate();
- if (lastLoginDate == null) {
- // should never happen
- logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenuStaticInfo: no last login in session");
- lastLogin = "no last login available";
- }
- else {
- lastLogin = sdf.format(lastLoginDate);
- }
-
- // If any item is missing from session, try the Shared Context
- // service.
- SharedContext orgUserIdSC = null, firstNameSC = null, lastNameSC = null, emailSC = null;
- String sessionId = request.getSession().getId();
- if (firstNameStr == null)
- firstNameSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_FIRST_NAME);
- if (lastNameStr == null)
- lastNameSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_LAST_NAME);
- if (emailStr == null)
- emailSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_EMAIL);
- if (orgUserIdStr == null)
- orgUserIdSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_ORG_USERID);
-
- // Build the response
- Map<String, String> map = new HashMap<String, String>();
- map.put("firstName",
- firstNameStr != null ? firstNameStr : (firstNameSC != null ? firstNameSC.getCvalue() : null));
- map.put("lastName",
- lastNameStr != null ? lastNameStr : (lastNameSC != null ? lastNameSC.getCvalue() : null));
- map.put("email", emailStr != null ? emailStr : (emailSC != null ? emailSC.getCvalue() : null));
- map.put("userId", orgUserIdStr != null ? orgUserIdStr : (orgUserIdSC != null ? orgUserIdSC.getCvalue() : null));
- map.put("last_login", lastLogin);
- JSONObject j = new JSONObject(map);
- fnMenuStaticResponse = j.toString();
- // Be chatty in the log
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuStaticInfo", "GET result =",
- fnMenuStaticResponse);
- } catch (Exception e) {
- // Should never happen.
- logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenuStaticInfo failed", e);
- // Return a real error?
- // fnMenuStaticResponse = "{ \"status\": \"error\", \"message\": \""
- // + e.toString() + "\" }";
- // But the angular controller expects null on error.
- }
- return fnMenuStaticResponse;
- }
-
- private Comparator<BusinessCardApplicationRole> getUserAppRolesComparator = new Comparator<BusinessCardApplicationRole>() {
- public int compare(BusinessCardApplicationRole o1, BusinessCardApplicationRole o2) {
- return o1.getAppName().compareTo(o2.getAppName());
- }
- };
-
- @RequestMapping(value = {
- "/portalApi/userApplicationRoles" }, method = RequestMethod.GET, produces = "application/json")
- public List<BusinessCardApplicationRolesList> getAppList(HttpServletRequest request,@RequestParam("userId") String userId) throws IOException {
-
-
- List<BusinessCardApplicationRolesList> AppRoles = null;
- try {
- List<BusinessCardApplicationRole> userAppRoleList = functionalMenuService.getUserAppRolesList(userId);
-
- Collections.sort(userAppRoleList, getUserAppRolesComparator);
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList);
-
- AppRoles = new ArrayList<BusinessCardApplicationRolesList>();
- for(BusinessCardApplicationRole userAppRole: userAppRoleList)
- {
- boolean found = false;
- List<String> roles = null;
-
- for(BusinessCardApplicationRolesList app :AppRoles)
- {
- if(app.getAppName().equals(userAppRole.getAppName()))
- {
- roles= app.getRoleNames();
- roles.add(userAppRole.getRoleName());
- app.setRoleNames(roles);
- found = true;
- break;
- }
- }
-
- if(!found)
- {
- roles = new ArrayList<String>();
- roles.add(userAppRole.getRoleName());
- AppRoles.add(new BusinessCardApplicationRolesList(userAppRole.getAppName(), roles));
- }
-
- Collections.sort(roles);
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- logger.error(EELFLoggerDelegate.errorLogger, "getAppList failed", e);
- }
-
- return AppRoles;
-
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +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.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.SharedContext; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.FunctionalMenuService; +import org.openecomp.portalapp.portal.service.SearchService; +import org.openecomp.portalapp.portal.service.SharedContextService; +import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRole; +import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRolesList; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItemWithRoles; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +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.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * Supports menus at the top of the Portal app landing page. + */ +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class FunctionalMenuController extends EPRestrictedBaseController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuController.class); + + @Autowired + private AdminRolesService adminRolesService; + @Autowired + private FunctionalMenuService functionalMenuService; + @Autowired + private SharedContextService sharedContextService; + @Autowired + private SearchService searchService; + + /** + * RESTful service method to fetch all the FunctionalMenuItems. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return List of FunctionalMenuItem objects + */ + @RequestMapping(value = { "/portalApi/functionalMenu" }, method = RequestMethod.GET, produces = "application/json") + public List<FunctionalMenuItem> getMenuItems(HttpServletRequest request, HttpServletResponse response) { + // TODO: should only the superuser be allowed to use this API? + List<FunctionalMenuItem> menuItems = null; + try { + menuItems = functionalMenuService.getFunctionalMenuItems(); + functionalMenuService.assignHelpURLs(menuItems); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenu", "result =", menuItems); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while calling functionalMenu. Details: " + EcompPortalUtils.getStackTrace(e)); + } + return menuItems; + } + + /** + * RESTful service method to get ECOMP Portal Title. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return PortalRestResponse of ECOMP portal title + */ + @RequestMapping(value = { "/portalApi/ecompTitle" }, method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<String> getECOMPTitle(HttpServletRequest request, HttpServletResponse response) { + PortalRestResponse<String> portalRestResponse = null; + try { + String ecompTitle = SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME); + portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", ecompTitle); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/ecompTitle", "result =", ecompTitle); + } catch (Exception e) { + portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(), null); + logger.error(EELFLoggerDelegate.errorLogger, "getEcompTitle failed", e); + } + return portalRestResponse; + } + + /** + * RESTful service method to fetch all the FunctionalMenuItems, both active + * and inactive, for the EditFunctionalMenu feature. Can only be accessed by + * the portal admin. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return List of FunctionalMenuItem objects + */ + @RequestMapping(value = { + "/portalApi/functionalMenuForEditing" }, method = RequestMethod.GET, produces = "application/json") + public List<FunctionalMenuItem> getMenuItemsForEditing(HttpServletRequest request, HttpServletResponse response) { + // TODO: should only the superuser be allowed to use this API? + EPUser user = EPUserUtils.getUserSession(request); + List<FunctionalMenuItem> menuItems = null; + try { + if (!adminRolesService.isSuperAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "getFunctionalMenuItemDetails"); + } else { + menuItems = functionalMenuService.getFunctionalMenuItems(true); + } + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForEditing", "result =", + menuItems); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while calling functionalMenuForEditing. Details: " + + EcompPortalUtils.getStackTrace(e)); + } + return menuItems; + } + + /** + * RESTful service method to fetch all the FunctionalMenuItems, active , for + * the Functional menu in notification Tree feature. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return List of FunctionalMenuItem objects + */ + @RequestMapping(value = { + "/portalApi/functionalMenuForNotificationTree" }, method = RequestMethod.GET, produces = "application/json") + public List<FunctionalMenuItem> getMenuItemsForNotifications(HttpServletRequest request, + HttpServletResponse response) { + // TODO: should only the superuser be allowed to use this API? + // EPUser user = EPUserUtils.getUserSession(request); + List<FunctionalMenuItem> menuItems = null; + try { + menuItems = functionalMenuService.getFunctionalMenuItemsForNotificationTree(true); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForNotificationTree", "result =", + menuItems); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while calling functionalMenuForNotifications. Details: " + + EcompPortalUtils.getStackTrace(e)); + } + return menuItems; + } + + /** + * RESTful service method to fetch all FunctionalMenuItems associated with + * an application. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @param appId + * application ID + * @return List of FunctionalMenuItem objects + */ + @RequestMapping(value = { + "/portalApi/functionalMenuForApp/{appId}" }, method = RequestMethod.GET, produces = "application/json") + public List<FunctionalMenuItem> getMenuItemsForApp(HttpServletRequest request, + @PathVariable("appId") Integer appId) { + // TODO: should only the superuser be allowed to use this API? + List<FunctionalMenuItem> menuItems = null; + try { + menuItems = functionalMenuService.getFunctionalMenuItemsForApp(appId); + functionalMenuService.assignHelpURLs(menuItems); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForApp/" + appId, "result =", + menuItems); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while calling functionalMenuForApp. Details: " + + EcompPortalUtils.getStackTrace(e)); + } + return menuItems; + } + + /** + * RESTful service method to fetch all FunctionalMenuItems associated with + * the applications and roles that a user has access to. + * + * @param request + * HttpServletRequest + * @param orgUserId + * user ID + * @return List of FunctionalMenuItem objects + */ + @RequestMapping(value = { + "/portalApi/functionalMenuForUser/{orgUserId}" }, method = RequestMethod.GET, produces = "application/json") + public List<FunctionalMenuItem> getMenuItemsForUser(HttpServletRequest request, + @PathVariable("orgUserId") String orgUserId) { + // TODO: should only the superuser be allowed to use this API? + List<FunctionalMenuItem> menuItems = null; + try { + menuItems = functionalMenuService.getFunctionalMenuItemsForUser(orgUserId); + functionalMenuService.assignHelpURLs(menuItems); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForUser/" + orgUserId, "result =", + menuItems); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while calling functionalMenuForUser. Details: " + + EcompPortalUtils.getStackTrace(e)); + } + + return menuItems; + } + + /** + * RESTful service method to fetch all FunctionalMenuItems associated with + * the applications and roles that the authenticated user has access to. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return List of FunctionalMenuItem objects + */ + @RequestMapping(value = { + "/portalApi/functionalMenuForAuthUser" }, method = RequestMethod.GET, produces = "application/json") + public List<FunctionalMenuItem> getMenuItemsForAuthUser(HttpServletRequest request, HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + List<FunctionalMenuItem> menuItems = null; + try { + if (user == null) { + EcompPortalUtils.setBadPermissions(user, response, "getMenuItemsForAuthUser"); + } else if (adminRolesService.isSuperAdmin(user)) { + menuItems = functionalMenuService.getFunctionalMenuItems(); + } else { + // calculate the menu items + String orgUserId = user.getOrgUserId(); + menuItems = functionalMenuService.getFunctionalMenuItemsForUser(orgUserId); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuForUser/" + orgUserId, + "result =", menuItems); + } + functionalMenuService.assignHelpURLs(menuItems); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while calling getMenuItemsForAuthUser. Details: " + + EcompPortalUtils.getStackTrace(e)); + } + return menuItems; + } + + /** + * RESTful service method to fetch the details for a functional menu item. + * Requirement: you must be the Ecomp portal super admin user. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @param menuId + * menu ID + * @return FunctionalMenuItem object + */ + @RequestMapping(value = { + "/portalApi/functionalMenuItemDetails/{menuId}" }, method = RequestMethod.GET, produces = "application/json") + public FunctionalMenuItem getFunctionalMenuItemDetails(HttpServletRequest request, + @PathVariable("menuId") Integer menuId, HttpServletResponse response) { + // TODO: return FunctionalMenuItemJson + // TODO: modify FunctionalMenuItem to not include the transient fields + FunctionalMenuItem menuItem = null; + try { + EPUser user = EPUserUtils.getUserSession(request); + if (!adminRolesService.isSuperAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "getFunctionalMenuItemDetails"); + } else { + menuItem = functionalMenuService.getFunctionalMenuItemDetails(menuId); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItemDetails/" + menuId, + "result =", menuItem); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while calling functionalMenuItemDetails. Details: " + + EcompPortalUtils.getStackTrace(e)); + } + + return menuItem; + } + + /** + * RESTful service method to create a new menu item. + * + * Requirement: you must be the Ecomp portal super admin user. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @param menuItemJson + * FunctionalMenuItemWithRoles + * @return FieldsValidator + */ + @RequestMapping(value = { "/portalApi/functionalMenuItem" }, method = RequestMethod.POST) + public FieldsValidator createFunctionalMenuItem(HttpServletRequest request, + @RequestBody FunctionalMenuItemWithRoles menuItemJson, HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + FieldsValidator fieldsValidator = null; + if (!adminRolesService.isSuperAdmin(user)) { + logger.debug(EELFLoggerDelegate.debugLogger, + "FunctionalMenuController.createFunctionalMenuItem bad permissions"); + EcompPortalUtils.setBadPermissions(user, response, "createFunctionalMenuItem"); + } else { + fieldsValidator = functionalMenuService.createFunctionalMenuItem(menuItemJson); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "POST result =", + response.getStatus()); + } + + return fieldsValidator; + } + + /** + * RESTful service method to update an existing menu item + * + * Requirement: you must be the Ecomp portal super admin user. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @param menuItemJson + * FunctionalMenuItemWithRoles + * @return FieldsValidator + */ + @RequestMapping(value = { "/portalApi/functionalMenuItem" }, method = RequestMethod.PUT) + public FieldsValidator editFunctionalMenuItem(HttpServletRequest request, + @RequestBody FunctionalMenuItemWithRoles menuItemJson, HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + FieldsValidator fieldsValidator = null; + if (!adminRolesService.isSuperAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "editFunctionalMenuItem"); + } else { + fieldsValidator = functionalMenuService.editFunctionalMenuItem(menuItemJson); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "PUT result =", + response.getStatus()); + } + + return fieldsValidator; + } + + /** + * RESTful service method to delete a menu item + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @param menuId + * menu identifier + * @return FieldsValidator + */ + @RequestMapping(value = { "/portalApi/functionalMenuItem/{menuId}" }, method = RequestMethod.DELETE) + public FieldsValidator deleteFunctionalMenuItem(HttpServletRequest request, @PathVariable("menuId") Long menuId, + HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + FieldsValidator fieldsValidator = null; + if (!adminRolesService.isSuperAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "deleteFunctionalMenuItem"); + } else { + fieldsValidator = functionalMenuService.deleteFunctionalMenuItem(menuId); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuItem", "DELETE result =", + response.getStatus()); + } + + return fieldsValidator; + } + + /** + * RESTful service to regenerate table + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return FieldsValidator + */ + @RequestMapping(value = { "/portalApi/regenerateFunctionalMenuAncestors" }, method = RequestMethod.GET) + public FieldsValidator regenerateAncestorTable(HttpServletRequest request, HttpServletResponse response) { + // TODO: should only the superuser be allowed to use this API? + EPUser user = EPUserUtils.getUserSession(request); + FieldsValidator fieldsValidator = null; + + if (!adminRolesService.isSuperAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "deleteFunctionalMenuItem"); + } else { + fieldsValidator = functionalMenuService.regenerateAncestorTable(); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/regenerateAncestorTable", "GET result =", + response.getStatus()); + } + + return fieldsValidator; + } + + /** + * RESful service to set a favorite item. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @param menuItemJson + * FunctionalMenuItemWithRoles + * @return FieldsValidator + */ + @RequestMapping(value = { "/portalApi/setFavoriteItem" }, method = RequestMethod.POST) + public FieldsValidator addFavoriteItem(HttpServletRequest request, + @RequestBody FavoritesFunctionalMenuItem menuItemJson, HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + FieldsValidator fieldsValidator = null; + menuItemJson.userId = user.getId(); + fieldsValidator = functionalMenuService.setFavoriteItem(menuItemJson); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/setFavoriteItem", "Post result =", + response.getStatus()); + + return fieldsValidator; + } + + /** + * RESTful service to get favorites for the current user as identified in + * the session + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return List of FavoritesFunctionalMenuItemJson + */ + @RequestMapping(value = { + "/portalApi/getFavoriteItems" }, method = RequestMethod.GET, produces = "application/json") + public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request, + HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + List<FavoritesFunctionalMenuItemJson> favorites = functionalMenuService.getFavoriteItems(user.getId()); + FieldsValidator fieldsValidator = new FieldsValidator(); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getFavoriteItems", "GET result =", + response.getStatus()); + return favorites; + } + + /** + * RESTful service to delete a favorite menu item for the current user as + * identified in the session. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @param menuId + * menu identifier + * @return FieldsValidator + */ + @RequestMapping(value = { "/portalApi/removeFavoriteItem/{menuId}" }, method = RequestMethod.DELETE) + public FieldsValidator deleteFavoriteItem(HttpServletRequest request, @PathVariable("menuId") Long menuId, + HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + FieldsValidator fieldsValidator = null; + Long userId = user.getId(); + fieldsValidator = functionalMenuService.removeFavoriteItem(userId, menuId); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + EcompPortalUtils.logAndSerializeObject(logger, "/deleteFavoriteItem", "DELETE result =", response.getStatus()); + + return fieldsValidator; + } + + /** + * RESTful service to get user information: user's first and last names, org + * user ID, email and last-login. (Actually has nothing to do with the real + * functional menu.) First attempts to get the information from the Tomcat + * session (i.e., the CSP cookie); if that fails, calls the shared context + * service to read the information from the database. Gives back what it + * found, any of which may be null, as a JSON collection. + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @return JSON collection of key-value pairs shown below. + */ + @RequestMapping(value = { + "/portalApi/functionalMenuStaticInfo" }, method = RequestMethod.GET, produces = "application/json") + public String getFunctionalMenuStaticInfo(HttpServletRequest request, HttpServletResponse response) { + + // Get user details from session + logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuStaticInfo: getting user info"); + String fnMenuStaticResponse = null; + try { + String orgUserIdStr = null, firstNameStr = null, lastNameStr = null, emailStr = null, lastLogin = null; + EPUser user = EPUserUtils.getUserSession(request); + firstNameStr = user.getFirstName(); + lastNameStr = user.getLastName(); + orgUserIdStr = user.getOrgUserId(); + emailStr = user.getEmail(); + if (emailStr == null || emailStr.equals("")) { + EPUser userResult = searchService.searchUserByUserId(orgUserIdStr); + emailStr = userResult.getEmail(); + } + SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ssZ"); + Date lastLoginDate = user.getLastLoginDate(); + if (lastLoginDate == null) { + // should never happen + logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenuStaticInfo: no last login in session"); + lastLogin = "no last login available"; + } else { + lastLogin = sdf.format(lastLoginDate); + } + + // If any item is missing from session, try the Shared Context + // service. + SharedContext orgUserIdSC = null, firstNameSC = null, lastNameSC = null, emailSC = null; + String sessionId = request.getSession().getId(); + if (firstNameStr == null) + firstNameSC = sharedContextService.getSharedContext(sessionId, + EPCommonSystemProperties.USER_FIRST_NAME); + if (lastNameStr == null) + lastNameSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_LAST_NAME); + if (emailStr == null) + emailSC = sharedContextService.getSharedContext(sessionId, EPCommonSystemProperties.USER_EMAIL); + if (orgUserIdStr == null) + orgUserIdSC = sharedContextService.getSharedContext(sessionId, + EPCommonSystemProperties.USER_ORG_USERID); + + // Build the response + Map<String, String> map = new HashMap<String, String>(); + map.put("firstName", + firstNameStr != null ? firstNameStr : (firstNameSC != null ? firstNameSC.getCvalue() : null)); + map.put("lastName", + lastNameStr != null ? lastNameStr : (lastNameSC != null ? lastNameSC.getCvalue() : null)); + map.put("email", emailStr != null ? emailStr : (emailSC != null ? emailSC.getCvalue() : null)); + map.put("userId", + orgUserIdStr != null ? orgUserIdStr : (orgUserIdSC != null ? orgUserIdSC.getCvalue() : null)); + map.put("last_login", lastLogin); + JSONObject j = new JSONObject(map); + fnMenuStaticResponse = j.toString(); + // Be chatty in the log + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/functionalMenuStaticInfo", "GET result =", + fnMenuStaticResponse); + } catch (Exception e) { + // Should never happen. + logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenuStaticInfo failed", e); + // Return a real error? + // fnMenuStaticResponse = "{ \"status\": \"error\", \"message\": \"" + // + e.toString() + "\" }"; + // But the angular controller expects null on error. + } + return fnMenuStaticResponse; + } + + private Comparator<BusinessCardApplicationRole> getUserAppRolesComparator = new Comparator<BusinessCardApplicationRole>() { + public int compare(BusinessCardApplicationRole o1, BusinessCardApplicationRole o2) { + return o1.getAppName().compareTo(o2.getAppName()); + } + }; + + /** + * + * @param request + * HttpServletRequest + * @param userId + * user ID + * @return List<BusinessCardApplicationRolesList> + * @throws IOException + * on error + */ + @RequestMapping(value = { + "/portalApi/userApplicationRoles" }, method = RequestMethod.GET, produces = "application/json") + public List<BusinessCardApplicationRolesList> getAppList(HttpServletRequest request, + @RequestParam("userId") String userId) throws IOException { + + List<BusinessCardApplicationRolesList> AppRoles = null; + try { + List<BusinessCardApplicationRole> userAppRoleList = functionalMenuService.getUserAppRolesList(userId); + + Collections.sort(userAppRoleList, getUserAppRolesComparator); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", + userAppRoleList); + + AppRoles = new ArrayList<BusinessCardApplicationRolesList>(); + for (BusinessCardApplicationRole userAppRole : userAppRoleList) { + boolean found = false; + List<String> roles = null; + + for (BusinessCardApplicationRolesList app : AppRoles) { + if (app.getAppName().equals(userAppRole.getAppName())) { + roles = app.getRoleNames(); + roles.add(userAppRole.getRoleName()); + app.setRoleNames(roles); + found = true; + break; + } + } + + if (!found) { + roles = new ArrayList<String>(); + roles.add(userAppRole.getRoleName()); + AppRoles.add(new BusinessCardApplicationRolesList(userAppRole.getAppName(), roles)); + } + + Collections.sort(roles); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAppList failed", e); + } + + return AppRoles; + + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java index 84731af4..ee5e5eea 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java @@ -41,16 +41,17 @@ import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; import org.openecomp.portalapp.portal.utils.EcompPortalUtils; import com.google.gson.Gson; -/* - * This controller checks the health status and returns JSON response. - * It does not require authentication or session. +/** + * This controller processes requests for the health-check feature implemented + * in the HealthMonitor, which runs in its own thread. These requests do not + * require any authentication nor an active user session. */ @RestController @org.springframework.context.annotation.Configuration @EnableAspectJAutoProxy @EPAuditLog public class HealthCheckController extends EPUnRestrictedBaseController { - + private class HealthStatus { public int statusCode; @SuppressWarnings("unused") @@ -96,8 +97,8 @@ public class HealthCheckController extends EPUnRestrictedBaseController { private final String statusDown = "DOWN"; private final String statusOk = "OK"; - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthCheckController.class); - + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthCheckController.class); + @RequestMapping(value = { "/portalApi/healthCheck" }, method = RequestMethod.GET, produces = "application/json") public HealthStatus healthCheck(HttpServletRequest request, HttpServletResponse response) { HealthStatus healthStatus = new HealthStatus(500, ""); @@ -106,7 +107,8 @@ public class HealthCheckController extends EPUnRestrictedBaseController { if (HealthMonitor.isSuspended) { healthStatus.body = "Suspended"; response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + MDC.put(EPCommonSystemProperties.RESPONSE_CODE, + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); return healthStatus; } @@ -142,28 +144,27 @@ public class HealthCheckController extends EPUnRestrictedBaseController { dbInfo.description = "Check the logs for more details"; EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError); } - + if (!HealthMonitor.isClusterStatusOk()) { dbInfo.dbClusterStatus = "Problem, check the logs for more details"; EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError); - } - else { + } else { dbInfo.dbClusterStatus = statusOk; } - + if (!HealthMonitor.isDatabasePermissionsOk()) { dbInfo.dbPermissions = "Problem, check the logs for more details"; EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError); - } - else { + } else { dbInfo.dbPermissions = statusOk; } statusCollection.add(dbInfo); HealthStatusInfo uebInfo = new HealthStatusInfo("UEB"); if (!HealthMonitor.isUebUp()) { - //As per test case review meeting, UEB is considered as critical as DB. Hence commenting - //overallStatus = false; + // As per test case review meeting, UEB is considered as + // critical as DB. Hence commenting + // overallStatus = false; uebInfo.healthCheckStatus = statusDown; uebInfo.description = "Check the logs for more details"; EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError); @@ -186,12 +187,13 @@ public class HealthCheckController extends EPUnRestrictedBaseController { } MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(healthStatus.statusCode)); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the healthcheck. Details: " - + EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while performing the healthcheck. Details: " + + EcompPortalUtils.getStackTrace(e)); } - + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/healthCheck", "GET result =", response.getStatus()); - + return healthStatus; } @@ -202,10 +204,10 @@ public class HealthCheckController extends EPUnRestrictedBaseController { HealthMonitor.isSuspended = true; healthStatus.statusCode = 200; - + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/healthCheckSuspend", "GET result =", - response.getStatus()); - + response.getStatus()); + return healthStatus; } @@ -217,19 +219,15 @@ public class HealthCheckController extends EPUnRestrictedBaseController { HealthMonitor.isSuspended = false; healthStatus.statusCode = 200; EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/healthCheckResume", "GET result =", - response.getStatus()); + response.getStatus()); return healthStatus; } - - - @RequestMapping(value = { - "/portalApi/ping" }, method = RequestMethod.GET, produces = "application/json") + @RequestMapping(value = { "/portalApi/ping" }, method = RequestMethod.GET, produces = "application/json") public HealthStatus ping(HttpServletRequest request, HttpServletResponse response) { - HealthStatus healthStatus = new HealthStatus(200, "OK"); - EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/ping", "GET result =", - response.getStatus()); - + HealthStatus healthStatus = new HealthStatus(200, "OK"); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/ping", "GET result =", response.getStatus()); + return healthStatus; } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceController.java index 82d70ecd..bc21dd98 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceController.java @@ -1,141 +1,139 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.MicroserviceData;
-import org.openecomp.portalapp.portal.domain.WidgetCatalog;
-import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.ConsulHealthService;
-import org.openecomp.portalapp.portal.service.MicroserviceService;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.core.ParameterizedTypeReference;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.ResponseEntity;
-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.springframework.web.client.RestClientException;
-import org.springframework.web.client.RestTemplate;
-
-@SuppressWarnings("unchecked")
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class MicroserviceController extends EPRestrictedBaseController {
-
- private static final String HTTPS = "https://";
-
- String whatService = "widgets-service";
- RestTemplate template = new RestTemplate();
-
- @Autowired
- private ConsulHealthService consulHealthService;
-
- @Autowired
- private MicroserviceService microserviceService;
-
- @RequestMapping(value = { "/portalApi/microservices" }, method = RequestMethod.POST)
- public PortalRestResponse<String> createMicroservice(HttpServletRequest request, HttpServletResponse response,
- @RequestBody MicroserviceData newServiceData) throws Exception {
- if (newServiceData == null) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
- "MicroserviceData cannot be null or empty");
- }
- long serviceId = microserviceService.saveMicroservice(newServiceData);
-
- try {
- microserviceService.saveServiceParameters(serviceId, newServiceData.getParameterList());
- } catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
- }
-
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
- }
-
- @RequestMapping(value = { "/portalApi/microservices" }, method = RequestMethod.GET)
- public List<MicroserviceData> getMicroservice(HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- List<MicroserviceData> list = microserviceService.getMicroserviceData();
- return list;
- }
-
- @RequestMapping(value = { "/portalApi/microservices/{serviceId}" }, method = RequestMethod.PUT)
- public PortalRestResponse<String> updateMicroservice(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("serviceId") long serviceId, @RequestBody MicroserviceData newServiceData) throws Exception {
-
- if (newServiceData == null) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
- "MicroserviceData cannot be null or empty");
- }
- try {
- microserviceService.updateMicroservice(serviceId, newServiceData);
- } catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
- }
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
- }
-
- @RequestMapping(value = { "/portalApi/microservices/{serviceId}" }, method = RequestMethod.DELETE)
- public PortalRestResponse<String> deleteMicroservice(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("serviceId") long serviceId) throws Exception {
- try {
- ParameterizedTypeReference<List<WidgetCatalog>> typeRef = new ParameterizedTypeReference<List<WidgetCatalog>>() {
- };
- // If this service is assoicated with widgets, cannnot be deleted
- ResponseEntity<List<WidgetCatalog>> ans = (ResponseEntity<List<WidgetCatalog>>) template.exchange(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/service/" + serviceId,
- HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef);
- List<WidgetCatalog> widgets = ans.getBody();
- if(widgets.size() == 0)
- microserviceService.deleteMicroservice(serviceId);
- else{
- StringBuilder sb = new StringBuilder();
- for(int i = 0; i < widgets.size(); i++){
- sb.append("'" + widgets.get(i).getName() + "' ");
- if(i < (widgets.size()-1)){
- sb.append(",");
- }
- }
- return new PortalRestResponse<String>(PortalRestStatusEnum.WARN, "SOME WIDGETS ASSOICATE WITH THIS SERVICE", sb.toString());
- }
- } catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
- }
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.MicroserviceData; +import org.openecomp.portalapp.portal.domain.WidgetCatalog; +import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.ConsulHealthService; +import org.openecomp.portalapp.portal.service.MicroserviceService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +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.springframework.web.client.RestTemplate; + +@SuppressWarnings("unchecked") +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class MicroserviceController extends EPRestrictedBaseController { + + private static final String HTTPS = "https://"; + + String whatService = "widgets-service"; + RestTemplate template = new RestTemplate(); + + @Autowired + private ConsulHealthService consulHealthService; + + @Autowired + private MicroserviceService microserviceService; + + @RequestMapping(value = { "/portalApi/microservices" }, method = RequestMethod.POST) + public PortalRestResponse<String> createMicroservice(HttpServletRequest request, HttpServletResponse response, + @RequestBody MicroserviceData newServiceData) throws Exception { + if (newServiceData == null) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", + "MicroserviceData cannot be null or empty"); + } + long serviceId = microserviceService.saveMicroservice(newServiceData); + + try { + microserviceService.saveServiceParameters(serviceId, newServiceData.getParameterList()); + } catch (Exception e) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); + } + + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); + } + + @RequestMapping(value = { "/portalApi/microservices" }, method = RequestMethod.GET) + public List<MicroserviceData> getMicroservice(HttpServletRequest request, HttpServletResponse response) + throws Exception { + List<MicroserviceData> list = microserviceService.getMicroserviceData(); + return list; + } + + @RequestMapping(value = { "/portalApi/microservices/{serviceId}" }, method = RequestMethod.PUT) + public PortalRestResponse<String> updateMicroservice(HttpServletRequest request, HttpServletResponse response, + @PathVariable("serviceId") long serviceId, @RequestBody MicroserviceData newServiceData) throws Exception { + + if (newServiceData == null) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", + "MicroserviceData cannot be null or empty"); + } + try { + microserviceService.updateMicroservice(serviceId, newServiceData); + } catch (Exception e) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); + } + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); + } + + @RequestMapping(value = { "/portalApi/microservices/{serviceId}" }, method = RequestMethod.DELETE) + public PortalRestResponse<String> deleteMicroservice(HttpServletRequest request, HttpServletResponse response, + @PathVariable("serviceId") long serviceId) throws Exception { + try { + ParameterizedTypeReference<List<WidgetCatalog>> typeRef = new ParameterizedTypeReference<List<WidgetCatalog>>() { + }; + // If this service is assoicated with widgets, cannnot be deleted + ResponseEntity<List<WidgetCatalog>> ans = (ResponseEntity<List<WidgetCatalog>>) template.exchange( + HTTPS + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/widgetCatalog/service/" + serviceId, + HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef); + List<WidgetCatalog> widgets = ans.getBody(); + if(widgets.size() == 0) + microserviceService.deleteMicroservice(serviceId); + else{ + StringBuilder sb = new StringBuilder(); + for(int i = 0; i < widgets.size(); i++){ + sb.append("'" + widgets.get(i).getName() + "' "); + if(i < (widgets.size()-1)){ + sb.append(","); + } + } + return new PortalRestResponse<String>(PortalRestStatusEnum.WARN, "SOME WIDGETS ASSOICATE WITH THIS SERVICE", sb.toString()); + } + } catch (Exception e) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); + } + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceProxyController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceProxyController.java index 6724d4c6..6313822a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceProxyController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/MicroserviceProxyController.java @@ -1,108 +1,98 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.controller.EPUnRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.WidgetParameterResult;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.MicroserviceProxyService;
-import org.openecomp.portalapp.util.EPUserUtils;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.client.HttpClientErrorException;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@SuppressWarnings("unchecked")
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class MicroserviceProxyController extends EPUnRestrictedBaseController {
-
- @Autowired
- private MicroserviceProxyService microserviceProxyService;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyController.class);
-
- @RequestMapping(value = { "/portalApi/microservice/proxy/{serviceId}" }, method = {
- RequestMethod.GET }, produces = "application/json")
- public String getMicroserviceProxy(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("serviceId") long serviceId) throws Exception {
- EPUser user = EPUserUtils.getUserSession(request);
- String answer = "";
- try{
- answer = microserviceProxyService.proxyToDestination(serviceId, user, request);
- }catch(HttpClientErrorException e){
- //Check whether the error message is valid JSON format
- boolean valid = true;
- ObjectMapper objectMapper = new ObjectMapper();
- try{
- objectMapper.readTree(e.getResponseBodyAsString());
- } catch(JsonProcessingException exception){
- valid = false;
- }
- if(valid)
- return e.getResponseBodyAsString();
- else
- return "{\"error\":\""+ e.getResponseBodyAsString() +"\"}";
- }
- return answer;
- }
-
- @RequestMapping(value = { "/portalApi/microservice/proxy/parameter/{widgetId}" }, method = {
- RequestMethod.GET }, produces = "application/json")
- public String getMicroserviceProxyByWidgetId(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws Exception {
- EPUser user = EPUserUtils.getUserSession(request);
- String answer = "";
- try{
- answer = microserviceProxyService.proxyToDestinationByWidgetId(widgetId, user, request);
- }catch(HttpClientErrorException e){
- //Check whether the error message is valid JSON format
- boolean valid = true;
- ObjectMapper objectMapper = new ObjectMapper();
- try{
- objectMapper.readTree(e.getResponseBodyAsString());
- } catch(JsonProcessingException exception){
- valid = false;
- }
- if(valid)
- return e.getResponseBodyAsString();
- else
- return "{\"error\":\""+ e.getResponseBodyAsString() +"\"}";
- }
- return answer;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPUnRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.MicroserviceProxyService; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.HttpClientErrorException; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@SuppressWarnings("unchecked") +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class MicroserviceProxyController extends EPUnRestrictedBaseController { + + @Autowired + private MicroserviceProxyService microserviceProxyService; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyController.class); + + @RequestMapping(value = { "/portalApi/microservice/proxy/{serviceId}" }, method = { + RequestMethod.GET }, produces = "application/json") + public String getMicroserviceProxy(HttpServletRequest request, HttpServletResponse response, + @PathVariable("serviceId") long serviceId) throws Exception { + EPUser user = EPUserUtils.getUserSession(request); + String answer = ""; + try { + answer = microserviceProxyService.proxyToDestination(serviceId, user, request); + } catch (HttpClientErrorException e) { + answer = e.getResponseBodyAsString(); + } + return isValidJSON(answer) ? answer : "{\"error\":\"" + answer.replace(System.getProperty("line.separator"), "") + "\"}"; + } + + @RequestMapping(value = { "/portalApi/microservice/proxy/parameter/{widgetId}" }, method = { + RequestMethod.GET }, produces = "application/json") + public String getMicroserviceProxyByWidgetId(HttpServletRequest request, HttpServletResponse response, + @PathVariable("widgetId") long widgetId) throws Exception { + EPUser user = EPUserUtils.getUserSession(request); + String answer = ""; + try { + answer = microserviceProxyService.proxyToDestinationByWidgetId(widgetId, user, request); + } catch (HttpClientErrorException e) { + answer = e.getResponseBodyAsString(); + } + return isValidJSON(answer) ? answer : "{\"error\":\"" + answer.replace(System.getProperty("line.separator"), "") + "\"}"; + } + + /** + * Check whether the response is a valid JSON + * @param response + * @return true if the response is valid JSON, otherwise, false + */ + private boolean isValidJSON(String response) { + try { + final ObjectMapper mapper = new ObjectMapper(); + mapper.readTree(response); + return true; + } catch (IOException e) { + return false; + } + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java index 2499ec66..b98a7cb4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java @@ -1,200 +1,209 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-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.AuditLog;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.AuditService;
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPRole;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EcompAuditLog;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.service.AdminRolesService;
-import org.openecomp.portalapp.portal.service.PortalAdminService;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.PortalAdmin;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalapp.util.EPUserUtils;
-
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class PortalAdminController extends EPRestrictedBaseController {
- @Autowired
- PortalAdminService portalAdminService;
- @Autowired
- AdminRolesService adminRolesService;
- @Autowired
- AuditService auditService;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminController.class);
-
- @RequestMapping(value = { "/portalApi/portalAdmins" }, method = RequestMethod.GET, produces = "application/json")
- public List<PortalAdmin> getPortalAdmins(HttpServletRequest request, HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- List<PortalAdmin> portalAdmins = null;
- if (user == null) {
- logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, null user");
- EcompPortalUtils.setBadPermissions(user, response, "getPortalAdmins");
- } else if (!adminRolesService.isSuperAdmin(user)) {
- logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, bad permissions");
- EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
- } else {
- // return the list of portal admins
- portalAdmins = portalAdminService.getPortalAdmins();
- logger.debug(EELFLoggerDelegate.debugLogger, "portalAdmins: called getPortalAdmins()");
- EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getPortalAdmins", "result =", portalAdmins);
- }
-
- return portalAdmins;
- }
-
- /**
- * RESTful service method to create a new portal admin. Requirement: you
- * must be the Ecomp portal super admin user.
- */
-
- @RequestMapping(value = { "/portalApi/portalAdmin" }, method = RequestMethod.POST)
- public FieldsValidator createPortalAdmin(HttpServletRequest request, @RequestBody String sbcid,
- HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- FieldsValidator fieldsValidator = null;
- if (user == null) {
- logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin, null user");
- EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
- } else if (!adminRolesService.isSuperAdmin(user)) {
- logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin bad permissions");
- EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
- } else {
- fieldsValidator = portalAdminService.createPortalAdmin(sbcid);
- int statusCode = fieldsValidator.httpStatusCode.intValue();
- response.setStatus(statusCode);
- if (statusCode == 200) {
- AuditLog auditLog = new AuditLog();
- auditLog.setUserId(user.getId());
- auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN);
- auditLog.setAffectedRecordId(sbcid);
- auditService.logActivity(auditLog, null);
-
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- logger.info(EELFLoggerDelegate.auditLogger,
- EPLogUtil.formatAuditLogMessage("PortalAdminController.createPortalAdmin",
- EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN, user.getOrgUserId(), sbcid,
- "A new Portal Admin has been added"));
- MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
- }
- }
- EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "POST result =", response.getStatus());
-
- return fieldsValidator;
- }
-
- @RequestMapping(value = { "/portalApi/portalAdmin/{userInfo}" }, method = RequestMethod.DELETE)
- public FieldsValidator deletePortalAdmin(HttpServletRequest request, @PathVariable("userInfo") String userInfo,
- HttpServletResponse response) {
- int userIdIdx = userInfo.indexOf("-");
- Long userId = null;
- String sbcid = null;
- FieldsValidator fieldsValidator = null;
- try{
- if(userIdIdx==-1){
- logger.error(EELFLoggerDelegate.errorLogger,"deletePortalAdmin missing userId");
- return fieldsValidator;
- }else{
- String userIdStr = userInfo.substring(0, userIdIdx);
- userId = Long.valueOf(userIdStr);
- sbcid = userInfo.substring(userIdIdx+1, userInfo.length());
- }
- }catch(Exception e){
- logger.error(EELFLoggerDelegate.errorLogger,"deletePortalAdmin error while parsing the userInfo",e);
- }
- EPUser user = EPUserUtils.getUserSession(request);
- if (!adminRolesService.isSuperAdmin(user)) {
- EcompPortalUtils.setBadPermissions(user, response, "deletePortalAdmin");
- } else {
- fieldsValidator = portalAdminService.deletePortalAdmin(userId);
- int statusCode = fieldsValidator.httpStatusCode.intValue();
- response.setStatus(statusCode);
- if (statusCode == 200) {
- AuditLog auditLog = new AuditLog();
- auditLog.setUserId(user.getId());
- auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN);
- auditLog.setAffectedRecordId(sbcid);
- auditService.logActivity(auditLog, null);
-
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- logger.info(EELFLoggerDelegate.auditLogger,
- EPLogUtil.formatAuditLogMessage("PortalAdminController.deletePortalAdmin",
- EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN, user.getOrgUserId(), sbcid,
- "A Portal Admin has been deleted"));
- MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
- }
- }
- EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "DELETE result =", response.getStatus());
-
- return fieldsValidator;
- }
-
- @RequestMapping(value = {
- "/portalApi/adminAppsRoles/{appId}" }, method = RequestMethod.GET, produces = "application/json")
- public List<EPRole> getRolesByApp(HttpServletRequest request, @PathVariable("appId") Long appId,
- HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- List<EPRole> rolesByApp = null;
-
- try {
- if (user == null) {
- EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
- } else {
- rolesByApp = adminRolesService.getRolesByApp(user, appId);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while performing getRolesByApp operation, Details: "
- + EcompPortalUtils.getStackTrace(e));
- }
-
- return rolesByApp;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +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.AuditLog; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.AuditService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EcompAuditLog; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.PortalAdminService; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.PortalAdmin; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; + +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class PortalAdminController extends EPRestrictedBaseController { + @Autowired + PortalAdminService portalAdminService; + @Autowired + AdminRolesService adminRolesService; + @Autowired + AuditService auditService; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminController.class); + + @RequestMapping(value = { "/portalApi/portalAdmins" }, method = RequestMethod.GET, produces = "application/json") + public List<PortalAdmin> getPortalAdmins(HttpServletRequest request, HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + List<PortalAdmin> portalAdmins = null; + if (user == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, null user"); + EcompPortalUtils.setBadPermissions(user, response, "getPortalAdmins"); + } else if (!adminRolesService.isSuperAdmin(user)) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, bad permissions"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else { + // return the list of portal admins + portalAdmins = portalAdminService.getPortalAdmins(); + logger.debug(EELFLoggerDelegate.debugLogger, "portalAdmins: called getPortalAdmins()"); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getPortalAdmins", "result =", portalAdmins); + } + + return portalAdmins; + } + + /** + * RESTful service method to create a new portal admin. Requirement: you + * must be the Ecomp portal super admin user. + */ + + @RequestMapping(value = { "/portalApi/portalAdmin" }, method = RequestMethod.POST) + public FieldsValidator createPortalAdmin(HttpServletRequest request, @RequestBody String userId, + HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + FieldsValidator fieldsValidator = null; + if (user == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin, null user"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else if (!adminRolesService.isSuperAdmin(user)) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin bad permissions"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else { + fieldsValidator = portalAdminService.createPortalAdmin(userId); + int statusCode = fieldsValidator.httpStatusCode.intValue(); + response.setStatus(statusCode); + if (statusCode == 200) { + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN); + auditLog.setAffectedRecordId(userId); + auditService.logActivity(auditLog, null); + + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("PortalAdminController.createPortalAdmin", + EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN, user.getOrgUserId(), userId, + "A new Portal Admin has been added")); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } + } + EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "POST result =", response.getStatus()); + + return fieldsValidator; + } + + @RequestMapping(value = { "/portalApi/portalAdmin/{userInfo}" }, method = RequestMethod.DELETE) + public FieldsValidator deletePortalAdmin(HttpServletRequest request, @PathVariable("userInfo") String userInfo, + HttpServletResponse response) { + int userIdIdx = userInfo.indexOf("-"); + Long userId = null; + String sbcid = null; + FieldsValidator fieldsValidator = null; + try { + if (userIdIdx == -1) { + logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin missing userId"); + return fieldsValidator; + } else { + String userIdStr = userInfo.substring(0, userIdIdx); + userId = Long.valueOf(userIdStr); + sbcid = userInfo.substring(userIdIdx + 1, userInfo.length()); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin error while parsing the userInfo", e); + } + EPUser user = EPUserUtils.getUserSession(request); + if (!adminRolesService.isSuperAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "deletePortalAdmin"); + } else { + fieldsValidator = portalAdminService.deletePortalAdmin(userId); + int statusCode = fieldsValidator.httpStatusCode.intValue(); + response.setStatus(statusCode); + if (statusCode == 200) { + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN); + auditLog.setAffectedRecordId(sbcid); + auditService.logActivity(auditLog, null); + + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("PortalAdminController.deletePortalAdmin", + EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN, user.getOrgUserId(), sbcid, + "A Portal Admin has been deleted")); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } + } + EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "DELETE result =", response.getStatus()); + + return fieldsValidator; + } + + @RequestMapping(value = { + "/portalApi/adminAppsRoles/{appId}" }, method = RequestMethod.GET, produces = "application/json") + public List<EPRole> getRolesByApp(HttpServletRequest request, @PathVariable("appId") Long appId, + HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + List<EPRole> rolesByApp = null; + + try { + if (user == null) { + EcompPortalUtils.setBadPermissions(user, response, "getUserApps"); + } else { + rolesByApp = adminRolesService.getRolesByApp(user, appId); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while performing getRolesByApp operation, Details: " + + EcompPortalUtils.getStackTrace(e)); + } + + return rolesByApp; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java index d567269f..2d0fe279 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java @@ -1,166 +1,166 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.controller.core.RoleController;
-import org.openecomp.portalapp.controller.core.RoleFunctionListController;
-import org.openecomp.portalapp.controller.core.RoleListController;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-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.springframework.web.servlet.ModelAndView;
-
-/**
- * Proxies REST calls to role-management functions that arrive on paths
- * /portalApi/* over to controller methods provided by the SDK-Core library.
- * Those controller methods are mounted on paths not exposed by the Portal FE.
- */
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class RoleManageController extends EPRestrictedBaseController {
-
- @Autowired
- private RoleController roleController;
-
- @Autowired
- private RoleListController roleListController;
-
- @Autowired
- private RoleFunctionListController roleFunctionListController;
-
- /**
- * Calls an SDK-Core library method that gets the available roles and writes
- * them to the request object. Portal specifies a Hibernate mappings from
- * the Role class to the fn_role_v view, which ensures that only Portal
- * (app_id is null) roles are fetched.
- *
- * Any method declared void (no return value) or returning null causes the
- * audit log aspect method to declare failure. TODO: should return a JSON
- * string.
- *
- * @param request
- * @param response
- */
- @RequestMapping(value = { "/portalApi/get_roles" }, method = RequestMethod.GET)
- public void getRoles(HttpServletRequest request, HttpServletResponse response) {
- getRoleListController().getRoles(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role_list/toggleRole" }, method = RequestMethod.POST)
- public PortalRestResponse<String> toggleRole(HttpServletRequest request, HttpServletResponse response) {
- PortalRestResponse<String> portalRestResponse = null;
- try{
- getRoleListController().toggleRole(request, response);
- portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", null);
- }catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "failure", e.getMessage());
- }
- return portalRestResponse;
- }
-
- @RequestMapping(value = { "/portalApi/role_list/removeRole" }, method = RequestMethod.POST)
- public ModelAndView removeRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
- return getRoleListController().removeRole(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role/saveRole" }, method = RequestMethod.POST)
- public ModelAndView saveRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
- return getRoleController().saveRole(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role/removeRoleFunction" }, method = RequestMethod.POST)
- public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- return getRoleController().removeRoleFunction(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role/addRoleFunction" }, method = RequestMethod.POST)
- public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- return getRoleController().addRoleFunction(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role/removeChildRole" }, method = RequestMethod.POST)
- public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
- return getRoleController().removeChildRole(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role/addChildRole" }, method = RequestMethod.POST)
- public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
- return getRoleController().addChildRole(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/get_role" }, method = RequestMethod.GET)
- public void getRole(HttpServletRequest request, HttpServletResponse response) {
- getRoleController().getRole(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/get_role_functions" }, method = RequestMethod.GET)
- public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response) {
- getRoleFunctionListController().getRoleFunctionList(request, response);
- }
-
- @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction" }, method = RequestMethod.POST)
- public void saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody String roleFunc) throws Exception {
- getRoleFunctionListController().saveRoleFunction(request, response, roleFunc);
- }
-
- @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction" }, method = RequestMethod.POST)
- public void removeRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody String roleFunc) throws Exception {
- getRoleFunctionListController().removeRoleFunction(request, response, roleFunc);
- }
-
- public RoleListController getRoleListController() {
- return roleListController;
- }
-
- public void setRoleListController(RoleListController roleListController) {
- this.roleListController = roleListController;
- }
-
- public RoleController getRoleController() {
- return roleController;
- }
-
- public void setRoleController(RoleController roleController) {
- this.roleController = roleController;
- }
-
- public RoleFunctionListController getRoleFunctionListController() {
- return roleFunctionListController;
- }
-
- public void setRoleFunctionListController(RoleFunctionListController roleFunctionListController) {
- this.roleFunctionListController = roleFunctionListController;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.controller.core.RoleController; +import org.openecomp.portalapp.controller.core.RoleFunctionListController; +import org.openecomp.portalapp.controller.core.RoleListController; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +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.springframework.web.servlet.ModelAndView; + +/** + * Proxies REST calls to role-management functions that arrive on paths + * /portalApi/* over to controller methods provided by the SDK-Core library. + * Those controller methods are mounted on paths not exposed by the Portal FE. + */ +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class RoleManageController extends EPRestrictedBaseController { + + @Autowired + private RoleController roleController; + + @Autowired + private RoleListController roleListController; + + @Autowired + private RoleFunctionListController roleFunctionListController; + + /** + * Calls an SDK-Core library method that gets the available roles and writes + * them to the request object. Portal specifies a Hibernate mappings from + * the Role class to the fn_role_v view, which ensures that only Portal + * (app_id is null) roles are fetched. + * + * Any method declared void (no return value) or returning null causes the + * audit log aspect method to declare failure. TODO: should return a JSON + * string. + * + * @param request + * @param response + */ + @RequestMapping(value = { "/portalApi/get_roles" }, method = RequestMethod.GET) + public void getRoles(HttpServletRequest request, HttpServletResponse response) { + getRoleListController().getRoles(request, response); + } + + @RequestMapping(value = { "/portalApi/role_list/toggleRole" }, method = RequestMethod.POST) + public PortalRestResponse<String> toggleRole(HttpServletRequest request, HttpServletResponse response) { + PortalRestResponse<String> portalRestResponse = null; + try{ + getRoleListController().toggleRole(request, response); + portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", null); + }catch (Exception e) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "failure", e.getMessage()); + } + return portalRestResponse; + } + + @RequestMapping(value = { "/portalApi/role_list/removeRole" }, method = RequestMethod.POST) + public ModelAndView removeRole(HttpServletRequest request, HttpServletResponse response) throws Exception { + return getRoleListController().removeRole(request, response); + } + + @RequestMapping(value = { "/portalApi/role/saveRole" }, method = RequestMethod.POST) + public ModelAndView saveRole(HttpServletRequest request, HttpServletResponse response) throws Exception { + return getRoleController().saveRole(request, response); + } + + @RequestMapping(value = { "/portalApi/role/removeRoleFunction" }, method = RequestMethod.POST) + public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return getRoleController().removeRoleFunction(request, response); + } + + @RequestMapping(value = { "/portalApi/role/addRoleFunction" }, method = RequestMethod.POST) + public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return getRoleController().addRoleFunction(request, response); + } + + @RequestMapping(value = { "/portalApi/role/removeChildRole" }, method = RequestMethod.POST) + public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception { + return getRoleController().removeChildRole(request, response); + } + + @RequestMapping(value = { "/portalApi/role/addChildRole" }, method = RequestMethod.POST) + public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception { + return getRoleController().addChildRole(request, response); + } + + @RequestMapping(value = { "/portalApi/get_role" }, method = RequestMethod.GET) + public void getRole(HttpServletRequest request, HttpServletResponse response) { + getRoleController().getRole(request, response); + } + + @RequestMapping(value = { "/portalApi/get_role_functions" }, method = RequestMethod.GET) + public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response) { + getRoleFunctionListController().getRoleFunctionList(request, response); + } + + @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction" }, method = RequestMethod.POST) + public void saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody String roleFunc) throws Exception { + getRoleFunctionListController().saveRoleFunction(request, response, roleFunc); + } + + @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction" }, method = RequestMethod.POST) + public void removeRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody String roleFunc) throws Exception { + getRoleFunctionListController().removeRoleFunction(request, response, roleFunc); + } + + public RoleListController getRoleListController() { + return roleListController; + } + + public void setRoleListController(RoleListController roleListController) { + this.roleListController = roleListController; + } + + public RoleController getRoleController() { + return roleController; + } + + public void setRoleController(RoleController roleController) { + this.roleController = roleController; + } + + public RoleFunctionListController getRoleFunctionListController() { + return roleFunctionListController; + } + + public void setRoleFunctionListController(RoleFunctionListController roleFunctionListController) { + this.roleFunctionListController = roleFunctionListController; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/externalsystemapproval/controller/RolesApprovalSystemController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemController.java index e0fa523a..c150528e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/externalsystemapproval/controller/RolesApprovalSystemController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemController.java @@ -1,143 +1,199 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.externalsystemapproval.controller;
-
-import java.util.ArrayList;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval;
-import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser;
-import org.openecomp.portalapp.portal.controller.BasicAuthenticationController;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.UserRolesService;
-import org.openecomp.portalapp.portal.utils.PortalConstants;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-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 io.swagger.annotations.ApiOperation;
-
-@RestController
-@RequestMapping(PortalConstants.REST_AUX_API)
-@Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class RolesApprovalSystemController implements BasicAuthenticationController {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RolesApprovalSystemController.class);
-
- @Autowired
- private UserRolesService userRolesService;
-
- /**
- * Creates an application user with the specified roles.
- *
- * @param request
- * @param extSysUser
- * @return PortalRestResponse with appropriate status value and message
- */
- @ApiOperation(value = "Creates an application user with the specified roles.", response = PortalRestResponse.class)
- @RequestMapping(value = { "/userProfile" }, method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> postUserProfile(HttpServletRequest request,
- @RequestBody ExternalSystemUser extSysUser) {
- try {
- validateExtSystemUser(extSysUser, true);
- String response = userRolesService.setAppWithUserRoleStateForUser(extSysUser);
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Saved Successfully", response);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "postUserProfile failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
- /**
- * Updates an application user to have only the specified roles.
- *
- * @param request
- * @param extSysUser
- * @return PortalRestResponse with appropriate status value and message
- */
- @ApiOperation(value = "Updates an application user to have only the specified roles.", response = PortalRestResponse.class)
- @RequestMapping(value = { "/userProfile" }, method = RequestMethod.PUT, produces = "application/json")
- public PortalRestResponse<String> putUserProfile(HttpServletRequest request,
- @RequestBody ExternalSystemUser extSysUser) {
- try {
- validateExtSystemUser(extSysUser, true);
- String response = userRolesService.setAppWithUserRoleStateForUser(extSysUser);
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Updated Successfully", response);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "putUserProfile failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
- /**
- * Deletes an application user by removing all assigned roles.
- *
- * @param request
- * @param extSysUser
- * This object must have zero roles.
- * @return PortalRestResponse with appropriate status value and message
- */
- @ApiOperation(value = "Processes a request to delete one or more application roles for one specified user who has roles.", response = PortalRestResponse.class)
- @RequestMapping(value = { "/userProfile" }, method = RequestMethod.DELETE, produces = "application/json")
- public PortalRestResponse<String> deleteUserProfile(HttpServletRequest request,
- @RequestBody ExternalSystemUser extSysUser) {
- try {
- validateExtSystemUser(extSysUser, false);
- // Ignore any roles that might be mistakenly present in the request
- extSysUser.setRoles(new ArrayList<ExternalSystemRoleApproval>());
- String result = userRolesService.setAppWithUserRoleStateForUser(extSysUser);
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Deleted Successfully", result);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteUserProfile failed", e);
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
- /**
- * Checks for presence of required fields.
- *
- * @param extSysUser
- * @param rolesRequired
- * If true, checks whether roles are present
- * @throws Exception
- * If any field is missing.
- */
- private void validateExtSystemUser(ExternalSystemUser extSysUser, boolean rolesRequired) throws Exception {
- if (extSysUser.getLoginId() == null)
- throw new Exception("Request has no login ID");
- if (extSysUser.getApplicationName() == null)
- throw new Exception("Request has no application name");
- if (extSysUser.getMyloginrequestId() == null)
- throw new Exception("Request has no request ID");
- if (rolesRequired && (extSysUser.getRoles() == null || extSysUser.getRoles().size() == 0))
- throw new Exception("Request has no roles");
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ + +package org.openecomp.portalapp.portal.controller; + +import java.util.ArrayList; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval; +import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.UserRolesService; +import org.openecomp.portalapp.portal.transport.ExternalRequestFieldsValidator; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +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 io.swagger.annotations.ApiOperation; + +@RestController +@RequestMapping("/auxapi") +@Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class RolesApprovalSystemController implements BasicAuthenticationController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RolesApprovalSystemController.class); + + @Autowired + private UserRolesService userRolesService; + + /** + * Creates an application user with the specified roles. + * + * @param request + * @param extSysUser + * @return PortalRestResponse with appropriate status value and message + */ + @ApiOperation(value = "Creates an application user with the specified roles.", response = PortalRestResponse.class) + @RequestMapping(value = { "/userProfile" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse<String> postUserProfile(HttpServletRequest request, + @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) { + ExternalRequestFieldsValidator reqResult = null; + try { + logger.info(EELFLoggerDelegate.debugLogger, "postUserProfile: request received for app {}, user {}", + extSysUser.getApplicationName(), extSysUser.getLoginId()); + + validateExtSystemUser(extSysUser, true); + reqResult = userRolesService.setExternalRequestUserAppRole(extSysUser, "POST"); + if (!reqResult.isResult()) + throw new Exception(reqResult.getDetailMessage()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "postUserProfile: failed for app {}, user {}", + extSysUser.getApplicationName(), extSysUser.getLoginId(), e); + if(reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404"))){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + e.getMessage(), "save user profile failed"); + } else if(e.getMessage().contains("404")){ + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + e.getMessage(), "save user profile failed"); + } else{ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + e.getMessage(), "save user profile failed"); + } + } + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, reqResult.getDetailMessage(), "Success"); + } + + /** + * Updates an application user to have only the specified roles. + * + * @param request + * @param extSysUser + * @return PortalRestResponse with appropriate status value and message + */ + @ApiOperation(value = "Updates an application user to have only the specified roles.", response = PortalRestResponse.class) + @RequestMapping(value = { "/userProfile" }, method = RequestMethod.PUT, produces = "application/json") + public PortalRestResponse<String> putUserProfile(HttpServletRequest request, + @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) { + ExternalRequestFieldsValidator reqResult = null; + try { + logger.info(EELFLoggerDelegate.debugLogger, "putUserProfile: request received for app {}, user {}", + extSysUser.getApplicationName(), extSysUser.getLoginId()); + validateExtSystemUser(extSysUser, true); + reqResult = userRolesService.setExternalRequestUserAppRole(extSysUser, "PUT"); + if (!reqResult.isResult()) + throw new Exception(reqResult.getDetailMessage()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "putUserProfile: failed for app {}, user {}", + extSysUser.getApplicationName(), extSysUser.getLoginId(), e); + if(reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404"))){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + e.getMessage(), "save user profile failed"); + } else if(e.getMessage().contains("404")){ + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + e.getMessage(), "save user profile failed"); + } else{ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + e.getMessage(), "save user profile failed"); + } + } + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, reqResult.getDetailMessage() , "Success"); + } + + /** + * Deletes an application user by removing all assigned roles. + * + * @param request + * @param extSysUser + * This object must have zero roles. + * @return PortalRestResponse with appropriate status value and message + */ + @ApiOperation(value = "Processes a request to delete one or more application roles for one specified user who has roles.", response = PortalRestResponse.class) + @RequestMapping(value = { "/userProfile" }, method = RequestMethod.DELETE, produces = "application/json") + public PortalRestResponse<String> deleteUserProfile(HttpServletRequest request, + @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) { + ExternalRequestFieldsValidator reqResult = null; + try { + logger.info(EELFLoggerDelegate.debugLogger, "deleteUserProfile: request received for app {}, user {}", + extSysUser.getApplicationName(), extSysUser.getLoginId()); + validateExtSystemUser(extSysUser, false); + // Ignore any roles that might be mistakenly present in the request + extSysUser.setRoles(new ArrayList<ExternalSystemRoleApproval>()); + reqResult = userRolesService.setExternalRequestUserAppRole(extSysUser, "DELETE"); + if (!reqResult.isResult()) + throw new Exception(reqResult.getDetailMessage()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteUserProfile: failed for app {}, user {}", + extSysUser.getApplicationName(), extSysUser.getLoginId(), e); + if(reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404"))){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + e.getMessage(), "delete user profile failed"); + }else if(e.getMessage().contains("404")){ + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + e.getMessage(), "delete user profile failed"); + } else{ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + e.getMessage(), "delete user profile failed"); + } + } + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Deleted Successfully", "Success"); + } + + /** + * Checks for presence of required fields. + * + * @param extSysUser + * @param rolesRequired + * If true, checks whether roles are present + * @throws Exception + * If any field is missing. + */ + private void validateExtSystemUser(ExternalSystemUser extSysUser, boolean rolesRequired) throws Exception { + if (extSysUser.getLoginId() == null || extSysUser.getLoginId() == "") + throw new Exception("Request has no login ID"); + if (extSysUser.getApplicationName() == null || extSysUser.getApplicationName() == "") + throw new Exception("Request has no application name"); + if (extSysUser.getMyloginrequestId() == null) + throw new Exception("Request has no request ID"); + if (rolesRequired && (extSysUser.getRoles() == null || extSysUser.getRoles().size() == 0)) + throw new Exception("Request has no roles"); + } + +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java index a59a4579..984bbf75 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java @@ -69,12 +69,12 @@ import io.swagger.annotations.ApiOperation; public class SharedContextRestController extends EPRestrictedRESTfulBaseController { /** - * Model for a one-element JSON object returned by many methods. + * Model for a one-element JSON object returned by many methods. */ class SharedContextJsonResponse { String response; } - + /** * Access to the database */ @@ -94,12 +94,16 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll /** * Gets a value for the specified context and key (RESTful service method). * - * @param ctxtId + * @param request + * HTTP servlet request + * @param context_id * ID that identifies the context, usually the ECOMP Portal * session key. * @param ckey * Key for the key-value pair to fetch * @return JSON with shared context object; response=null if not found. + * @throws Exception + * on bad arguments */ @ApiOperation(value = "Gets a value for the specified context and key.", response = SharedContext.class) @RequestMapping(value = { "/get" }, method = RequestMethod.GET, produces = "application/json") @@ -123,12 +127,15 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll /** * Gets user information for the specified context (RESTful service method). * - * @param ctxtId + * @param request + * HTTP servlet request + * @param context_id * ID that identifies the context, usually the ECOMP Portal * session key. - * * @return List of shared-context objects as JSON; should have user's first * name, last name and email address; null if none found + * @throws Exception + * on bad arguments */ @ApiOperation(value = "Gets user information for the specified context.", response = SharedContext.class, responseContainer = "List") @RequestMapping(value = { "/get_user" }, method = RequestMethod.GET, produces = "application/json") @@ -162,6 +169,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll * Tests for presence of the specified key in the specified context (RESTful * service method). * + * @param request + * HTTP servlet request * @param context_id * ID that identifies the context, usually the ECOMP Portal * session key. @@ -169,6 +178,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll * Key for the key-value pair to test * @return JSON with result indicating whether the context and key were * found. + * @throws Exception + * on bad arguments */ @ApiOperation(value = "Tests for presence of the specified key in the specified context.", response = SharedContextJsonResponse.class) @RequestMapping(value = { "/check" }, method = RequestMethod.GET, produces = "application/json") @@ -192,6 +203,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll * Removes the specified key in the specified context (RESTful service * method). * + * @param request + * HTTP servlet request * @param context_id * ID that identifies the context, usually the ECOMP Portal * session key. @@ -199,6 +212,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll * Key for the key-value pair to remove * @return JSON with result indicating whether the context and key were * found. + * @throws Exception + * on bad arguments */ @ApiOperation(value = "Removes the specified key in the specified context.", response = SharedContextJsonResponse.class) @RequestMapping(value = { "/remove" }, method = RequestMethod.GET, produces = "application/json") @@ -224,11 +239,15 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll * Clears all key-value pairs in the specified context (RESTful service * method). * + * @param request + * HTTP servlet request * @param context_id * ID that identifies the context, usually the ECOMP Portal * session key. * @return JSON with result indicating the number of key-value pairs * removed. + * @throws Exception + * on bad arguments */ @ApiOperation(value = "Clears all key-value pairs in the specified context.", response = SharedContextJsonResponse.class) @RequestMapping(value = { "/clear" }, method = RequestMethod.GET, produces = "application/json") @@ -248,6 +267,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll * method). Creates the context if no context with the specified ID-key pair * exists, overwrites the value if it exists already. * + * @param request + * HTTP servlet request * @param userJson * JSON block with these tag-value pairs: * <UL> @@ -257,6 +278,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll * </UL> * @return JSON with result indicating whether the value was added (key not * previously known) or replaced (key previously known). + * @throws Exception + * on bad arguments */ @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.", response = SharedContextJsonResponse.class) @RequestMapping(value = { "/set" }, method = RequestMethod.POST, produces = "application/json") @@ -314,7 +337,7 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll /** * Creates a JSON object with the content of the shared context; null is ok. * - * @param responseBody + * @param context * @return tag "response" with collection of context object's fields * @throws JsonProcessingException */ diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java index 0dd344d7..e0a9e587 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java @@ -1,179 +1,184 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.UserNotificationService;
-import org.openecomp.portalapp.portal.transport.EpNotificationItem;
-import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem;
-import org.openecomp.portalapp.portal.utils.PortalConstants;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-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 com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import io.swagger.annotations.ApiOperation;
-
-/**
- * Receives messages from the Collaboration Bus (C-BUS) notification and event
- * brokering tool. Creates notifications for ECOMP Portal users.
- */
-@RestController
-@RequestMapping(PortalConstants.REST_AUX_API)
-@Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class TicketEventController implements BasicAuthenticationController {
-
- @Autowired
- private UserNotificationService userNotificationService;
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TicketEventController.class);
-
- public boolean isAuxRESTfulCall() {
- return true;
- }
-
- private final ObjectMapper mapper = new ObjectMapper();
-
- @ApiOperation(value = "Accepts messages from external ticketing systems and creates notifications for Portal users.", response = PortalRestResponse.class)
- @RequestMapping(value = { "/ticketevent" }, method = RequestMethod.POST)
- public PortalRestResponse<String> handleRequest(HttpServletRequest request, HttpServletResponse response,
- @RequestBody String ticketEventJson) throws Exception {
-
- logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson);
- PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
- try {
- JsonNode ticketEventNotif = mapper.readTree(ticketEventJson);
-
- // Reject request if required fields are missing.
- String error = validateTicketEventMessage(ticketEventNotif);
- if (error != null) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- portalResponse.setMessage(error);
- response.setStatus(400);
- return portalResponse;
- }
-
- EpNotificationItem epItem = new EpNotificationItem();
- epItem.setCreatedDate(new Date());
- epItem.setIsForOnlineUsers("Y");
- epItem.setIsForAllRoles("N");
- epItem.setActiveYn("Y");
- //JsonNode application = ticketEventNotif.get("application");
- JsonNode event = ticketEventNotif.get("event");
- JsonNode header = event.get("header");
- JsonNode body = event.get("body");
- epItem.setMsgDescription(body.toString());
- Long eventDate = body.get("eventDate").asLong();
-
- String assetID = body.get("assetID").asText();
- epItem.setMsgHeader(assetID);
- String eventSource = header.get("eventSource").asText();
- epItem.setMsgSource(eventSource);
- epItem.setStartTime(new Date(eventDate));
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(epItem.getStartTime());
- int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
- calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth + 30);
- epItem.setEndTime(calendar.getTime());
- String severityString= (body.get("severity").toString()).substring(1, 2);
- Long severity=Long.parseLong(severityString);
- epItem.setPriority(severity);
- epItem.setCreatorId(null);
- Set<EpRoleNotificationItem> roles = new HashSet<>();
- JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
- JsonNode userList = SubscriberInfo.get("UserList");
- String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "")
- .split(",");
- List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds));
- for (String userId : UserIds) {
- EpRoleNotificationItem roleNotifItem = new EpRoleNotificationItem();
- for (EPUser user : users) {
- if (user.getOrgUserId().equals(userId)) {
- roleNotifItem.setRecvUserId(user.getId().intValue());
- roles.add(roleNotifItem);
- break;
- }
- }
-
- }
- epItem.setRoles(roles);
- userNotificationService.saveNotification(epItem);
-
- portalResponse.setStatus(PortalRestStatusEnum.OK);
- portalResponse.setMessage("processEventNotification: notification created");
- portalResponse.setResponse("NotificationId is :" + epItem.notificationId);
- } catch (Exception ex) {
- portalResponse.setStatus(PortalRestStatusEnum.ERROR);
- response.setStatus(400);
- portalResponse.setMessage(ex.toString());
- }
- return portalResponse;
- }
-
- /**
- * Validates that mandatory fields are present.
- *
- * @param ticketEventNotif
- * @return Error message if a problem is found; null if all is well.
- */
- private String validateTicketEventMessage(JsonNode ticketEventNotif) {
- JsonNode application = ticketEventNotif.get("application");
- JsonNode event = ticketEventNotif.get("event");
- JsonNode header = event.get("header");
- JsonNode body = event.get("body");
- JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo");
- if (application == null)
- return "application is mandatory";
- if (body == null)
- return "body is mandatory";
- if (body.get("assetID") == null)
- return "Asset Id is mandatory";
- if (body.get("eventDate") == null)
- return "Event Date is mandatory";
- if (header.get("eventSource") == null)
- return "Message Source is mandatory";
- if (SubscriberInfo.get("UserList") == null)
- return "At least one user Id is mandatory";
- return null;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.UserNotificationService; +import org.openecomp.portalapp.portal.transport.EpNotificationItem; +import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +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 com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.swagger.annotations.ApiOperation; + +/** + * Receives messages from the Collaboration Bus (C-BUS) notification and event + * brokering tool. Creates notifications for ECOMP Portal users. + */ +@RestController +@RequestMapping(PortalConstants.REST_AUX_API) +@Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class TicketEventController implements BasicAuthenticationController { + + @Autowired + private UserNotificationService userNotificationService; + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TicketEventController.class); + + public boolean isAuxRESTfulCall() { + return true; + } + + private final ObjectMapper mapper = new ObjectMapper(); + + @ApiOperation(value = "Accepts messages from external ticketing systems and creates notifications for Portal users.", response = PortalRestResponse.class) + @RequestMapping(value = { "/ticketevent" }, method = RequestMethod.POST) + public PortalRestResponse<String> handleRequest(HttpServletRequest request, HttpServletResponse response, + @RequestBody String ticketEventJson) throws Exception { + + logger.debug(EELFLoggerDelegate.debugLogger, "Ticket Event notification" + ticketEventJson); + PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); + try { + JsonNode ticketEventNotif = mapper.readTree(ticketEventJson); + + // Reject request if required fields are missing. + String error = validateTicketEventMessage(ticketEventNotif); + if (error != null) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage(error); + response.setStatus(400); + return portalResponse; + } + + EpNotificationItem epItem = new EpNotificationItem(); + epItem.setCreatedDate(new Date()); + epItem.setIsForOnlineUsers("Y"); + epItem.setIsForAllRoles("N"); + epItem.setActiveYn("Y"); + + JsonNode event = ticketEventNotif.get("event"); + JsonNode header = event.get("header"); + JsonNode body = event.get("body"); + epItem.setMsgDescription(body.toString()); + Long eventDate = System.currentTimeMillis(); + if (body.get("eventDate") != null) { + eventDate = body.get("eventDate").asLong(); + } + String eventSource = header.get("eventSource").asText(); + epItem.setMsgSource(eventSource); + epItem.setStartTime(new Date(eventDate)); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(epItem.getStartTime()); + int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); + calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth + 30); + epItem.setEndTime(calendar.getTime()); + String severityString = "1"; + if (body.get("severity") != null) { + severityString = (body.get("severity").toString()).substring(1, 2); + } + Long severity = Long.parseLong(severityString); + epItem.setPriority(severity); + epItem.setCreatorId(null); + Set<EpRoleNotificationItem> roles = new HashSet<>(); + JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo"); + JsonNode userList = SubscriberInfo.get("UserList"); + String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "") + .split(","); + String assetID = eventSource + ' ' + + userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "") + ' ' + + new Date(eventDate); + if (body.get("assetID") != null) { + assetID = body.get("assetID").asText(); + } + epItem.setMsgHeader(assetID); + List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds)); + for (String userId : UserIds) { + EpRoleNotificationItem roleNotifItem = new EpRoleNotificationItem(); + for (EPUser user : users) { + if (user.getOrgUserId().equals(userId)) { + roleNotifItem.setRecvUserId(user.getId().intValue()); + roles.add(roleNotifItem); + break; + } + } + + } + epItem.setRoles(roles); + userNotificationService.saveNotification(epItem); + + portalResponse.setStatus(PortalRestStatusEnum.OK); + portalResponse.setMessage("processEventNotification: notification created"); + portalResponse.setResponse("NotificationId is :" + epItem.notificationId); + } catch (Exception ex) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + response.setStatus(400); + portalResponse.setMessage(ex.toString()); + } + return portalResponse; + } + + /** + * Validates that mandatory fields are present. + * + * @param ticketEventNotif + * @return Error message if a problem is found; null if all is well. + */ + private String validateTicketEventMessage(JsonNode ticketEventNotif) { + JsonNode application = ticketEventNotif.get("application"); + JsonNode event = ticketEventNotif.get("event"); + JsonNode header = event.get("header"); + JsonNode body = event.get("body"); + JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo"); + if (application == null) + return "application is mandatory"; + if (body == null) + return "body is mandatory"; + if (header.get("eventSource") == null) + return "Message Source is mandatory"; + if (SubscriberInfo.get("UserList") == null) + return "At least one user Id is mandatory"; + return null; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserController.java new file mode 100644 index 00000000..4cf7ca63 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserController.java @@ -0,0 +1,104 @@ +package org.openecomp.portalapp.portal.controller; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.UserService; +import org.openecomp.portalapp.portal.transport.ProfileDetail; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +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; + +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class UserController extends EPRestrictedBaseController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserController.class); + + @Autowired + private UserService userService; + + /** + * RESTful service method to get ECOMP Logged in User details. + * + * @param request + * HttpServletRequest + * + * @return PortalRestResponse of EPUser + */ + @RequestMapping(value = { "/portalApi/loggedinUser" }, method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<ProfileDetail> getLoggedinUser(HttpServletRequest request) { + PortalRestResponse<ProfileDetail> portalRestResponse = null; + try { + EPUser user = EPUserUtils.getUserSession(request); + ProfileDetail profileDetail = new ProfileDetail(user.getFirstName(), user.getLastName(), + user.getMiddleInitial(), user.getEmail(), user.getLoginId(), CipherUtil.decrypt(user.getLoginPwd())); + portalRestResponse = new PortalRestResponse<ProfileDetail>(PortalRestStatusEnum.OK, "success", + profileDetail); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/loggedinUser", "result =", profileDetail); + } catch (Exception e) { + portalRestResponse = new PortalRestResponse<ProfileDetail>(PortalRestStatusEnum.ERROR, e.getMessage(), + null); + logger.error(EELFLoggerDelegate.errorLogger, "getLoggedinUser failed", e); + } + return portalRestResponse; + } + + /** + * RESTful service method to update ECOMP Logged in User in DB. + * + * @param request + * HttpServletRequest + * @param profileDetail + * Body with user information + * @return PortalRestResponse of String + */ + @RequestMapping(value = { + "/portalApi/modifyLoggedinUser" }, method = RequestMethod.PUT, produces = "application/json") + public PortalRestResponse<String> modifyLoggedinUser(HttpServletRequest request, + @RequestBody ProfileDetail profileDetail) { + PortalRestResponse<String> portalRestResponse = null; + try { + String errorMsg = ""; + if (profileDetail.getFirstName().equals("") || profileDetail.getLastName().equals("") + || profileDetail.getEmail().equals("") || profileDetail.getLoginId().equals("") + || profileDetail.getLoginPassword().equals("")) { + errorMsg = "Required field(s) is missing"; + portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, errorMsg, null); + logger.error(EELFLoggerDelegate.errorLogger, "modifyLoggedinUser failed", errorMsg); + } else { + EPUser user = EPUserUtils.getUserSession(request); + user.setFirstName(profileDetail.getFirstName()); + user.setLastName(profileDetail.getLastName()); + user.setEmail(profileDetail.getEmail()); + user.setMiddleInitial(profileDetail.getMiddleName()); + user.setLoginId(profileDetail.getLoginId()); + user.setLoginPwd(CipherUtil.encrypt(profileDetail.getLoginPassword())); + userService.saveUser(user); + // Update user info in the session + request.getSession().setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), + user); + portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", null); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/modifyLoggedinUser", "result =", user); + } + } catch (Exception e) { + portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.toString(), null); + logger.error(EELFLoggerDelegate.errorLogger, "modifyLoggedinUser failed", e); + } + return portalRestResponse; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserNotificationController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserNotificationController.java index 777fb91d..24b698e8 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserNotificationController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserNotificationController.java @@ -1,216 +1,217 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-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.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-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.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EcompAppRole;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.FunctionalMenuService;
-import org.openecomp.portalapp.portal.service.UserNotificationService;
-import org.openecomp.portalapp.portal.transport.EpNotificationItem;
-import org.openecomp.portalapp.portal.transport.EpNotificationItemVO;
-import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuRole;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.util.EPUserUtils;
-
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class UserNotificationController extends EPRestrictedBaseController {
-
- @Autowired
- FunctionalMenuService functionalMenuService;
-
- @Autowired
- UserNotificationService userNotificationService;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserNotificationController.class);
-
- @RequestMapping(value = {
- "/portalApi/getFunctionalMenuRole" }, method = RequestMethod.GET, produces = "application/json")
- public List<FunctionalMenuRole> getMenuIdRoleId(HttpServletRequest request, HttpServletResponse response) {
- // EPUser user = EPUserUtils.getUserSession(request);
- List<FunctionalMenuRole> menuRoleList = null;
- menuRoleList = functionalMenuService.getFunctionalMenuRole();
- return menuRoleList;
- }
-
- @RequestMapping(value = {
- "/portalApi/getNotifications" }, method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<List<EpNotificationItem>> getNotifications(HttpServletRequest request,
- HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- PortalRestResponse<List<EpNotificationItem>> portalRestResponse = null;
- try {
- List<EpNotificationItem> notificationList = userNotificationService.getNotifications(user.getId());
- portalRestResponse = new PortalRestResponse<List<EpNotificationItem>>(PortalRestStatusEnum.OK, "success",
- notificationList);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getAllAppsAndContacts failed", e);
- portalRestResponse = new PortalRestResponse<List<EpNotificationItem>>(PortalRestStatusEnum.ERROR,
- e.getMessage(), null);
- }
- return portalRestResponse;
- }
-
- @RequestMapping(value = {
- "/portalApi/getAdminNotifications" }, method = RequestMethod.GET, produces = "application/json")
- public List<EpNotificationItemVO> getAdminNotifications(HttpServletRequest request, HttpServletResponse response) {
- List<EpNotificationItemVO> adminNotificationList = null;
- adminNotificationList = userNotificationService.getAdminNotificationVOS();
- return adminNotificationList;
- }
-
- @RequestMapping(value = "/portalApi/saveNotification", method = RequestMethod.POST, produces = "application/json")
- public PortalRestResponse<String> save(HttpServletRequest request, HttpServletResponse response,
- @RequestBody EpNotificationItem notificationItem) {
-
- if (notificationItem == null || notificationItem.getMsgHeader() == null)
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
- "Notification Header cannot be null or empty");
- if (notificationItem.getEndTime().compareTo(notificationItem.getStartTime()) < 0) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
- "End Time should be greater than start time");
- }
-
- if ((notificationItem.getIsForAllRoles() == "N") && notificationItem.getRoleIds().isEmpty()) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE",
- "No Roles Ids Exist for the selected Roles");
- }
-
- Long creatorId = UserUtils.getUserIdAsLong(request);
- notificationItem.setCreatorId(creatorId);
-
- // Front-end date picker does not accept a time value, so all
- // values are the start of the chosen day in the local time zone.
- // Move the end time value to the very end of the chosen day.
- // Avoid Calendar.getDefault() which uses the server's locale.
- Long endTime = notificationItem.getEndTime().getTime();
- endTime += (23 * 3600 + 59 * 60 + 59) * 1000;
- notificationItem.getEndTime().setTime(endTime);
-
- try {
- userNotificationService.saveNotification(notificationItem);
- } catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
- }
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
- }
-
- @RequestMapping(value = {
- "/portalApi/notificationUpdateRate" }, method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<Map<String, String>> getNotificationUpdateRate(HttpServletRequest request) {
- try {
- String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_RATE);
- String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_DURATION);
- Integer rateInMiliSec = Integer.valueOf(updateRate) * 1000;
- Integer durationInMiliSec = Integer.valueOf(updateDuration) * 1000;
- Map<String, String> results = new HashMap<String, String>();
- results.put("updateRate", String.valueOf(rateInMiliSec));
- results.put("updateDuration", String.valueOf(durationInMiliSec));
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getNotificationUpdateRate failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
- @RequestMapping(value = {
- "/portalApi/notificationRead" }, method = RequestMethod.GET, produces = "application/json")
- public PortalRestResponse<Map<String, String>> notificationRead(
- @RequestParam("notificationId") String notificationID, HttpServletRequest request) {
- try {
- userNotificationService.setNotificationRead(Long.parseLong(notificationID), UserUtils.getUserId(request));
- return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "notificationRead failed", e);
- return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
- }
- }
-
- @RequestMapping(value = {
- "/portalApi/getNotificationHistory" }, method = RequestMethod.GET, produces = "application/json")
- public List<EpNotificationItemVO> getNotificationHistory(HttpServletRequest request, HttpServletResponse response) {
- EPUser user = EPUserUtils.getUserSession(request);
- List<EpNotificationItemVO> notificationList = null;
- notificationList = userNotificationService.getNotificationHistoryVO(user.getId());
- return notificationList;
- }
-
- @RequestMapping(value = { "/portalApi/notificationRole/{notificationId}/roles" }, method = {
- RequestMethod.GET }, produces = "application/json")
- public List<Integer> testGetRoles(HttpServletRequest request, @PathVariable("notificationId") Long notificationId) {
- List<EpRoleNotificationItem> NotifRoles = userNotificationService.getNotificationRoles(notificationId);
- ArrayList<Integer> rolesList = new ArrayList<Integer>();
- for (EpRoleNotificationItem notifRole : NotifRoles) {
- rolesList.add(notifRole.roleId);
- }
- return rolesList;
- }
-
- @RequestMapping(value = { "/portalApi/getNotificationAppRoles" }, method = {
- RequestMethod.GET }, produces = "application/json")
- public List<EcompAppRole> getNotificationAppRoles(HttpServletRequest request, HttpServletResponse response) {
- List<EcompAppRole> epAppRoleList = null;
- try {
- epAppRoleList = userNotificationService.getAppRoleList();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while performing UserNofiticationController.getNotificationAppRoles. Details: ",
- e);
- }
- return epAppRoleList;
- }
-
- @RequestMapping(value = {
- "/portalApi/getMessageRecipients" }, method = RequestMethod.GET, produces = "application/json")
- public List<String> getMessageRecipients(@RequestParam("notificationId") Long notificationID) {
- // EPUser user = EPUserUtils.getUserSession(request);
- List<String> messageUserRecipients = null;
- messageUserRecipients = userNotificationService.getMessageRecipients(notificationID);
- return messageUserRecipients;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +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.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +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.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EcompAppRole; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.FunctionalMenuService; +import org.openecomp.portalapp.portal.service.UserNotificationService; +import org.openecomp.portalapp.portal.transport.EpNotificationItem; +import org.openecomp.portalapp.portal.transport.EpNotificationItemVO; +import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem; +import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.util.EPUserUtils; + +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class UserNotificationController extends EPRestrictedBaseController { + + @Autowired + FunctionalMenuService functionalMenuService; + + @Autowired + UserNotificationService userNotificationService; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserNotificationController.class); + + @RequestMapping(value = { + "/portalApi/getFunctionalMenuRole" }, method = RequestMethod.GET, produces = "application/json") + public List<FunctionalMenuRole> getMenuIdRoleId(HttpServletRequest request, HttpServletResponse response) { + // EPUser user = EPUserUtils.getUserSession(request); + List<FunctionalMenuRole> menuRoleList = null; + menuRoleList = functionalMenuService.getFunctionalMenuRole(); + return menuRoleList; + } + + @RequestMapping(value = { + "/portalApi/getNotifications" }, method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<List<EpNotificationItem>> getNotifications(HttpServletRequest request, + HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + PortalRestResponse<List<EpNotificationItem>> portalRestResponse = null; + try { + List<EpNotificationItem> notificationList = userNotificationService.getNotifications(user.getId()); + portalRestResponse = new PortalRestResponse<List<EpNotificationItem>>(PortalRestStatusEnum.OK, "success", + notificationList); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAllAppsAndContacts failed", e); + portalRestResponse = new PortalRestResponse<List<EpNotificationItem>>(PortalRestStatusEnum.ERROR, + e.getMessage(), null); + } + return portalRestResponse; + } + + @RequestMapping(value = { + "/portalApi/getAdminNotifications" }, method = RequestMethod.GET, produces = "application/json") + public List<EpNotificationItemVO> getAdminNotifications(HttpServletRequest request, HttpServletResponse response) { + List<EpNotificationItemVO> adminNotificationList = null; + EPUser user = EPUserUtils.getUserSession(request); + adminNotificationList = userNotificationService.getAdminNotificationVOS(user.getId()); + return adminNotificationList; + } + + @RequestMapping(value = "/portalApi/saveNotification", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse<String> save(HttpServletRequest request, HttpServletResponse response, + @RequestBody EpNotificationItem notificationItem) { + + if (notificationItem == null || notificationItem.getMsgHeader() == null) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", + "Notification Header cannot be null or empty"); + if (notificationItem.getEndTime().compareTo(notificationItem.getStartTime()) < 0) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", + "End Time should be greater than start time"); + } + + if ((notificationItem.getIsForAllRoles() == "N") && notificationItem.getRoleIds().isEmpty()) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", + "No Roles Ids Exist for the selected Roles"); + } + + Long creatorId = UserUtils.getUserIdAsLong(request); + notificationItem.setCreatorId(creatorId); + + // Front-end date picker does not accept a time value, so all + // values are the start of the chosen day in the local time zone. + // Move the end time value to the very end of the chosen day. + // Avoid Calendar.getDefault() which uses the server's locale. + Long endTime = notificationItem.getEndTime().getTime(); + endTime += (23 * 3600 + 59 * 60 + 59) * 1000; + notificationItem.getEndTime().setTime(endTime); + + try { + userNotificationService.saveNotification(notificationItem); + } catch (Exception e) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); + } + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); + } + + @RequestMapping(value = { + "/portalApi/notificationUpdateRate" }, method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<Map<String, String>> getNotificationUpdateRate(HttpServletRequest request) { + try { + String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_RATE); + String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.NOTIFICATION_UPDATE_DURATION); + Integer rateInMiliSec = Integer.valueOf(updateRate) * 1000; + Integer durationInMiliSec = Integer.valueOf(updateDuration) * 1000; + Map<String, String> results = new HashMap<String, String>(); + results.put("updateRate", String.valueOf(rateInMiliSec)); + results.put("updateDuration", String.valueOf(durationInMiliSec)); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getNotificationUpdateRate failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null); + } + } + + @RequestMapping(value = { + "/portalApi/notificationRead" }, method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<Map<String, String>> notificationRead( + @RequestParam("notificationId") String notificationID, HttpServletRequest request) { + try { + userNotificationService.setNotificationRead(Long.parseLong(notificationID), UserUtils.getUserId(request)); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "notificationRead failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null); + } + } + + @RequestMapping(value = { + "/portalApi/getNotificationHistory" }, method = RequestMethod.GET, produces = "application/json") + public List<EpNotificationItemVO> getNotificationHistory(HttpServletRequest request, HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + List<EpNotificationItemVO> notificationList = null; + notificationList = userNotificationService.getNotificationHistoryVO(user.getId()); + return notificationList; + } + + @RequestMapping(value = { "/portalApi/notificationRole/{notificationId}/roles" }, method = { + RequestMethod.GET }, produces = "application/json") + public List<Integer> testGetRoles(HttpServletRequest request, @PathVariable("notificationId") Long notificationId) { + List<EpRoleNotificationItem> NotifRoles = userNotificationService.getNotificationRoles(notificationId); + ArrayList<Integer> rolesList = new ArrayList<Integer>(); + for (EpRoleNotificationItem notifRole : NotifRoles) { + rolesList.add(notifRole.roleId); + } + return rolesList; + } + + @RequestMapping(value = { "/portalApi/getNotificationAppRoles" }, method = { + RequestMethod.GET }, produces = "application/json") + public List<EcompAppRole> getNotificationAppRoles(HttpServletRequest request, HttpServletResponse response) { + List<EcompAppRole> epAppRoleList = null; + try { + epAppRoleList = userNotificationService.getAppRoleList(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while performing UserNofiticationController.getNotificationAppRoles. Details: ", + e); + } + return epAppRoleList; + } + + @RequestMapping(value = { + "/portalApi/getMessageRecipients" }, method = RequestMethod.GET, produces = "application/json") + public List<String> getMessageRecipients(@RequestParam("notificationId") Long notificationID) { + // EPUser user = EPUserUtils.getUserSession(request); + List<String> messageUserRecipients = null; + messageUserRecipients = userNotificationService.getMessageRecipients(notificationID); + return messageUserRecipients; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRecommendationController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRecommendationController.java new file mode 100644 index 00000000..3ec06ed3 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRecommendationController.java @@ -0,0 +1,87 @@ +package org.openecomp.portalapp.portal.controller; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.ConsulHealthService; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class UserRecommendationController extends EPRestrictedBaseController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRecommendationController.class); + + @Autowired + private ConsulHealthService consulHealthService; + + private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api"; + private static final String GET_RECOMMENDATION = MACHINE_LEARNING_SERVICE_CTX + "/" + "getRecommendation"; + private static final String GET_RECOMM_COUNT = MACHINE_LEARNING_SERVICE_CTX + "/" + "getRecommCount"; + private static final String CONSUL_ML_SERVICE_ID = "mlearning-service"; + private static final String SERVICE_PROTOCOL = "http"; + + @RequestMapping(value = { + "/portalApi/getRecommendationsCount" }, method = RequestMethod.GET, produces = "application/json") + public String getRecommendationsCount(HttpServletRequest request, HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + Map<String, String> requestMapping = new HashMap<String, String>(); + requestMapping.put("id", user.getOrgUserId()); + requestMapping.put("action", "reports"); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + // set your entity to send + HttpEntity<Map<String,String>> entity = new HttpEntity<>(requestMapping, headers); + String endpoint = SERVICE_PROTOCOL + "://"+ consulHealthService.getServiceLocation(CONSUL_ML_SERVICE_ID, + SystemProperties.getProperty("microservices.m-learn.local.port")) + GET_RECOMM_COUNT; + logger.debug(EELFLoggerDelegate.debugLogger, "Going to hit mlearning endpoint on: {1}", endpoint); + ResponseEntity<String> out = new RestTemplate().exchange(endpoint, HttpMethod.POST, entity, String.class); + return out.getBody(); + } + + @RequestMapping(value = { + "/portalApi/getRecommendations" }, method = RequestMethod.GET, produces = "application/json") + public String getRecommendations(HttpServletRequest request, HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + Map<String, String> requestMapping = new HashMap<String, String>(); + requestMapping.put("id", user.getOrgUserId()); + requestMapping.put("action", "reports"); + requestMapping.put("recommendations", "1"); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + // set your entity to send + HttpEntity<Map<String,String>> entity = new HttpEntity<>(requestMapping, headers); + String endpoint = SERVICE_PROTOCOL + "://"+ + consulHealthService.getServiceLocation(CONSUL_ML_SERVICE_ID, + SystemProperties.getProperty("microservices.m-learn.local.port")) + GET_RECOMMENDATION; + logger.debug(EELFLoggerDelegate.debugLogger, "Going to hit mlearning endpoint on: {1}", endpoint); + ResponseEntity<String> out = new RestTemplate().exchange(endpoint, HttpMethod.POST, entity, String.class); + return out.getBody(); + } + +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java index 719b7d45..7bcd5845 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java @@ -57,7 +57,7 @@ import org.openecomp.portalsdk.core.domain.AuditLog; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.openecomp.portalsdk.core.restful.domain.EcompRole; import org.openecomp.portalsdk.core.service.AuditService; -import org.openecomp.portalsdk.core.service.RoleService; +import org.openecomp.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.EnableAspectJAutoProxy; @@ -74,29 +74,34 @@ import org.springframework.web.bind.annotation.RestController; @EPAuditLog public class UserRolesController extends EPRestrictedBaseController { + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class); + @Autowired - SearchService searchService; - @Autowired - AdminRolesService adminRolesService; - @Autowired - UserRolesService userRolesService; + private SearchService searchService; @Autowired - ApplicationsRestClientService applicationsRestClientService; + private AdminRolesService adminRolesService; + private @Autowired UserRolesService userRolesService; @Autowired - RoleService roleService; + private ApplicationsRestClientService applicationsRestClientService; @Autowired - AuditService auditService; - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class); - - static final String FAILURE = "failure"; + private AuditService auditService; + + private static final String FAILURE = "failure"; /** * RESTful service method to fetch users in the WebPhone external service * + * @param request + * HttpServletRequest + * @param searchString + * search string + * @param response + * HttpServletResponse * @return array of found users as json */ @RequestMapping(value = { "/portalApi/queryUsers" }, method = RequestMethod.GET, produces = "application/json") - public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString, HttpServletResponse response) { + public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString, + HttpServletResponse response) { EPUser user = EPUserUtils.getUserSession(request); String searchResult = null; if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)) { @@ -106,23 +111,32 @@ public class UserRolesController extends EPRestrictedBaseController { if (searchString.length() > 2) { searchResult = searchService.searchUsersInPhoneBook(searchString); } else { - logger.info(EELFLoggerDelegate.errorLogger, "getPhoneBookSearchResult - too short search string: " + searchString); + logger.info(EELFLoggerDelegate.errorLogger, + "getPhoneBookSearchResult - too short search string: " + searchString); } } EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult); - + return searchResult; } /** * RESTful service method to fetch applications where user is admin * - * @return for GET: array of all applications with boolean isAdmin=true/false for each application + * @param request + * HttpServletRequest + * @param orgUserId + * search string + * @param response + * HttpServletResponse + * @return for GET: array of all applications with boolean + * isAdmin=true/false for each application */ - @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = { RequestMethod.GET }, produces = "application/json") - public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(HttpServletRequest request, @RequestParam("user") String orgUserId, - HttpServletResponse response) { - + @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = { + RequestMethod.GET }, produces = "application/json") + public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(HttpServletRequest request, + @RequestParam("user") String orgUserId, HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); AppsListWithAdminRole result = null; if (!adminRolesService.isSuperAdmin(user)) { @@ -131,15 +145,16 @@ public class UserRolesController extends EPRestrictedBaseController { if (EcompPortalUtils.legitimateUserId(orgUserId)) { result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId); } else { - logger.info(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID"); + logger.info(EELFLoggerDelegate.errorLogger, + "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } StringBuilder adminAppRoles = new StringBuilder(); - if(result != null && result.appsRoles.size() >= 1) { + if (result != null && result.appsRoles.size() >= 1) { adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {"); - for(AppNameIdIsAdmin adminAppRole : result.appsRoles) { + for (AppNameIdIsAdmin adminAppRole : result.appsRoles) { if (adminAppRole.isAdmin) { adminAppRoles.append(adminAppRole.appName + ", "); } @@ -149,36 +164,47 @@ public class UserRolesController extends EPRestrictedBaseController { adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role."); } logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString()); - + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "get result =", result); return result; } - @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = { RequestMethod.PUT }, produces = "application/json") - public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request, @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, - HttpServletResponse response) { - - //newAppsListWithAdminRoles.appsRoles + /** + * + * @param request + * HttpServletRequest + * @param newAppsListWithAdminRoles + * new apps + * @param response + * HttpServletResponse + * @return FieldsValidator + */ + @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = { + RequestMethod.PUT }, produces = "application/json") + public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request, + @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, HttpServletResponse response) { + + // newAppsListWithAdminRoles.appsRoles FieldsValidator fieldsValidator = new FieldsValidator(); StringBuilder newAppRoles = new StringBuilder(); - if(newAppsListWithAdminRoles != null && newAppsListWithAdminRoles.appsRoles.size() >= 1) { + if (newAppsListWithAdminRoles != null && newAppsListWithAdminRoles.appsRoles.size() >= 1) { newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = { "); - for(AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) { + for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) { if (adminAppRole.isAdmin) { newAppRoles.append(adminAppRole.appName + " ,"); } } - newAppRoles.deleteCharAt(newAppRoles.length()-1); + newAppRoles.deleteCharAt(newAppRoles.length() - 1); newAppRoles.append("}."); } else { newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has no Apps with Admin Role."); } logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString()); - + EPUser user = EPUserUtils.getUserSession(request); boolean changesApplied = false; - + if (!adminRolesService.isSuperAdmin(user)) { EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser"); } else { @@ -190,20 +216,44 @@ public class UserRolesController extends EPRestrictedBaseController { auditLog.setComments(newAppRoles.toString()); auditService.logActivity(auditLog, null); - MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC()); - MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC()); - logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("UserRolesController.putAppsWithAdminRoleStateForUser", - EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(), newAppsListWithAdminRoles.orgUserId, newAppRoles.toString())); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("UserRolesController.putAppsWithAdminRoleStateForUser", + EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(), + newAppsListWithAdminRoles.orgUserId, newAppRoles.toString())); MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); } EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied); - + return fieldsValidator; } - @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { RequestMethod.GET }, produces = "application/json") - public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId, @RequestParam("app") Long appid, HttpServletResponse response) { + /** + * It returns a list of user app roles for single app + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + * @param orgUserId + * user ID + * @param appid + * application ID + * @param extRequestValue + * set to false if request is from users page otherwise true + * @return List<RoleInAppForUser> + */ + @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { + RequestMethod.GET }, produces = "application/json") + public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId, + @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue, + HttpServletResponse response) { EPUser user = EPUserUtils.getUserSession(request); List<RoleInAppForUser> result = null; String feErrorString = ""; @@ -212,16 +262,18 @@ public class UserRolesController extends EPRestrictedBaseController { feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus()); } else { if (EcompPortalUtils.legitimateUserId(orgUserId)) { - result = userRolesService.getAppRolesForUser(appid, orgUserId); + result = userRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue); int responseCode = EcompPortalUtils.getExternalAppResponseCode(); if (responseCode != 0 && responseCode != 200) { // external error response.setStatus(responseCode); feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode); } else if (result == null) { - // If the result is null, there was an internal ecomp error in the service call. + // If the result is null, there was an internal ecomp error + // in the service call. response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + feErrorString = EcompPortalUtils.getFEErrorString(true, + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no Organization User ID"); @@ -229,29 +281,29 @@ public class UserRolesController extends EPRestrictedBaseController { feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST); } } - + StringBuilder sbUserApps = new StringBuilder(); - if (result!=null && result.size()>=1) { + if (result != null && result.size() >= 1) { sbUserApps.append("User '" + orgUserId + "' has Roles={"); - for(RoleInAppForUser appRole : result) { + for (RoleInAppForUser appRole : result) { if (appRole.isApplied) { sbUserApps.append(appRole.roleName + ", "); } } sbUserApps.append("} assigned to the appId '" + appid + "'."); } else { - //Not sure creating an empty object will make any difference - //but would like to give it a shot for defect #DE221057 - if (result==null) { + // Not sure creating an empty object will make any difference + // but would like to give it a shot for defect #DE221057 + if (result == null) { result = new ArrayList<RoleInAppForUser>(); } sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles"); } logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString()); - + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "get result =", result); if (feErrorString != "") { - logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: "+feErrorString); + logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: " + feErrorString); response.addHeader("FEErrorString", feErrorString); response.addHeader("Access-Control-Expose-Headers", "FEErrorString"); @@ -259,129 +311,155 @@ public class UserRolesController extends EPRestrictedBaseController { return result; } - @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { RequestMethod.PUT }, produces = "application/json") - public FieldsValidator putAppWithUserRoleStateForUser(HttpServletRequest request, @RequestBody AppWithRolesForUser newAppRolesForUser, - HttpServletResponse response) { + @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { + RequestMethod.PUT }, produces = "application/json") + public FieldsValidator putAppWithUserRoleStateForUser(HttpServletRequest request, + @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) { FieldsValidator fieldsValidator = new FieldsValidator(); StringBuilder sbUserApps = new StringBuilder(); - if (newAppRolesForUser!=null) { + if (newAppRolesForUser != null) { sbUserApps.append("User '" + newAppRolesForUser.orgUserId); - if (newAppRolesForUser.appRoles!=null && newAppRolesForUser.appRoles.size()>=1) { + if (newAppRolesForUser.appRoles != null && newAppRolesForUser.appRoles.size() >= 1) { sbUserApps.append("' has roles = { "); - for(RoleInAppForUser appRole : newAppRolesForUser.appRoles) { - if (appRole.isApplied) { - sbUserApps.append(appRole.roleName + " ,"); - } + for (RoleInAppForUser appRole : newAppRolesForUser.appRoles) { + if (appRole.isApplied) { + sbUserApps.append(appRole.roleName + " ,"); + } } - sbUserApps.deleteCharAt(sbUserApps.length()-1); + sbUserApps.deleteCharAt(sbUserApps.length() - 1); sbUserApps.append("} assigned for the app " + newAppRolesForUser.appId); } else { sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.appId); } } logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", sbUserApps.toString()); - + EPUser user = EPUserUtils.getUserSession(request); boolean changesApplied = false; if (!adminRolesService.isAccountAdmin(user)) { EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser"); } else { changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser); - if (changesApplied){ - logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: succeeded for app {}, user {}", - newAppRolesForUser.appId, newAppRolesForUser.orgUserId); + if (changesApplied) { + logger.info(EELFLoggerDelegate.applicationLogger, + "putAppWithUserRoleStateForUser: succeeded for app {}, user {}", newAppRolesForUser.appId, + newAppRolesForUser.orgUserId); AuditLog auditLog = new AuditLog(); auditLog.setUserId(user.getId()); auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER); auditLog.setAffectedRecordId(newAppRolesForUser.orgUserId); auditLog.setComments(sbUserApps.toString()); - MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); auditService.logActivity(auditLog, null); - MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC()); - logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser", - EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(), newAppRolesForUser.orgUserId, sbUserApps.toString())); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser", + EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(), + newAppRolesForUser.orgUserId, sbUserApps.toString())); MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); } else { - logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleStateForUser: failed for app {}, user {}", - newAppRolesForUser.appId, newAppRolesForUser.orgUserId); + logger.error(EELFLoggerDelegate.errorLogger, + "putAppWithUserRoleStateForUser: failed for app {}, user {}", newAppRolesForUser.appId, + newAppRolesForUser.orgUserId); } } EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied); return fieldsValidator; } - - @RequestMapping(value = { "/portalApi/updateRemoteUserProfile" }, method = { RequestMethod.GET }, produces = "application/json") - public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request,HttpServletResponse response) { - + + @RequestMapping(value = { "/portalApi/updateRemoteUserProfile" }, method = { + RequestMethod.GET }, produces = "application/json") + public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request, + HttpServletResponse response) { + String updateRemoteUserFlag = FAILURE; try { - //saveNewUser = userService.saveNewUser(newUser); + // saveNewUser = userService.saveNewUser(newUser); String orgUserId = request.getParameter("loginId"); Long appId = Long.parseLong(request.getParameter("appId")); userRolesService.updateRemoteUserProfile(orgUserId, appId); - + } catch (Exception e) { return new PortalRestResponse<String>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage()); } return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, ""); - + } - @RequestMapping(value = { "/portalApi/app/{appId}/users" }, method = { RequestMethod.GET }, produces = "application/json") - public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException { + @RequestMapping(value = { "/portalApi/app/{appId}/users" }, method = { + RequestMethod.GET }, produces = "application/json") + public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request, + @PathVariable("appId") Long appId) throws HTTPException { try { logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId); List<UserApplicationRoles> appUsers = userRolesService.getUsersFromAppEndpoint(appId); return appUsers; - } catch(Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing UserRolesController.getUsersFromAppEndpoint. Details: " + EcompPortalUtils.getStackTrace(e)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while performing UserRolesController.getUsersFromAppEndpoint. Details: " + + EcompPortalUtils.getStackTrace(e)); return new ArrayList<UserApplicationRoles>(); } } - @RequestMapping(value = { "/portalApi/app/{appId}/roles" }, method = { RequestMethod.GET }, produces = "application/json") - public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException { + @RequestMapping(value = { "/portalApi/app/{appId}/roles" }, method = { + RequestMethod.GET }, produces = "application/json") + public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId) + throws HTTPException { EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles"); List<EcompRole> rolesList = Arrays.asList(appRoles); - EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId, rolesList); - + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId, + rolesList); + return rolesList; } - @RequestMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, method = { RequestMethod.GET }, produces = "application/json") - public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException { + @RequestMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, method = { + RequestMethod.GET }, produces = "application/json") + public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId) + throws HTTPException { List<EPRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId); - EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles", "response for appId=" + appId, rolesList); - + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles", + "response for appId=" + appId, rolesList); + return rolesList; } - @RequestMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, method = { RequestMethod.GET }, produces = "application/json") - public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId, @PathVariable("orgUserId") String orgUserId) throws Exception { + @RequestMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, method = { + RequestMethod.GET }, produces = "application/json") + public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId, + @PathVariable("orgUserId") String orgUserId) throws Exception { if (!EcompPortalUtils.legitimateUserId(orgUserId)) { String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId; logger.error(EELFLoggerDelegate.errorLogger, msg); throw new Exception(msg); } - EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId, String.format("/user/%s/roles", orgUserId)); + EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId, + String.format("/user/%s/roles", orgUserId)); if (roles.length != 1) { String msg = "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length; logger.error(EELFLoggerDelegate.errorLogger, msg); throw new Exception(msg); } - - EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles", "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]); + + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles", + "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]); return roles[0]; } - - @RequestMapping(value = { "/portalApi/saveUserAppRoles" }, method = { RequestMethod.PUT }, produces = "application/json") - public FieldsValidator putAppWithUserRoleRequest(HttpServletRequest request, @RequestBody AppWithRolesForUser newAppRolesForUser, - HttpServletResponse response) { + + @RequestMapping(value = { "/portalApi/saveUserAppRoles" }, method = { + RequestMethod.PUT }, produces = "application/json") + public FieldsValidator putAppWithUserRoleRequest(HttpServletRequest request, + @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) { FieldsValidator fieldsValidator = null; try { - + EPUser user = EPUserUtils.getUserSession(request); fieldsValidator = userRolesService.putUserAppRolesRequest(newAppRolesForUser, user); response.setStatus(fieldsValidator.httpStatusCode.intValue()); @@ -395,7 +473,7 @@ public class UserRolesController extends EPRestrictedBaseController { response.getStatus()); return fieldsValidator; } - + @RequestMapping(value = { "/portalApi/appCatalogRoles" }, method = { RequestMethod.GET }, produces = "application/json") public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(HttpServletRequest request, @@ -414,22 +492,24 @@ public class UserRolesController extends EPRestrictedBaseController { return userAppRoleList; } + private Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator = new Comparator<EPUserAppCatalogRoles>() { public int compare(EPUserAppCatalogRoles o1, EPUserAppCatalogRoles o2) { return o1.getRolename().compareTo(o2.getRolename()); } }; - + @RequestMapping(value = "/portalApi/externalRequestAccessSystem", method = RequestMethod.GET, produces = "application/json") public ExternalSystemAccess readExternalRequestAccess(HttpServletRequest request) { ExternalSystemAccess result = null; - try { + try { result = userRolesService.getExternalRequestAccess(); - EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =", result); + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =", + result); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger,"readExternalRequestAccess failed: " + e.getMessage()); - } + logger.error(EELFLoggerDelegate.errorLogger, "readExternalRequestAccess failed: " + e.getMessage()); + } return result; } - + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java index f1d77a3f..b5761617 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java @@ -1,157 +1,241 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.commons.io.IOUtils;
-import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController;
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EcompAuditLog;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.service.AppsCacheService;
-import org.openecomp.portalapp.portal.transport.Analytics;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.PortalConstants;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
-import org.openecomp.portalsdk.core.service.AuditService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.ResponseBody;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.swagger.annotations.ApiOperation;
-
-@RestController
-@RequestMapping(PortalConstants.REST_AUX_API)
-@Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController{
-
- private static final String APP_KEY = "uebkey";
-
- @Autowired
- AuditService auditService;
-
- @Autowired
- AppsCacheService appCacheService;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
-
- protected boolean isAuxRESTfulCall() {
- return true;
- }
-
- /*
- * Answers requests from partner applications for a file that is expected to
- * contain javascript to support web analytics.
- *
- * @param request
- * @return
- * @throws Exception
- */
- @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class)
- @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript")
- public String getAnalyticsScript(HttpServletRequest request) throws Exception {
- String responseText = "";
- final String fileName = "analytics.txt";
- InputStream analyticsFileStream = null;
- try {
- analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
- responseText = IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e);
- } finally {
- if (analyticsFileStream != null)
- analyticsFileStream.close();
- }
-
- String feURLContext = SystemProperties.getProperty("frontend_url");
- String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/'));
-
- responseText = responseText.replace("PORTAL_ENV_URL", feURL);
- return responseText;
- }
-
- /**
- * Accepts data from partner applications with web analytics data.
- *
- * @param request
- * @param analyticsMap
- * @param response
- * @return
- * @throws Exception
- */
- @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json")
- @ResponseBody
- @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class)
- public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap) throws Exception {
- try{
- MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
- String appName = "";
- try {
-
- String appKeyValue = request.getHeader(APP_KEY);
- if(appKeyValue == null || appKeyValue.equals("")) {
- logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
- } else {
- EPApp appRecord = appCacheService.getAppForAnalytics(appKeyValue);
- if(appRecord == null){
- logger.error(EELFLoggerDelegate.errorLogger, " App could not be found for the key "+ appKeyValue);
- }
- else appName = appRecord.getName();
-
- }
-
- } catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, " Error retrieving Application to capture app name for analytics; Proceeding with empty app name");
- }
-
-
-
- logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserId(),appName, "WebAnalyticsExtAppController.postWebAnalyticsData",
- EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(),analyticsMap.getPage(),analyticsMap.getFunction(),analyticsMap.getType()));
- MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
- MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
-
- PortalAPIResponse response = new PortalAPIResponse(true, "success");
- return response;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e);
- PortalAPIResponse response = new PortalAPIResponse(true, "error");
- return response;
- }
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EcompAuditLog; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.service.AppsCacheService; +import org.openecomp.portalapp.portal.service.ConsulHealthService; +import org.openecomp.portalapp.portal.transport.Analytics; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse; +import org.openecomp.portalsdk.core.service.AuditService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.concurrent.FailureCallback; +import org.springframework.util.concurrent.ListenableFuture; +import org.springframework.util.concurrent.SuccessCallback; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.AsyncRestTemplate; + +import io.swagger.annotations.ApiOperation; + +@RestController +@RequestMapping(PortalConstants.REST_AUX_API) +@Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController { + + @Autowired + private ConsulHealthService consulHealthService; + + private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api"; + private static final String REGISTER_ACTION = MACHINE_LEARNING_SERVICE_CTX + "/" + "registerAction"; + private static final String CONSUL_ML_SERVICE_ID = "machine-learning"; + private static final String SERVICE_PROTOCOL = "http"; + private static final String APP_KEY = "uebkey"; + + @Autowired + AuditService auditService; + + @Autowired + AppsCacheService appCacheService; + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class); + + private AsyncRestTemplate restTemplate = new AsyncRestTemplate(); + + SuccessCallback<ResponseEntity<String>> successCallback = new SuccessCallback<ResponseEntity<String>>() { + @Override + public void onSuccess(ResponseEntity<String> arg) { + logger.info(EELFLoggerDelegate.debugLogger, arg.getBody()); + } + }; + + FailureCallback failureCallback = new FailureCallback() { + @Override + public void onFailure(Throwable arg) { + logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg); + } + }; + + protected boolean isAuxRESTfulCall() { + return true; + } + + /** + * Answers requests from partner applications for a file that is expected to + * contain javascript to support web analytics. + * + * @param request + * HttpServletRequest + * @return String + * @throws Exception + * on failure + */ + @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class) + @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript") + public String getAnalyticsScript(HttpServletRequest request) throws Exception { + String responseText = ""; + final String fileName = "analytics.txt"; + InputStream analyticsFileStream = null; + try { + analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName); + responseText = IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e); + } finally { + if (analyticsFileStream != null) + analyticsFileStream.close(); + } + + String feURLContext = SystemProperties.getProperty("frontend_url"); + String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/')); + + responseText = responseText.replace("PORTAL_ENV_URL", feURL); + return responseText; + } + + /** + * Accepts data from partner applications with web analytics data. + * + * @param request + * HttpServletRequest + * @param analyticsMap + * Analytics + * @return PortalAPIResponse + * @throws Exception + * on failure + */ + @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class) + public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap) + throws Exception { + try { + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + String appName = ""; + try { + appName = getAppName(request, appName); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + " Error retrieving Application to capture app name for analytics; Proceeding with empty app name"); + } + + try { + storeAuxAnalytics(analyticsMap, appName); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + " Error retrieving Application to capture app name for analytics; Proceeding with empty app name"); + } + + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserId(), appName, + "WebAnalyticsExtAppController.postWebAnalyticsData", + EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(), + analyticsMap.getFunction(), analyticsMap.getType())); + + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + + PortalAPIResponse response = new PortalAPIResponse(true, "success"); + return response; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e); + PortalAPIResponse response = new PortalAPIResponse(true, "error"); + return response; + } + } + + protected String getAppName(HttpServletRequest request, String appName) { + String appKeyValue = request.getHeader(APP_KEY); + if (appKeyValue == null || appKeyValue.equals("")) { + logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name"); + } else { + EPApp appRecord = appCacheService.getAppForAnalytics(appKeyValue); + if (appRecord == null) { + logger.error(EELFLoggerDelegate.errorLogger, " App could not be found for the key " + appKeyValue); + } else + appName = appRecord.getName(); + + } + return appName; + } + + protected void storeAuxAnalytics(Analytics analyticsMap, String appName) { + logger.info(EELFLoggerDelegate.debugLogger, + " Registering an action for recommendation: AppName/Function/UserId " + appName + "/" + + analyticsMap.getFunction() + "/" + analyticsMap.getUserId()); + + Map<String, String> requestMapping = new HashMap<String, String>(); + requestMapping.put("id", analyticsMap.getUserId()); + requestMapping.put("action", appName + "|" + analyticsMap.getFunction()); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + // set your entity to send + HttpEntity<Map<String, String>> entity = new HttpEntity<Map<String, String>>(requestMapping, headers); + + // send it! + ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange( + SERVICE_PROTOCOL + "://" + + consulHealthService.getServiceLocation(CONSUL_ML_SERVICE_ID, + SystemProperties.getProperty("microservices.m-learn.local.port")) + + REGISTER_ACTION, + HttpMethod.POST, entity, String.class); + out.addCallback(successCallback, failureCallback); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogController.java index f69a6484..9ac81e9a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogController.java @@ -1,376 +1,392 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.openecomp.portalapp.controller.EPRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.MicroserviceData;
-import org.openecomp.portalapp.portal.domain.MicroserviceParameter;
-import org.openecomp.portalapp.portal.domain.WidgetCatalog;
-import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter;
-import org.openecomp.portalapp.portal.domain.WidgetParameterResult;
-import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.ConsulHealthService;
-import org.openecomp.portalapp.portal.service.MicroserviceService;
-import org.openecomp.portalapp.portal.service.WidgetParameterService;
-import org.openecomp.portalapp.util.EPUserUtils;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.core.io.FileSystemResource;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.util.LinkedMultiValueMap;
-import org.springframework.util.MultiValueMap;
-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.springframework.web.client.RestClientException;
-import org.springframework.web.client.RestTemplate;
-import org.springframework.web.multipart.MultipartFile;
-import org.springframework.web.multipart.MultipartHttpServletRequest;
-import org.springframework.web.multipart.commons.CommonsMultipartResolver;
-
-@SuppressWarnings("unchecked")
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class WidgetsCatalogController extends EPRestrictedBaseController {
-
- private static final String HTTPS = "https://";
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogController.class);
- RestTemplate template = new RestTemplate();
- String whatService = "widgets-service";
-
- @Autowired
- private ConsulHealthService consulHealthService;
-
- @Autowired
- private MicroserviceService microserviceService;
-
- @Autowired
- private WidgetParameterService widgetParameterService;
-
- @Bean
- public CommonsMultipartResolver multipartResolver() {
- return new CommonsMultipartResolver();
- }
-
- static {
- // for localhost testing only
- javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
-
- public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
- if (hostname.equals("localhost")) {
- return true;
- }
- return false;
- }
- });
- }
-
- @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{loginName}" }, method = RequestMethod.GET)
- public List<WidgetCatalog> getUserWidgetCatalog(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("loginName") String loginName) throws RestClientException, Exception {
- List<WidgetCatalog> widgets = new ArrayList<>();
- try {
- ResponseEntity<ArrayList> ans = template.exchange(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/" + loginName,
- HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), ArrayList.class);
- widgets = ans.getBody();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getUserWidgetCatalog failed", e);
- // returning null because null help check on the UI if there was a
- // communication problem with Microservice.
- return null;
- }
- return widgets;
- }
-
- @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.GET)
- public List<WidgetCatalog> getWidgetCatalog(HttpServletRequest request, HttpServletResponse response)
- throws RestClientException, Exception {
- List<WidgetCatalog> widgets = new ArrayList<>();
- try {
- ResponseEntity<ArrayList> ans = template.exchange(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog",
- HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), ArrayList.class);
- widgets = ans.getBody();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getWidgetCatalog failed", e);
- // returning null because null help check on the UI if there was a
- // communication problem with Microservice.
- return null;
- }
- return widgets;
- }
-
- @RequestMapping(value = {
- "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.PUT, produces = "application/json")
- public void updateWidgetCatalog(HttpServletRequest request, HttpServletResponse response,
- @RequestBody WidgetCatalog newWidgetCatalog, @PathVariable("widgetId") long widgetId)
- throws RestClientException, Exception {
- template.exchange(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/" + widgetId,
- HttpMethod.PUT, new HttpEntity(newWidgetCatalog, WidgetServiceHeaders.getInstance()), String.class);
- }
-
- @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.DELETE)
- public void deleteOnboardingWidget(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
- template.exchange(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/" + widgetId,
- HttpMethod.DELETE, new HttpEntity(WidgetServiceHeaders.getInstance()), String.class);
- }
-
- @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.POST)
- public String updateWidgetCatalogWithFiles(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
- MultipartHttpServletRequest mRequest;
- MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
- String fileName;
- String tmp_folder = "/tmp/";
- String respond = null;
- FileOutputStream fo = null;
- try {
- mRequest = (MultipartHttpServletRequest) request;
- MultipartFile mFile = mRequest.getFile("file");
- fileName = mFile.getOriginalFilename();
- fo = new FileOutputStream(tmp_folder + fileName);
- fo.write(mFile.getBytes());
-
- HttpHeaders header = new HttpHeaders();
- header.setContentType(MediaType.MULTIPART_FORM_DATA);
- multipartRequest.add("file", new FileSystemResource(tmp_folder + fileName));
- multipartRequest.add("widget", request.getParameter("newWidget"));
- respond = template.postForObject(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/" + widgetId,
- new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
- File f = new File(tmp_folder + fileName);
- f.delete();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed", e);
- } finally {
- try {
- if (fo != null)
- fo.close();
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed 2", e);
- }
- }
- return respond;
- }
-
- @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.POST)
- public String createWidgetCatalog(HttpServletRequest request, HttpServletResponse response)
- throws RestClientException, Exception {
- MultipartHttpServletRequest mRequest;
- MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
- String fileName;
- String tmp_folder = "/tmp/";
- String respond = null;
- FileOutputStream fo = null;
- try {
- mRequest = (MultipartHttpServletRequest) request;
- MultipartFile mFile = mRequest.getFile("file");
- fileName = mFile.getOriginalFilename();
- fo = new FileOutputStream(tmp_folder + fileName);
- fo.write(mFile.getBytes());
-
- HttpHeaders header = new HttpHeaders();
- header.setContentType(MediaType.MULTIPART_FORM_DATA);
- multipartRequest.add("file", new FileSystemResource(tmp_folder + fileName));
- multipartRequest.add("widget", request.getParameter("newWidget"));
-
- respond = template.postForObject(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog",
- new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
- File f = new File(tmp_folder + fileName);
- f.delete();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed", e);
- } finally {
- try {
- if (fo != null)
- fo.close();
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed 2", e);
- }
- }
- return respond;
- }
-
- @RequestMapping(value = "/portalApi/microservices/{widgetId}/framework.js", method = RequestMethod.GET)
- public String getWidgetFramework(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
- return template.getForObject(HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/" + widgetId + "/framework.js", String.class,
- WidgetServiceHeaders.getInstance());
- }
-
- @RequestMapping(value = "/portalApi/microservices/{widgetId}/controller.js", method = RequestMethod.GET)
- public String getWidgetController(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
- return template.getForObject(HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/" + widgetId + "/controller.js", String.class,
- WidgetServiceHeaders.getInstance());
- }
-
- @RequestMapping(value = "/portalApi/microservices/{widgetId}/style.css", method = RequestMethod.GET)
- public String getWidgetCSS(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
- return template.getForObject(HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/" + widgetId + "/styles.css", String.class,
- WidgetServiceHeaders.getInstance());
- }
-
- @RequestMapping(value = { "/portalApi/microservices/parameters/{widgetId}" }, method = RequestMethod.GET)
- public PortalRestResponse<List<WidgetParameterResult>> getWidgetParameterResult(HttpServletRequest request,
- HttpServletResponse response, @PathVariable("widgetId") long widgetId) throws Exception {
- EPUser user = EPUserUtils.getUserSession(request);
-
- List<WidgetParameterResult> list = new ArrayList<>();
- Long serviceId = template.exchange(
- HTTPS + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
- HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class).getBody();
- if (serviceId == null) {
- // return ok/sucess and no service parameter for this widget
- return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.WARN,
- "No service parameters for this widget", list);
- } else {
- List<MicroserviceParameter> defaultParam = microserviceService.getParametersById(serviceId);
- for (MicroserviceParameter param : defaultParam) {
- WidgetParameterResult user_result = new WidgetParameterResult();
- user_result.setParam_id(param.getId());
- user_result.setDefault_value(param.getPara_value());
- user_result.setParam_key(param.getPara_key());
- WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
- param.getId());
- if (userValue == null)
- user_result.setUser_value(param.getPara_value());
- else {
- user_result.setUser_value(userValue.getUser_value());
- }
- list.add(user_result);
- }
- }
- return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.OK, "SUCCESS", list);
- }
-
- @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.GET)
- public List<WidgetCatalogParameter> getUserParameterById(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("paramId") long paramId) throws Exception {
- List<WidgetCatalogParameter> list = widgetParameterService.getUserParameterById(paramId);
- return list;
- }
-
- @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.DELETE)
- public void deleteUserParameterById(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("paramId") long paramId) throws Exception {
- widgetParameterService.deleteUserParameterById(paramId);
- }
-
- @RequestMapping(value = { "/portalApi/microservices/download/{widgetId}" }, method = RequestMethod.GET)
- public void doDownload(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
-
- ServletContext context = request.getServletContext();
- byte[] byteFile = template.exchange(HTTPS + consulHealthService.getServiceLocation(whatService) + "/widget/microservices/download/" + widgetId,
- HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), byte[].class).getBody();
- String fileLocation = widgetId + ".zip";
- FileOutputStream stream = new FileOutputStream(fileLocation);
- stream.write(byteFile);
- stream.close();
-
- File downloadFile = new File(fileLocation);
- FileInputStream inputStream = new FileInputStream(downloadFile);
- String mimeType = context.getMimeType(downloadFile.getPath());
- if (mimeType == null) {
- mimeType = "application/octet-stream";
- }
-
- response.setContentType(mimeType);
- response.setContentLength((int) downloadFile.length());
- String headerKey = "Content-Disposition";
- String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
- downloadFile.delete();
- response.setHeader(headerKey, headerValue);
-
- OutputStream outStream = response.getOutputStream();
- byte[] buffer = new byte[32 * 1024];
- int bytesRead = -1;
- while ((bytesRead = inputStream.read(buffer)) != -1) {
- outStream.write(buffer, 0, bytesRead);
- }
-
- inputStream.close();
- outStream.close();
- }
-
- @RequestMapping(value = { "/portalApi/microservices/parameters" }, method = RequestMethod.POST)
- public PortalRestResponse<String> saveWidgetParameter(HttpServletRequest request, HttpServletResponse response,
- @RequestBody WidgetCatalogParameter widgetParameters) throws Exception {
- EPUser user = EPUserUtils.getUserSession(request);
- widgetParameters.setUserId(user.getId());
- try {
- WidgetCatalogParameter oldParam = widgetParameterService.getUserParamById(widgetParameters.getWidgetId(),
- widgetParameters.getUserId(), widgetParameters.getParamId());
- if (oldParam != null) {
- widgetParameters.setId(oldParam.getId());
- }
- widgetParameterService.saveUserParameter(widgetParameters);
-
- } catch (Exception e) {
- return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
- }
- return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", "");
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.MicroserviceParameter; +import org.openecomp.portalapp.portal.domain.WidgetCatalog; +import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter; +import org.openecomp.portalapp.portal.domain.WidgetParameterResult; +import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.ConsulHealthService; +import org.openecomp.portalapp.portal.service.MicroserviceService; +import org.openecomp.portalapp.portal.service.WidgetParameterService; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +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.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.MultipartHttpServletRequest; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; + +@SuppressWarnings("unchecked") +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class WidgetsCatalogController extends EPRestrictedBaseController { + + private static final String HTTPS = "https://"; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogController.class); + RestTemplate template = new RestTemplate(); + String whatService = "widgets-service"; + + @Autowired + private ConsulHealthService consulHealthService; + + @Autowired + private MicroserviceService microserviceService; + + @Autowired + private WidgetParameterService widgetParameterService; + + @Bean + public CommonsMultipartResolver multipartResolver() { + return new CommonsMultipartResolver(); + } + + static { + // for localhost testing only + javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() { + + public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) { + if (hostname.equals("localhost")) { + return true; + } + return false; + } + }); + } + + @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{loginName}" }, method = RequestMethod.GET) + public List<WidgetCatalog> getUserWidgetCatalog(HttpServletRequest request, HttpServletResponse response, + @PathVariable("loginName") String loginName) throws RestClientException, Exception { + List<WidgetCatalog> widgets = new ArrayList<>(); + try { + ResponseEntity<ArrayList> ans = template.exchange( + HTTPS + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/widgetCatalog/" + loginName, + HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), ArrayList.class); + widgets = ans.getBody(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getUserWidgetCatalog failed", e); + // returning null because null help check on the UI if there was a + // communication problem with Microservice. + return null; + } + return widgets; + } + + @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.GET) + public List<WidgetCatalog> getWidgetCatalog(HttpServletRequest request, HttpServletResponse response) + throws RestClientException, Exception { + List<WidgetCatalog> widgets = new ArrayList<>(); + try { + ResponseEntity<ArrayList> ans = template.exchange( + HTTPS + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/widgetCatalog", + HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), ArrayList.class); + widgets = ans.getBody(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getWidgetCatalog failed", e); + // returning null because null help check on the UI if there was a + // communication problem with Microservice. + return null; + } + return widgets; + } + + @RequestMapping(value = { + "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.PUT, produces = "application/json") + public void updateWidgetCatalog(HttpServletRequest request, HttpServletResponse response, + @RequestBody WidgetCatalog newWidgetCatalog, @PathVariable("widgetId") long widgetId) + throws RestClientException, Exception { + template.exchange( + HTTPS + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/widgetCatalog/" + widgetId, + HttpMethod.PUT, new HttpEntity(newWidgetCatalog, WidgetServiceHeaders.getInstance()), String.class); + } + + @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.DELETE) + public void deleteOnboardingWidget(HttpServletRequest request, HttpServletResponse response, + @PathVariable("widgetId") long widgetId) throws RestClientException, Exception { + template.exchange( + HTTPS + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/widgetCatalog/" + widgetId, + HttpMethod.DELETE, new HttpEntity(WidgetServiceHeaders.getInstance()), String.class); + } + + @RequestMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" }, method = RequestMethod.POST) + public String updateWidgetCatalogWithFiles(HttpServletRequest request, HttpServletResponse response, + @PathVariable("widgetId") long widgetId) throws RestClientException, Exception { + MultipartHttpServletRequest mRequest; + MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>(); + String fileName; + String tmp_folder = "/tmp/"; + String respond = null; + FileOutputStream fo = null; + try { + mRequest = (MultipartHttpServletRequest) request; + MultipartFile mFile = mRequest.getFile("file"); + fileName = mFile.getOriginalFilename(); + fo = new FileOutputStream(tmp_folder + fileName); + fo.write(mFile.getBytes()); + + HttpHeaders header = new HttpHeaders(); + header.setContentType(MediaType.MULTIPART_FORM_DATA); + multipartRequest.add("file", new FileSystemResource(tmp_folder + fileName)); + multipartRequest.add("widget", request.getParameter("newWidget")); + respond = template.postForObject( + HTTPS + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/widgetCatalog/" + widgetId, + new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class); + File f = new File(tmp_folder + fileName); + f.delete(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed", e); + } finally { + try { + if (fo != null) + fo.close(); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed 2", e); + } + } + return respond; + } + + @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.POST) + public String createWidgetCatalog(HttpServletRequest request, HttpServletResponse response) + throws RestClientException, Exception { + MultipartHttpServletRequest mRequest; + MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>(); + String fileName; + String tmp_folder = "/tmp/"; + String respond = null; + FileOutputStream fo = null; + try { + mRequest = (MultipartHttpServletRequest) request; + MultipartFile mFile = mRequest.getFile("file"); + fileName = mFile.getOriginalFilename(); + fo = new FileOutputStream(tmp_folder + fileName); + fo.write(mFile.getBytes()); + + HttpHeaders header = new HttpHeaders(); + header.setContentType(MediaType.MULTIPART_FORM_DATA); + multipartRequest.add("file", new FileSystemResource(tmp_folder + fileName)); + multipartRequest.add("widget", request.getParameter("newWidget")); + + respond = template.postForObject( + HTTPS + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/widgetCatalog", + new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class); + File f = new File(tmp_folder + fileName); + f.delete(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed", e); + } finally { + try { + if (fo != null) + fo.close(); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed 2", e); + } + } + return respond; + } + + @RequestMapping(value = "/portalApi/microservices/{widgetId}/framework.js", method = RequestMethod.GET) + public String getWidgetFramework(HttpServletRequest request, HttpServletResponse response, + @PathVariable("widgetId") long widgetId) throws RestClientException, Exception { + return template.getForObject(HTTPS + + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/" + widgetId + "/framework.js", String.class, + WidgetServiceHeaders.getInstance()); + } + + @RequestMapping(value = "/portalApi/microservices/{widgetId}/controller.js", method = RequestMethod.GET) + public String getWidgetController(HttpServletRequest request, HttpServletResponse response, + @PathVariable("widgetId") long widgetId) throws RestClientException, Exception { + return template.getForObject(HTTPS + + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/" + widgetId + "/controller.js", String.class, + WidgetServiceHeaders.getInstance()); + } + + @RequestMapping(value = "/portalApi/microservices/{widgetId}/style.css", method = RequestMethod.GET) + public String getWidgetCSS(HttpServletRequest request, HttpServletResponse response, + @PathVariable("widgetId") long widgetId) throws RestClientException, Exception { + return template.getForObject(HTTPS + + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/" + widgetId + "/styles.css", String.class, + WidgetServiceHeaders.getInstance()); + } + + @RequestMapping(value = { "/portalApi/microservices/parameters/{widgetId}" }, method = RequestMethod.GET) + public PortalRestResponse<List<WidgetParameterResult>> getWidgetParameterResult(HttpServletRequest request, + HttpServletResponse response, @PathVariable("widgetId") long widgetId) throws Exception { + EPUser user = EPUserUtils.getUserSession(request); + + List<WidgetParameterResult> list = new ArrayList<>(); + Long serviceId = template.exchange( + HTTPS + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/widgetCatalog/parameters/" + widgetId, + HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class).getBody(); + if (serviceId == null) { + // return ok/sucess and no service parameter for this widget + return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.WARN, + "No service parameters for this widget", list); + } else { + List<MicroserviceParameter> defaultParam = microserviceService.getParametersById(serviceId); + for (MicroserviceParameter param : defaultParam) { + WidgetParameterResult user_result = new WidgetParameterResult(); + user_result.setParam_id(param.getId()); + user_result.setDefault_value(param.getPara_value()); + user_result.setParam_key(param.getPara_key()); + WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(), + param.getId()); + if (userValue == null) + user_result.setUser_value(param.getPara_value()); + else { + user_result.setUser_value(userValue.getUser_value()); + } + list.add(user_result); + } + } + return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.OK, "SUCCESS", list); + } + + @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.GET) + public List<WidgetCatalogParameter> getUserParameterById(HttpServletRequest request, HttpServletResponse response, + @PathVariable("paramId") long paramId) throws Exception { + List<WidgetCatalogParameter> list = widgetParameterService.getUserParameterById(paramId); + return list; + } + + @RequestMapping(value = { "/portalApi/microservices/services/{paramId}" }, method = RequestMethod.DELETE) + public void deleteUserParameterById(HttpServletRequest request, HttpServletResponse response, + @PathVariable("paramId") long paramId) throws Exception { + widgetParameterService.deleteUserParameterById(paramId); + } + + @RequestMapping(value = { "/portalApi/microservices/download/{widgetId}" }, method = RequestMethod.GET) + public void doDownload(HttpServletRequest request, HttpServletResponse response, + @PathVariable("widgetId") long widgetId) throws RestClientException, Exception { + + ServletContext context = request.getServletContext(); + byte[] byteFile = template.exchange( + HTTPS + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/download/" + widgetId, + HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), byte[].class).getBody(); + + File downloadFile = File.createTempFile("temp", ".zip"); + FileOutputStream stream = new FileOutputStream(downloadFile.getPath()); + stream.write(byteFile); + stream.close(); + + FileInputStream inputStream = new FileInputStream(downloadFile); + String mimeType = context.getMimeType(downloadFile.getPath()); + if (mimeType == null) { + mimeType = "application/octet-stream"; + } + + response.setContentType(mimeType); + response.setContentLength((int) downloadFile.length()); + String headerKey = "Content-Disposition"; + String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); + downloadFile.delete(); + response.setHeader(headerKey, headerValue); + + OutputStream outStream = response.getOutputStream(); + byte[] buffer = new byte[32 * 1024]; + int bytesRead = -1; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outStream.write(buffer, 0, bytesRead); + } + + inputStream.close(); + outStream.close(); + } + + @RequestMapping(value = { "/portalApi/microservices/parameters" }, method = RequestMethod.POST) + public PortalRestResponse<String> saveWidgetParameter(HttpServletRequest request, HttpServletResponse response, + @RequestBody WidgetCatalogParameter widgetParameters) throws Exception { + EPUser user = EPUserUtils.getUserSession(request); + widgetParameters.setUserId(user.getId()); + try { + WidgetCatalogParameter oldParam = widgetParameterService.getUserParamById(widgetParameters.getWidgetId(), + widgetParameters.getUserId(), widgetParameters.getParamId()); + if (oldParam != null) { + widgetParameters.setId(oldParam.getId()); + } + widgetParameterService.saveUserParameter(widgetParameters); + + } catch (Exception e) { + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); + } + return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogMarkupController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogMarkupController.java index 78499ef8..b0bc9fc4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogMarkupController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogMarkupController.java @@ -1,83 +1,86 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.controller;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.client.RestClientException;
-import org.springframework.web.client.RestTemplate;
-import org.springframework.web.multipart.commons.CommonsMultipartResolver;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalapp.controller.EPUnRestrictedBaseController;
-import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.service.ConsulHealthService;
-
-@SuppressWarnings("unchecked")
-@RestController
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPAuditLog
-public class WidgetsCatalogMarkupController extends EPUnRestrictedBaseController {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogMarkupController.class);
- RestTemplate template = new RestTemplate();
- String whatService = "widgets-service";
-
-
- @Autowired
- private ConsulHealthService consulHealthService;
-
- @Bean
- public CommonsMultipartResolver multipartResolver() {
- return new CommonsMultipartResolver();
- }
-
- static {
- //for localhost testing only
- javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
- new javax.net.ssl.HostnameVerifier(){
-
- public boolean verify(String hostname,
- javax.net.ssl.SSLSession sslSession) {
- if (hostname.equals("localhost")) {
- return true;
- }
- return false;
- }
- });
- }
-
-
- @RequestMapping(value = "/portalApi/microservices/markup/{widgetId}", method = RequestMethod.GET)
- public String getWidgetMarkup(HttpServletRequest request, HttpServletResponse response,
- @PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
- return template.getForObject("https://" + consulHealthService.getServiceLocation(whatService) + "/widget/microservices/markup/" + widgetId, String.class,
- WidgetServiceHeaders.getInstance());
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPUnRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.ConsulHealthService; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; + +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class WidgetsCatalogMarkupController extends EPUnRestrictedBaseController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogMarkupController.class); + + private RestTemplate template = new RestTemplate(); + + private final String whatService = "widgets-service"; + + @Autowired + private ConsulHealthService consulHealthService; + + @Bean + public CommonsMultipartResolver multipartResolver() { + return new CommonsMultipartResolver(); + } + + static { + // for localhost testing only + javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() { + + public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) { + if (hostname.equals("localhost")) { + return true; + } + return false; + } + }); + } + + @RequestMapping(value = "/portalApi/microservices/markup/{widgetId}", method = RequestMethod.GET) + public String getWidgetMarkup(HttpServletRequest request, HttpServletResponse response, + @PathVariable("widgetId") long widgetId) throws RestClientException, Exception { + return template + .getForObject( + "https://" + + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/markup/" + widgetId, + String.class, WidgetServiceHeaders.getInstance()); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/App.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/App.java index 21068513..794f26c0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/App.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/App.java @@ -1,62 +1,62 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-
-//@Entity
-//@Table(name = "FN_APP")
-public class App implements Serializable{
-
- private static final long serialVersionUID = 1L;
-
- //@Id
- //@Column(name = "APP_ID")
- //@GeneratedValue(strategy=GenerationType.AUTO)
- private Long appId;
-
- //@Column(name = "APP_Name")
- private String appName;
-
- public Long getAppId() {
- return appId;
- }
-
- public void setAppId(Long appId) {
- this.appId = appId;
- }
-
- public String getAppName() {
- return appName;
- }
-
- public void setAppName(String appName) {
- this.appName = appName;
- }
-
-
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +//@Entity +//@Table(name = "FN_APP") +public class App implements Serializable{ + + private static final long serialVersionUID = 1L; + + //@Id + //@Column(name = "APP_ID") + //@GeneratedValue(strategy=GenerationType.AUTO) + private Long appId; + + //@Column(name = "APP_Name") + private String appName; + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/AppContactUs.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/AppContactUs.java index d399c825..be3baa0c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/AppContactUs.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/AppContactUs.java @@ -1,86 +1,86 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-/**
- * Models rows in the fn_app_contact_us table added for 1610.1.
- */
-public class AppContactUs extends DomainVo {
-
- private static final long serialVersionUID = -2742197830465055134L;
-
- private EPApp app;
- private String description;
- private String contactEmail;
- private String contactName;
- private String url;
- private String activeYN;
-
- public EPApp getApp() {
- return app;
- }
-
- public void setApp(EPApp app) {
- this.app = app;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getContactEmail() {
- return contactEmail;
- }
-
- public void setContactEmail(String contactEmail) {
- this.contactEmail = contactEmail;
- }
-
- public String getContactName() {
- return contactName;
- }
-
- public void setContactName(String contactName) {
- this.contactName = contactName;
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public String getActiveYN() {
- return activeYN;
- }
-
- public void setActiveYN(String activeYN) {
- this.activeYN = activeYN;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +/** + * Models rows in the fn_app_contact_us table added for 1610.1. + */ +public class AppContactUs extends DomainVo { + + private static final long serialVersionUID = -2742197830465055134L; + + private EPApp app; + private String description; + private String contactEmail; + private String contactName; + private String url; + private String activeYN; + + public EPApp getApp() { + return app; + } + + public void setApp(EPApp app) { + this.app = app; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getContactEmail() { + return contactEmail; + } + + public void setContactEmail(String contactEmail) { + this.contactEmail = contactEmail; + } + + public String getContactName() { + return contactName; + } + + public void setContactName(String contactName) { + this.contactName = contactName; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getActiveYN() { + return activeYN; + } + + public void setActiveYN(String activeYN) { + this.activeYN = activeYN; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/AppIdAndNameTransportModel.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/AppIdAndNameTransportModel.java index 1440973e..3efa26a3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/AppIdAndNameTransportModel.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/AppIdAndNameTransportModel.java @@ -1,63 +1,63 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-@Entity
-public class AppIdAndNameTransportModel implements Serializable{
- private static final long serialVersionUID = 1L;
-
- @Id
- @Column(name="APP_ID")
- private Long id;
-
- @Column(name="APP_NAME")
- private String name;
-
- @Column(name="APP_TYPE")
- private Integer appType;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public Boolean isRestrictedApp() {
- return (this.appType == 2 ? true : false);
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class AppIdAndNameTransportModel implements Serializable{ + private static final long serialVersionUID = 1L; + + @Id + @Column(name="APP_ID") + private Long id; + + @Column(name="APP_NAME") + private String name; + + @Column(name="APP_TYPE") + private Integer appType; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Boolean isRestrictedApp() { + return (this.appType == 2 ? true : false); + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/AppsResponse.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/AppsResponse.java index 4935a22c..05fc5fe4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/AppsResponse.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/AppsResponse.java @@ -1,76 +1,76 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-public class AppsResponse {
-
- public AppsResponse(Long id, String name, Boolean restrictedApp, Boolean enabled) {
- this.index = id;
- this.title = this.value = name;
- this.restrictedApp = restrictedApp;
- this.enabled = enabled;
- }
-
- public Long getIndex() {
- return index;
- }
-
- public void setIndex(Long index) {
- this.index = index;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getValue() {
- return value;
- }
-
- public void setValue(String value) {
- this.value = value;
- }
-
- // Hide the implementation of restricted and normal app from the front end.
- // The json sent and received will include restrictedApp but not appType.
-
- public void setRestrictedApp(Boolean restrictedApp) {
- this.restrictedApp = restrictedApp;
- }
-
- public Boolean getEnabled() {
- return enabled;
- }
-
- public void setEnabled(Boolean enabled) {
- this.enabled = enabled;
- }
-
- private Long index;
- private String title;
- private String value;
- public Boolean restrictedApp;
- public Boolean enabled;
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +public class AppsResponse { + + public AppsResponse(Long id, String name, Boolean restrictedApp, Boolean enabled) { + this.index = id; + this.title = this.value = name; + this.restrictedApp = restrictedApp; + this.enabled = enabled; + } + + public Long getIndex() { + return index; + } + + public void setIndex(Long index) { + this.index = index; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + // Hide the implementation of restricted and normal app from the front end. + // The json sent and received will include restrictedApp but not appType. + + public void setRestrictedApp(Boolean restrictedApp) { + this.restrictedApp = restrictedApp; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + private Long index; + private String title; + private String value; + public Boolean restrictedApp; + public Boolean enabled; + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/BEProperty.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/BEProperty.java index e877641b..a5b5c0c6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/BEProperty.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/BEProperty.java @@ -1,43 +1,78 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-public class BEProperty {
- private String key;
- private String value;
-
- public BEProperty(String key, String value){
- this.key = key;
- this.value = value;
- }
-
- public String getKey() {
- return key;
- }
- public void setKey(String key) {
- this.key = key;
- }
- public String getValue() {
- return value;
- }
- public void setValue(String value) {
- this.value = value;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +public class BEProperty { + private String key; + private String value; + + public BEProperty(String key, String value) { + this.key = key; + this.value = value; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((key == null) ? 0 : key.hashCode()); + result = prime * result + ((value == null) ? 0 : value.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BEProperty other = (BEProperty) obj; + if (key == null) { + if (other.key != null) + return false; + } else if (!key.equals(other.key)) + return false; + if (value == null) { + if (other.value != null) + return false; + } else if (!value.equals(other.value)) + return false; + return true; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java index 1ba9e2d7..b0cd13b2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java @@ -1,292 +1,292 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import javax.persistence.Lob;
-
-import org.apache.commons.lang.StringUtils;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-/**
- * Model for all columns in the fn_app table.
- */
-public class EPApp extends DomainVo {
-
- private static final long serialVersionUID = 1L;
-
- private String name;
- private String imageUrl;
- private String description;
- private String notes;
- private String url;
- private String alternateUrl;
- private String appRestEndpoint;
- private String mlAppName;
- private String mlAppAdminId;
- private Long motsId;
- private String username;
- private String appPassword;
- @Lob
- private byte[] thumbnail;
- private Boolean open;
- private Boolean enabled;
- private String uebTopicName;
- private String uebKey;
- private String uebSecret;
- private Integer appType;
-
- private AppContactUs contactUs;
-
- public EPApp() {
- // Attention!!!
- // We set here all default values. We also place protection
- // into setters for fields with default values.
- // If we don't use such protection we are able to place null
- // to these fields and save such fields into DB even if DB has
- // default values for these fields.
- this.name = "";
- this.mlAppName = "";
- this.mlAppAdminId = "";
- this.username = "";
- this.appPassword = "";
- this.open = new Boolean(false);
- this.enabled = new Boolean(true);
- this.uebTopicName = "";
- this.uebKey = "";
- this.uebSecret = "";
- this.appType = 1;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- if (StringUtils.isEmpty(name)) {
- name = "";
- }
- this.name = name;
- }
-
- public String getImageUrl() {
- return imageUrl;
- }
-
- public void setImageUrl(String imageUrl) {
- this.imageUrl = imageUrl;
- }
-
- public byte[] getThumbnail() {
- return this.thumbnail;
- }
-
- public void setThumbnail(byte[] thumbnail) {
- this.thumbnail = thumbnail;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getNotes() {
- return notes;
- }
-
- public void setNotes(String notes) {
- this.notes = notes;
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public String getAlternateUrl() {
- return alternateUrl;
- }
-
- public void setAlternateUrl(String alternateUrl) {
- this.alternateUrl = alternateUrl;
- }
-
- public String getAppRestEndpoint() {
- return appRestEndpoint;
- }
-
- public void setAppRestEndpoint(String appRestEndpoint) {
- this.appRestEndpoint = appRestEndpoint;
- }
-
- public String getMlAppName() {
- return mlAppName;
- }
-
- public void setMlAppName(String mlAppName) {
- if (StringUtils.isEmpty(mlAppName)) {
- mlAppName = "";
- }
- this.mlAppName = mlAppName;
- }
-
- public String getMlAppAdminId() {
- return mlAppAdminId;
- }
-
- public void setMlAppAdminId(String mlAppAdminId) {
- if (StringUtils.isEmpty(mlAppAdminId)) {
- mlAppAdminId = "";
- }
- this.mlAppAdminId = mlAppAdminId;
- }
-
- public Long getMotsId() {
- return motsId;
- }
-
- public void setMotsId(Long motsId) {
- this.motsId = motsId;
- }
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getAppPassword() {
- return appPassword;
- }
-
- public void setAppPassword(String appPassword) {
- if (StringUtils.isEmpty(appPassword)) {
- appPassword = "";
- }
- this.appPassword = appPassword;
- }
-
- public Boolean getOpen() {
- return open;
- }
-
- public void setOpen(Boolean open) {
- if (open == null) {
- open = new Boolean(false);
- }
- this.open = open;
- }
-
- public Boolean getEnabled() {
- return enabled;
- }
-
- public void setEnabled(Boolean enabled) {
- if (enabled == null) {
- enabled = new Boolean(true);
- }
- this.enabled = enabled;
- }
-
- public Integer getAppType() {
- return appType;
- }
-
- public void setAppType(Integer appType) {
- if (appType == null) {
- appType = new Integer(1);
- }
- this.appType = appType;
- }
-
- public void setRestrictedApp(Boolean restrictedApp) {
- Integer result = 1;
- if (restrictedApp) {
- result = 2;
- }
- this.appType = result;
- }
-
- public Boolean isRestrictedApp() {
- return (this.appType == 2 ? true : false);
- }
-
- public int compareTo(Object obj) {
- Long c1 = getId();
- Long c2 = ((EPApp) obj).getId();
-
- return c1.compareTo(c2);
- }
-
- public String getUebTopicName() {
- return this.uebTopicName;
- }
-
- public void setUebTopicName(String topicName) {
- if (StringUtils.isEmpty(topicName)) {
- this.uebTopicName = "";
- }
- this.uebTopicName = topicName;
- }
-
- public String getUebKey() {
- return this.uebKey;
- }
-
- public void setUebKey(String uebKey) {
- if (StringUtils.isEmpty(uebKey)) {
- this.uebKey = "";
- }
- this.uebKey = uebKey;
- }
-
- public String getUebSecret() {
- return this.uebSecret;
- }
-
- public void setUebSecret(String uebSecret) {
- if (StringUtils.isEmpty(uebSecret)) {
- this.uebSecret = "";
- }
- this.uebSecret = uebSecret;
- }
-
- public AppContactUs getContactUs() {
- return contactUs;
- }
-
- public void setContactUs(AppContactUs contactUs) {
- this.contactUs = contactUs;
- }
-
- @Override
- public String toString() {
- String str = "[" + getId() + ":" + getName() + "]";
- return str;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import javax.persistence.Lob; + +import org.apache.commons.lang.StringUtils; +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +/** + * Model for all columns in the fn_app table. + */ +public class EPApp extends DomainVo { + + private static final long serialVersionUID = 1L; + + private String name; + private String imageUrl; + private String description; + private String notes; + private String url; + private String alternateUrl; + private String appRestEndpoint; + private String mlAppName; + private String mlAppAdminId; + private Long motsId; + private String username; + private String appPassword; + @Lob + private byte[] thumbnail; + private Boolean open; + private Boolean enabled; + private String uebTopicName; + private String uebKey; + private String uebSecret; + private Integer appType; + + private AppContactUs contactUs; + + public EPApp() { + // Attention!!! + // We set here all default values. We also place protection + // into setters for fields with default values. + // If we don't use such protection we are able to place null + // to these fields and save such fields into DB even if DB has + // default values for these fields. + this.name = ""; + this.mlAppName = ""; + this.mlAppAdminId = ""; + this.username = ""; + this.appPassword = ""; + this.open = new Boolean(false); + this.enabled = new Boolean(true); + this.uebTopicName = ""; + this.uebKey = ""; + this.uebSecret = ""; + this.appType = 1; + } + + public String getName() { + return name; + } + + public void setName(String name) { + if (StringUtils.isEmpty(name)) { + name = ""; + } + this.name = name; + } + + public String getImageUrl() { + return imageUrl; + } + + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } + + public byte[] getThumbnail() { + return this.thumbnail; + } + + public void setThumbnail(byte[] thumbnail) { + this.thumbnail = thumbnail; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getNotes() { + return notes; + } + + public void setNotes(String notes) { + this.notes = notes; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getAlternateUrl() { + return alternateUrl; + } + + public void setAlternateUrl(String alternateUrl) { + this.alternateUrl = alternateUrl; + } + + public String getAppRestEndpoint() { + return appRestEndpoint; + } + + public void setAppRestEndpoint(String appRestEndpoint) { + this.appRestEndpoint = appRestEndpoint; + } + + public String getMlAppName() { + return mlAppName; + } + + public void setMlAppName(String mlAppName) { + if (StringUtils.isEmpty(mlAppName)) { + mlAppName = ""; + } + this.mlAppName = mlAppName; + } + + public String getMlAppAdminId() { + return mlAppAdminId; + } + + public void setMlAppAdminId(String mlAppAdminId) { + if (StringUtils.isEmpty(mlAppAdminId)) { + mlAppAdminId = ""; + } + this.mlAppAdminId = mlAppAdminId; + } + + public Long getMotsId() { + return motsId; + } + + public void setMotsId(Long motsId) { + this.motsId = motsId; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getAppPassword() { + return appPassword; + } + + public void setAppPassword(String appPassword) { + if (StringUtils.isEmpty(appPassword)) { + appPassword = ""; + } + this.appPassword = appPassword; + } + + public Boolean getOpen() { + return open; + } + + public void setOpen(Boolean open) { + if (open == null) { + open = new Boolean(false); + } + this.open = open; + } + + public Boolean getEnabled() { + return enabled; + } + + public void setEnabled(Boolean enabled) { + if (enabled == null) { + enabled = new Boolean(true); + } + this.enabled = enabled; + } + + public Integer getAppType() { + return appType; + } + + public void setAppType(Integer appType) { + if (appType == null) { + appType = new Integer(1); + } + this.appType = appType; + } + + public void setRestrictedApp(Boolean restrictedApp) { + Integer result = 1; + if (restrictedApp) { + result = 2; + } + this.appType = result; + } + + public Boolean isRestrictedApp() { + return (this.appType == 2 ? true : false); + } + + public int compareTo(Object obj) { + Long c1 = getId(); + Long c2 = ((EPApp) obj).getId(); + + return c1.compareTo(c2); + } + + public String getUebTopicName() { + return this.uebTopicName; + } + + public void setUebTopicName(String topicName) { + if (StringUtils.isEmpty(topicName)) { + this.uebTopicName = ""; + } + this.uebTopicName = topicName; + } + + public String getUebKey() { + return this.uebKey; + } + + public void setUebKey(String uebKey) { + if (StringUtils.isEmpty(uebKey)) { + this.uebKey = ""; + } + this.uebKey = uebKey; + } + + public String getUebSecret() { + return this.uebSecret; + } + + public void setUebSecret(String uebSecret) { + if (StringUtils.isEmpty(uebSecret)) { + this.uebSecret = ""; + } + this.uebSecret = uebSecret; + } + + public AppContactUs getContactUs() { + return contactUs; + } + + public void setContactUs(AppContactUs contactUs) { + this.contactUs = contactUs; + } + + @Override + public String toString() { + String str = "[" + getId() + ":" + getName() + "]"; + return str; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPRole.java index ea70982a..a1e44575 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPRole.java @@ -1,202 +1,202 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.util.Iterator;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-import com.fasterxml.jackson.annotation.JsonIgnore;
-
-public class EPRole extends DomainVo {
-
- private static final long serialVersionUID = 1L;
- private String name;
- private boolean active;
- private Integer priority;
-
- // ECOMP will identify the specific remote application role id by appID;appRoleId among all the application roles it persists.
- private Long appId; // used by ECOMP only
- private Long appRoleId; // used by ECOMP only
-
- private SortedSet<RoleFunction> roleFunctions = new TreeSet<RoleFunction>();
-
- private SortedSet<EPRole> childRoles = new TreeSet<EPRole>();
-
- @JsonIgnore
- private SortedSet<EPRole> parentRoles = new TreeSet<EPRole>();
-
- public EPRole() {}
-
- public String getName() {
- return name;
- }
-
- public boolean getActive() {
- return active;
- }
-
- public SortedSet<RoleFunction> getRoleFunctions() {
- return roleFunctions;
- }
-
- public Integer getPriority() {
- return priority;
- }
-
- public SortedSet<EPRole> getChildRoles() {
- return childRoles;
- }
-
- public SortedSet<EPRole> getParentRoles() {
- return parentRoles;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public void setActive(boolean active) {
- this.active = active;
- }
-
- public void setRoleFunctions(SortedSet<RoleFunction> roleFunctions) {
- this.roleFunctions = roleFunctions;
- }
-
- public void setPriority(Integer priority) {
- this.priority = priority;
- }
-
- public void setChildRoles(SortedSet<EPRole> childRoles) {
- this.childRoles = childRoles;
- }
-
- public void setParentRoles(SortedSet<EPRole> parentRoles) {
- this.parentRoles = parentRoles;
- }
-
- public void addRoleFunction(RoleFunction roleFunction) {
- this.roleFunctions.add(roleFunction);
- }
-
- public void addChildRole(EPRole role) {
- this.childRoles.add(role);
- }
-
- public void addParentRole(EPRole role) {
- this.parentRoles.add(role);
- }
-
- public String getEditUrl() {
- return "/role.htm?role_id=" + getId();
- }
-
- public String getToggleActiveImage() {
- return "/static/fusion/images/" + (getActive() ? "active.png" : "inactive.png" );
- }
-
- public String getToggleActiveAltText() {
- return getActive() ? "Click to Deactivate Role" : "Click to Activate Role";
- }
-
- public void removeChildRole(Long roleId) {
- Iterator<EPRole> i = this.childRoles.iterator();
-
- while (i.hasNext()) {
- EPRole childRole = (EPRole)i.next();
- if (childRole.getId().equals(roleId)) {
- this.childRoles.remove(childRole);
- break;
- }
- }
- }
-
- public void removeParentRole(Long roleId) {
- Iterator<EPRole> i = this.parentRoles.iterator();
-
- while (i.hasNext()) {
- EPRole parentRole = (EPRole)i.next();
- if (parentRole.getId().equals(roleId)) {
- this.parentRoles.remove(parentRole);
- break;
- }
- }
- }
-
- public void removeRoleFunction(String roleFunctionCd) {
- Iterator<RoleFunction> i = this.roleFunctions.iterator();
-
- while (i.hasNext()) {
- RoleFunction roleFunction = (RoleFunction)i.next();
- if (roleFunction.getCode().equals(roleFunctionCd)) {
- this.roleFunctions.remove(roleFunction);
- break;
- }
- }
- }
-
- public int compareTo(Object obj){
- EPRole other = (EPRole)obj;
-
- if(this.appId == null)
- if(other.getAppId() == null)
- return compareByName(other); //equal
- else
- return -1;
- else // this.appId != null
- if(other.getAppId() == null)
- return 1; // appId != null, but others is null
- else{
- int appIdCompareResult = appId.compareTo(other.getAppId());
- return appIdCompareResult == 0? compareByName(other) : appIdCompareResult;
- }
- }
-
- private int compareByName(EPRole other) {
- String c1 = getName();
- String c2 = other.getName();
-
- return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
- }
-
- public Long getAppId() {
- return appId;
- }
-
- public void setAppId(Long appId) {
- this.appId = appId;
- }
-
- public Long getAppRoleId() {
- return appRoleId;
- }
-
- public void setAppRoleId(Long appRoleId) {
- this.appRoleId = appRoleId;
- }
-
- @Override
- public String toString() {
- return "[Id = " + id + ", name = " + name + "]";
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.util.Iterator; +import java.util.SortedSet; +import java.util.TreeSet; + +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.domain.support.DomainVo; +import com.fasterxml.jackson.annotation.JsonIgnore; + +public class EPRole extends DomainVo { + + private static final long serialVersionUID = 1L; + private String name; + private boolean active; + private Integer priority; + + // ECOMP will identify the specific remote application role id by appID;appRoleId among all the application roles it persists. + private Long appId; // used by ECOMP only + private Long appRoleId; // used by ECOMP only + + private SortedSet<RoleFunction> roleFunctions = new TreeSet<RoleFunction>(); + + private SortedSet<EPRole> childRoles = new TreeSet<EPRole>(); + + @JsonIgnore + private SortedSet<EPRole> parentRoles = new TreeSet<EPRole>(); + + public EPRole() {} + + public String getName() { + return name; + } + + public boolean getActive() { + return active; + } + + public SortedSet<RoleFunction> getRoleFunctions() { + return roleFunctions; + } + + public Integer getPriority() { + return priority; + } + + public SortedSet<EPRole> getChildRoles() { + return childRoles; + } + + public SortedSet<EPRole> getParentRoles() { + return parentRoles; + } + + public void setName(String name) { + this.name = name; + } + + public void setActive(boolean active) { + this.active = active; + } + + public void setRoleFunctions(SortedSet<RoleFunction> roleFunctions) { + this.roleFunctions = roleFunctions; + } + + public void setPriority(Integer priority) { + this.priority = priority; + } + + public void setChildRoles(SortedSet<EPRole> childRoles) { + this.childRoles = childRoles; + } + + public void setParentRoles(SortedSet<EPRole> parentRoles) { + this.parentRoles = parentRoles; + } + + public void addRoleFunction(RoleFunction roleFunction) { + this.roleFunctions.add(roleFunction); + } + + public void addChildRole(EPRole role) { + this.childRoles.add(role); + } + + public void addParentRole(EPRole role) { + this.parentRoles.add(role); + } + + public String getEditUrl() { + return "/role.htm?role_id=" + getId(); + } + + public String getToggleActiveImage() { + return "/static/fusion/images/" + (getActive() ? "active.png" : "inactive.png" ); + } + + public String getToggleActiveAltText() { + return getActive() ? "Click to Deactivate Role" : "Click to Activate Role"; + } + + public void removeChildRole(Long roleId) { + Iterator<EPRole> i = this.childRoles.iterator(); + + while (i.hasNext()) { + EPRole childRole = (EPRole)i.next(); + if (childRole.getId().equals(roleId)) { + this.childRoles.remove(childRole); + break; + } + } + } + + public void removeParentRole(Long roleId) { + Iterator<EPRole> i = this.parentRoles.iterator(); + + while (i.hasNext()) { + EPRole parentRole = (EPRole)i.next(); + if (parentRole.getId().equals(roleId)) { + this.parentRoles.remove(parentRole); + break; + } + } + } + + public void removeRoleFunction(String roleFunctionCd) { + Iterator<RoleFunction> i = this.roleFunctions.iterator(); + + while (i.hasNext()) { + RoleFunction roleFunction = (RoleFunction)i.next(); + if (roleFunction.getCode().equals(roleFunctionCd)) { + this.roleFunctions.remove(roleFunction); + break; + } + } + } + + public int compareTo(Object obj){ + EPRole other = (EPRole)obj; + + if(this.appId == null) + if(other.getAppId() == null) + return compareByName(other); //equal + else + return -1; + else // this.appId != null + if(other.getAppId() == null) + return 1; // appId != null, but others is null + else{ + int appIdCompareResult = appId.compareTo(other.getAppId()); + return appIdCompareResult == 0? compareByName(other) : appIdCompareResult; + } + } + + private int compareByName(EPRole other) { + String c1 = getName(); + String c2 = other.getName(); + + return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + } + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public Long getAppRoleId() { + return appRoleId; + } + + public void setAppRoleId(Long appRoleId) { + this.appRoleId = appRoleId; + } + + @Override + public String toString() { + return "[Id = " + id + ", name = " + name + "]"; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserApp.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserApp.java index 9ed62d8b..005d5328 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserApp.java @@ -1,119 +1,119 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-
-@SuppressWarnings("rawtypes")
-public class EPUserApp implements java.io.Serializable, Comparable {
-
- private static final long serialVersionUID = 1L;
-
- private Long userId;
- private EPApp app;
- private EPRole role;
- private Short priority;
-
- public EPUserApp() {
- }
-
- public Long getAppId() {
- return this.getApp().getId();
- }
-
- public Long getRoleId() {
- return (role == null) ? null : role.getId();
- }
-
- public Long getAppRoleId() {
- return (role.getAppRoleId() == null) ? null : role.getAppRoleId();
- }
-
- @Override
- public String toString() {
- String str = "[u: "+getUserId()+"; a: "+getAppId()+", r: "+getRoleId()+"; appRoleId: "+getAppRoleId()+"]";
- return str;
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public void setUserId(Long id) {
- this.userId = id;
- }
-
- public EPApp getApp() {
- return app;
- }
-
- public void setApp(EPApp app) {
- this.app = app;
- }
-
- public EPRole getRole() {
- return role;
- }
-
- public void setRole(EPRole role) {
- this.role = role;
- }
-
- public Short getPriority() {
- return this.priority;
- }
-
- public void setPriority(Short priority) {
- this.priority = priority;
- }
-
- public boolean equals(Object other) {
- if ((this == other))
- return true;
- if ((other == null))
- return false;
- if (!(other instanceof EPUserApp))
- return false;
- EPUserApp castOther = (EPUserApp) other;
-
- return (this.getUserId().equals(castOther.getUserId()))
- && (this.getApp().getId().equals(castOther.getApp().getId()))
- && (this.getRole().getId().equals(castOther.getRole().getId()))
- && ((this.priority==null && castOther.getPriority()==null) || this.getPriority().equals(castOther.getPriority()));
- }
-
- public int hashCode() {
- int result = 17;
-
- result = 37 * result + (int) (this.getUserId()==null ? 0 : this.getUserId().intValue());
- result = 37 * result + (int) (this.getApp().getId()==null ? 0 : this.getApp().getId().intValue());
- result = 37 * result + (int) (this.getRole().getId()==null ? 0 : this.getRole().getId().intValue());
- result = 37 * result + (int) (this.priority==null ? 0 : this.priority);
- return result;
- }
-
- public int compareTo(Object other){
- EPUserApp castOther = (EPUserApp) other;
-
- Long c1 = (this.getUserId()==null ? 0 : this.getUserId()) + (this.getApp()==null||this.getApp().getId()==null ? 0 : this.getApp().getId()) + (this.getRole()==null||this.getRole().getId()==null ? 0 : this.getRole().getId()) + (this.priority==null ? 0 : this.priority);
- Long c2 = (castOther.getUserId()==null ? 0 : castOther.getUserId()) + (castOther.getApp()==null||castOther.getApp().getId()==null ? 0 : castOther.getApp().getId()) + (castOther.getRole()==null||castOther.getRole().getId()==null ? 0 : castOther.getRole().getId()) + (castOther.priority==null ? 0 : castOther.priority);
-
- return c1.compareTo(c2);
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + + +@SuppressWarnings("rawtypes") +public class EPUserApp implements java.io.Serializable, Comparable { + + private static final long serialVersionUID = 1L; + + private Long userId; + private EPApp app; + private EPRole role; + private Short priority; + + public EPUserApp() { + } + + public Long getAppId() { + return this.getApp().getId(); + } + + public Long getRoleId() { + return (role == null) ? null : role.getId(); + } + + public Long getAppRoleId() { + return (role.getAppRoleId() == null) ? null : role.getAppRoleId(); + } + + @Override + public String toString() { + String str = "[u: "+getUserId()+"; a: "+getAppId()+", r: "+getRoleId()+"; appRoleId: "+getAppRoleId()+"]"; + return str; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long id) { + this.userId = id; + } + + public EPApp getApp() { + return app; + } + + public void setApp(EPApp app) { + this.app = app; + } + + public EPRole getRole() { + return role; + } + + public void setRole(EPRole role) { + this.role = role; + } + + public Short getPriority() { + return this.priority; + } + + public void setPriority(Short priority) { + this.priority = priority; + } + + public boolean equals(Object other) { + if ((this == other)) + return true; + if ((other == null)) + return false; + if (!(other instanceof EPUserApp)) + return false; + EPUserApp castOther = (EPUserApp) other; + + return (this.getUserId().equals(castOther.getUserId())) + && (this.getApp().getId().equals(castOther.getApp().getId())) + && (this.getRole().getId().equals(castOther.getRole().getId())) + && ((this.priority==null && castOther.getPriority()==null) || this.getPriority().equals(castOther.getPriority())); + } + + public int hashCode() { + int result = 17; + + result = 37 * result + (int) (this.getUserId()==null ? 0 : this.getUserId().intValue()); + result = 37 * result + (int) (this.getApp().getId()==null ? 0 : this.getApp().getId().intValue()); + result = 37 * result + (int) (this.getRole().getId()==null ? 0 : this.getRole().getId().intValue()); + result = 37 * result + (int) (this.priority==null ? 0 : this.priority); + return result; + } + + public int compareTo(Object other){ + EPUserApp castOther = (EPUserApp) other; + + Long c1 = (this.getUserId()==null ? 0 : this.getUserId()) + (this.getApp()==null||this.getApp().getId()==null ? 0 : this.getApp().getId()) + (this.getRole()==null||this.getRole().getId()==null ? 0 : this.getRole().getId()) + (this.priority==null ? 0 : this.priority); + Long c2 = (castOther.getUserId()==null ? 0 : castOther.getUserId()) + (castOther.getApp()==null||castOther.getApp().getId()==null ? 0 : castOther.getApp().getId()) + (castOther.getRole()==null||castOther.getRole().getId()==null ? 0 : castOther.getRole().getId()) + (castOther.priority==null ? 0 : castOther.priority); + + return c1.compareTo(c2); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppCatalogRoles.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppCatalogRoles.java index 89411ea5..db041857 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppCatalogRoles.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppCatalogRoles.java @@ -1,92 +1,92 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-@Entity
-@JsonInclude
-public class EPUserAppCatalogRoles extends DomainVo {
-
- private static final long serialVersionUID = -5259869298825093816L;
-
-
- @Id
- @Column(name="requested_role_id")
- public Long requestedRoleId;
-
-
- @Id
- @Column(name="role_name")
- public String rolename;
-
- @Id
- @Column(name="request_status")
- public String requestStatus;
-
- @Id
- @Column(name="app_id")
- public Long appId;
-
- public Long getRequestedRoleId() {
- return requestedRoleId;
- }
-
- public void setRequestedRoleId(Long requestedRoleId) {
- this.requestedRoleId = requestedRoleId;
- }
-
- public String getRolename() {
- return rolename;
- }
-
- public void setRolename(String rolename) {
- this.rolename = rolename;
- }
-
- public String getRequestStatus() {
- return requestStatus;
- }
-
- public void setRequestStatus(String requestStatus) {
- this.requestStatus = requestStatus;
- }
-
- public Long getAppId() {
- return appId;
- }
-
- public void setAppId(Long appId) {
- this.appId = appId;
- }
-
- public String toString() {
- return "EPUserAppCatalogRoles [requestedRoleId=" + requestedRoleId + ", rolename=" + rolename
- + ", requestStatus=" + requestStatus + ", appId=" + appId + "]";
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@Entity +@JsonInclude +public class EPUserAppCatalogRoles extends DomainVo { + + private static final long serialVersionUID = -5259869298825093816L; + + + @Id + @Column(name="requested_role_id") + public Long requestedRoleId; + + + @Id + @Column(name="role_name") + public String rolename; + + @Id + @Column(name="request_status") + public String requestStatus; + + @Id + @Column(name="app_id") + public Long appId; + + public Long getRequestedRoleId() { + return requestedRoleId; + } + + public void setRequestedRoleId(Long requestedRoleId) { + this.requestedRoleId = requestedRoleId; + } + + public String getRolename() { + return rolename; + } + + public void setRolename(String rolename) { + this.rolename = rolename; + } + + public String getRequestStatus() { + return requestStatus; + } + + public void setRequestStatus(String requestStatus) { + this.requestStatus = requestStatus; + } + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public String toString() { + return "EPUserAppCatalogRoles [requestedRoleId=" + requestedRoleId + ", rolename=" + rolename + + ", requestStatus=" + requestStatus + ", appId=" + appId + "]"; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequest.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequest.java index 1d73945e..c756ef58 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequest.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequest.java @@ -1,87 +1,85 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-
-import java.util.Date;
-import java.util.Set;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-
-public class EPUserAppRolesRequest extends DomainVo {
-
- private static final long serialVersionUID = -7225288307806389019L;
- private Long userId;
- private Long appId;
- private Date createdDate;
- private Date updatedDate;
- private String requestStatus;
-
- private Set<EPUserAppRolesRequestDetail> epRequestIdDetail;
-
- public final Long getUserId() {
- return userId;
- }
-
- public final void setUserId(Long userId) {
- this.userId = userId;
- }
-
- public final Long getAppId() {
- return appId;
- }
-
- public final void setAppId(Long appId) {
- this.appId = appId;
- }
-
- public final Date getCreatedDate() {
- return createdDate;
- }
-
- public final void setCreatedDate(Date createdDate) {
- this.createdDate = createdDate;
- }
-
- public final Date getUpdatedDate() {
- return updatedDate;
- }
-
- public final void setUpdatedDate(Date updatedDate) {
- this.updatedDate = updatedDate;
- }
-
- public final String getRequestStatus() {
- return requestStatus;
- }
-
- public final void setRequestStatus(String requestStatus) {
- this.requestStatus = requestStatus;
- }
-
- public final Set<EPUserAppRolesRequestDetail> getEpRequestIdDetail() {
- return epRequestIdDetail;
- }
-
- public final void setEpRequestIdDetail(Set<EPUserAppRolesRequestDetail> epMyLoginsDetail) {
- this.epRequestIdDetail = epMyLoginsDetail;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.util.Date; +import java.util.Set; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class EPUserAppRolesRequest extends DomainVo { + + private static final long serialVersionUID = -7225288307806389019L; + private Long userId; + private Long appId; + private Date createdDate; + private Date updatedDate; + private String requestStatus; + + private Set<EPUserAppRolesRequestDetail> epRequestIdDetail; + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public Date getUpdatedDate() { + return updatedDate; + } + + public void setUpdatedDate(Date updatedDate) { + this.updatedDate = updatedDate; + } + + public String getRequestStatus() { + return requestStatus; + } + + public void setRequestStatus(String requestStatus) { + this.requestStatus = requestStatus; + } + + public Set<EPUserAppRolesRequestDetail> getEpRequestIdDetail() { + return epRequestIdDetail; + } + + public void setEpRequestIdDetail(Set<EPUserAppRolesRequestDetail> epMyLoginsDetail) { + this.epRequestIdDetail = epMyLoginsDetail; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequestDetail.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequestDetail.java index d7989bcd..3b466f52 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequestDetail.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequestDetail.java @@ -1,52 +1,56 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-public class EPUserAppRolesRequestDetail extends DomainVo{
-
- private static final long serialVersionUID = -4908856671135348157L;
-
- private Long reqRoleId;
- private String reqType;
- private EPUserAppRolesRequest epRequestIdData;
-
- public final EPUserAppRolesRequest getEpRequestIdData() {
- return epRequestIdData;
- }
- public final void setEpRequestIdData(EPUserAppRolesRequest epRequestIdData) {
- this.epRequestIdData = epRequestIdData;
- }
- public final Long getReqRoleId() {
- return reqRoleId;
- }
- public final void setReqRoleId(Long reqRoleId) {
- this.reqRoleId = reqRoleId;
- }
- public final String getReqType() {
- return reqType;
- }
- public final void setReqType(String reqType) {
- this.reqType = reqType;
- }
-
-}
-
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class EPUserAppRolesRequestDetail extends DomainVo { + + private static final long serialVersionUID = -4908856671135348157L; + + private Long reqRoleId; + private String reqType; + private EPUserAppRolesRequest epRequestIdData; + + public EPUserAppRolesRequest getEpRequestIdData() { + return epRequestIdData; + } + + public void setEpRequestIdData(EPUserAppRolesRequest epRequestIdData) { + this.epRequestIdData = epRequestIdData; + } + + public Long getReqRoleId() { + return reqRoleId; + } + + public void setReqRoleId(Long reqRoleId) { + this.reqRoleId = reqRoleId; + } + + public String getReqType() { + return reqType; + } + + public void setReqType(String reqType) { + this.reqType = reqType; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppsManualSortPreference.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppsManualSortPreference.java index 30d69bab..6c150535 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppsManualSortPreference.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppsManualSortPreference.java @@ -1,50 +1,50 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-public class EPUserAppsManualSortPreference extends DomainVo {
-
- private static final long serialVersionUID = -6270136291139278216L;
- private int userId;
- private Long appId;
- private int appManualSortOrder;
-
- public int getUserId() {
- return userId;
- }
- public void setUserId(int userId) {
- this.userId = userId;
- }
- public Long getAppId() {
- return appId;
- }
- public void setAppId(Long appId) {
- this.appId = appId;
- }
- public int getAppManualSortOrder() {
- return appManualSortOrder;
- }
- public void setAppManualSortOrder(int appManualSortOrder) {
- this.appManualSortOrder = appManualSortOrder;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class EPUserAppsManualSortPreference extends DomainVo { + + private static final long serialVersionUID = -6270136291139278216L; + private int userId; + private Long appId; + private int appManualSortOrder; + + public int getUserId() { + return userId; + } + public void setUserId(int userId) { + this.userId = userId; + } + public Long getAppId() { + return appId; + } + public void setAppId(Long appId) { + this.appId = appId; + } + public int getAppManualSortOrder() { + return appManualSortOrder; + } + public void setAppManualSortOrder(int appManualSortOrder) { + this.appManualSortOrder = appManualSortOrder; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppsSortPreference.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppsSortPreference.java index 1cab30ff..f906d0c0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppsSortPreference.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppsSortPreference.java @@ -1,44 +1,44 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-public class EPUserAppsSortPreference extends DomainVo{
-
- private static final long serialVersionUID = -5267000174894006433L;
-
- private int userId;
- private String sortPref;
-
- public int getUserId() {
- return userId;
- }
- public void setUserId(final int userId) {
- this.userId = userId;
- }
- public String getSortPref() {
- return sortPref;
- }
- public void setSortPref(final String sortPref) {
- this.sortPref = sortPref;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class EPUserAppsSortPreference extends DomainVo{ + + private static final long serialVersionUID = -5267000174894006433L; + + private int userId; + private String sortPref; + + public int getUserId() { + return userId; + } + public void setUserId(final int userId) { + this.userId = userId; + } + public String getSortPref() { + return sortPref; + } + public void setSortPref(final String sortPref) { + this.sortPref = sortPref; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserNotification.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserNotification.java index c82db4de..3562efd6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserNotification.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserNotification.java @@ -1,57 +1,57 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.util.Date;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-
-public class EPUserNotification extends DomainVo {
- private Long userId;
- private Long notificationId;
- private String viewed;
- private Date updateTime;
-
- public Long getUserId() {
- return userId;
- }
- public void setUserId(Long userId) {
- this.userId = userId;
- }
- public Long getNotificationId() {
- return notificationId;
- }
- public void setNotificationId(Long notificationId) {
- this.notificationId = notificationId;
- }
- public String getViewed() {
- return viewed;
- }
- public void setViewed(String viewed) {
- this.viewed = viewed;
- }
- public Date getUpdateTime() {
- return updateTime;
- }
- public void setUpdateTime(Date updateTime) {
- this.updateTime = updateTime;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.util.Date; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + + +public class EPUserNotification extends DomainVo { + private Long userId; + private Long notificationId; + private String viewed; + private Date updateTime; + + public Long getUserId() { + return userId; + } + public void setUserId(Long userId) { + this.userId = userId; + } + public Long getNotificationId() { + return notificationId; + } + public void setNotificationId(Long notificationId) { + this.notificationId = notificationId; + } + public String getViewed() { + return viewed; + } + public void setViewed(String viewed) { + this.viewed = viewed; + } + public Date getUpdateTime() { + return updateTime; + } + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPWidgetsManualSortPreference.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPWidgetsManualSortPreference.java index 4a3b784b..9ea3c075 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPWidgetsManualSortPreference.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPWidgetsManualSortPreference.java @@ -1,70 +1,70 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-public class EPWidgetsManualSortPreference extends DomainVo{
-
- private static final long serialVersionUID = 4607102334801223570L;
- private int userId;
- private Long widgetId;
- private int widgetRow;
- private int widgetCol;
- private int widgetWidth;
- private int widgetHeight;
-
- public int getUserId() {
- return userId;
- }
- public void setUserId(int userId) {
- this.userId = userId;
- }
- public Long getWidgetId() {
- return widgetId;
- }
- public void setWidgetId(Long widgetId) {
- this.widgetId = widgetId;
- }
- public int getWidgetRow() {
- return widgetRow;
- }
- public void setWidgetRow(int widgetRow) {
- this.widgetRow = widgetRow;
- }
- public int getWidgetCol() {
- return widgetCol;
- }
- public void setWidgetCol(int widgetCol) {
- this.widgetCol = widgetCol;
- }
- public int getWidgetWidth() {
- return widgetWidth;
- }
- public void setWidgetWidth(int widgetWidth) {
- this.widgetWidth = widgetWidth;
- }
- public int getWidgetHeight() {
- return widgetHeight;
- }
- public void setWidgetHeight(int widgetHeight) {
- this.widgetHeight = widgetHeight;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class EPWidgetsManualSortPreference extends DomainVo{ + + private static final long serialVersionUID = 4607102334801223570L; + private int userId; + private Long widgetId; + private int widgetRow; + private int widgetCol; + private int widgetWidth; + private int widgetHeight; + + public int getUserId() { + return userId; + } + public void setUserId(int userId) { + this.userId = userId; + } + public Long getWidgetId() { + return widgetId; + } + public void setWidgetId(Long widgetId) { + this.widgetId = widgetId; + } + public int getWidgetRow() { + return widgetRow; + } + public void setWidgetRow(int widgetRow) { + this.widgetRow = widgetRow; + } + public int getWidgetCol() { + return widgetCol; + } + public void setWidgetCol(int widgetCol) { + this.widgetCol = widgetCol; + } + public int getWidgetWidth() { + return widgetWidth; + } + public void setWidgetWidth(int widgetWidth) { + this.widgetWidth = widgetWidth; + } + public int getWidgetHeight() { + return widgetHeight; + } + public void setWidgetHeight(int widgetHeight) { + this.widgetHeight = widgetHeight; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompApp.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompApp.java index 1cf89fbd..6df37e82 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompApp.java @@ -1,146 +1,146 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-/**
- * Model for a subset of the columns in the fn_app table.
- */
-public class EcompApp {
-
- protected Long id;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- private String name;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- private String imageUrl;
-
- public String getImageUrl() {
- return imageUrl;
- }
-
- public void setImageUrl(String imageUrl) {
- this.imageUrl = imageUrl;
- }
-
- private String description;
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- private String notes;
-
- public String getNotes() {
- return notes;
- }
-
- public void setNotes(String notes) {
- this.notes = notes;
- }
-
- private String url;
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- private String alternateUrl;
-
- public String getAlternateUrl() {
- return alternateUrl;
- }
-
- public void setAlternateUrl(String alternateUrl) {
- this.alternateUrl = alternateUrl;
- }
-
- private String uebTopicName;
-
- public String getUebTopicName() {
- return uebTopicName;
- }
-
- public void setUebTopicName(String topicName) {
- this.uebTopicName = topicName;
- }
-
- private String uebKey;
-
- public String getUebKey() {
- return uebKey;
- }
-
- public void setUebKey(String uebKey) {
- this.uebKey = uebKey;
- }
-
- private String uebSecret;
-
- public String getUebSecret() {
- return uebSecret;
- }
-
- public void setUebSecret(String secret) {
- this.uebSecret = secret;
- }
-
- private Boolean enabled;
-
- public Boolean isEnabled() {
- return enabled;
- }
-
- public void setEnabled(Boolean enable) {
- this.enabled = enable;
- }
-
- private Boolean restrictedApp;
-
- public Boolean isRestrictedApp() {
- return restrictedApp;
- }
-
- public void setRestrictedApp(Boolean restrictedApp) {
- this.restrictedApp = restrictedApp;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +/** + * Model for a subset of the columns in the fn_app table. + */ +public class EcompApp { + + protected Long id; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + private String imageUrl; + + public String getImageUrl() { + return imageUrl; + } + + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } + + private String description; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + private String notes; + + public String getNotes() { + return notes; + } + + public void setNotes(String notes) { + this.notes = notes; + } + + private String url; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + private String alternateUrl; + + public String getAlternateUrl() { + return alternateUrl; + } + + public void setAlternateUrl(String alternateUrl) { + this.alternateUrl = alternateUrl; + } + + private String uebTopicName; + + public String getUebTopicName() { + return uebTopicName; + } + + public void setUebTopicName(String topicName) { + this.uebTopicName = topicName; + } + + private String uebKey; + + public String getUebKey() { + return uebKey; + } + + public void setUebKey(String uebKey) { + this.uebKey = uebKey; + } + + private String uebSecret; + + public String getUebSecret() { + return uebSecret; + } + + public void setUebSecret(String secret) { + this.uebSecret = secret; + } + + private Boolean enabled; + + public Boolean isEnabled() { + return enabled; + } + + public void setEnabled(Boolean enable) { + this.enabled = enable; + } + + private Boolean restrictedApp; + + public Boolean isRestrictedApp() { + return restrictedApp; + } + + public void setRestrictedApp(Boolean restrictedApp) { + this.restrictedApp = restrictedApp; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAppRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAppRole.java index 78cf4162..52529cb6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAppRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAppRole.java @@ -1,80 +1,80 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.IdClass;
-
-@Entity
-@IdClass(EcompAppRoleId.class)
-public class EcompAppRole {
-
- @Id
- @Column(name="app_id")
- private Long appId;
-
- @Id
- @Column(name="app_name")
- private String appName;
-
- @Id
- @Column(name="role_id")
- private Integer roleId;
-
- @Id
- @Column(name="role_name")
- private String roleName;
-
- public Long getAppId() {
- return appId;
- }
-
- public void setAppId(Long appId) {
- this.appId = appId;
- }
-
- public String getAppName() {
- return appName;
- }
-
- public void setAppName(String appName) {
- this.appName = appName;
- }
-
- public Integer getRoleId() {
- return roleId;
- }
-
- public void setRoleId(Integer roleId) {
- this.roleId = roleId;
- }
-
- public String getRoleName() {
- return roleName;
- }
-
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.IdClass; + +@Entity +@IdClass(EcompAppRoleId.class) +public class EcompAppRole { + + @Id + @Column(name="app_id") + private Long appId; + + @Id + @Column(name="app_name") + private String appName; + + @Id + @Column(name="role_id") + private Integer roleId; + + @Id + @Column(name="role_name") + private String roleName; + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public Integer getRoleId() { + return roleId; + } + + public void setRoleId(Integer roleId) { + this.roleId = roleId; + } + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAppRoleId.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAppRoleId.java index d89c0736..894316e5 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAppRoleId.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAppRoleId.java @@ -1,83 +1,83 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Id;
-
-public class EcompAppRoleId implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- @Id
- @Column(name="app_id")
- private Long appId;
-
- @Id
- @Column(name="app_name")
- private String appName;
-
- @Id
- @Column(name="role_id")
- private Integer roleId;
-
- @Id
- @Column(name="role_name")
- private String roleName;
-
- public Long getAppId() {
- return appId;
- }
-
- public void setAppId(Long appId) {
- this.appId = appId;
- }
-
- public String getAppName() {
- return appName;
- }
-
- public void setAppName(String appName) {
- this.appName = appName;
- }
-
- public Integer getRoleId() {
- return roleId;
- }
-
- public void setRoleId(Integer roleId) {
- this.roleId = roleId;
- }
-
- public String getRoleName() {
- return roleName;
- }
-
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Id; + +public class EcompAppRoleId implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + @Id + @Column(name="app_id") + private Long appId; + + @Id + @Column(name="app_name") + private String appName; + + @Id + @Column(name="role_id") + private Integer roleId; + + @Id + @Column(name="role_name") + private String roleName; + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public Integer getRoleId() { + return roleId; + } + + public void setRoleId(Integer roleId) { + this.roleId = roleId; + } + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAuditLog.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAuditLog.java index 4d4ec277..3d53c8d3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAuditLog.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompAuditLog.java @@ -1,61 +1,61 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.util.Date;
-
-import org.openecomp.portalsdk.core.domain.AuditLog;
-
-public class EcompAuditLog extends AuditLog {
-
- private static final long serialVersionUID = 7970458389782626231L;
-
- // values of activity_cd column in table fu_lu_activity
- // as loaded by DML sql script
- public static final String CD_ACTIVITY_ADD_CHILD_ROLE = "add_child_role";
- public static final String CD_ACTIVITY_ADD_ROLE = "add_role";
- public static final String CD_ACTIVITY_ADD_ROLE_FUNCTION = "add_role_function";
- public static final String CD_ACTIVITY_ADD_USER_ROLE = "add_user_role";
- public static final String CD_ACTIVITY_APP_ACCESS = "app_access";
- public static final String CD_ACTIVITY_FUNCTIONAL_ACCESS = "functional_access";
- public static final String CD_ACTIVITY_GUEST_LOGIN = "guest_login";
- public static final String CD_ACTIVITY_LOGIN = "login";
- public static final String CD_ACTIVITY_LOGOUT = "logout";
- public static final String CD_ACTIVITY_MOBILE_LOGIN = "mobile_login";
- public static final String CD_ACTIVITY_MOBILE_LOGOUT = "mobile_logout";
- public static final String CD_ACTIVITY_REMOVE_CHILD_ROLE = "remove_child_role";
- public static final String CD_ACTIVITY_REMOVE_ROLE = "remove_role";
- public static final String CD_ACTIVITY_REMOVE_ROLE_FUNCTION = "remove_role_function";
- public static final String CD_ACTIVITY_REMOVE_USER_ROLE = "remove_user_role";
- public static final String CD_ACTIVITY_TAB_ACCESS = "tab_access";
- public static final String CD_ACTIVITY_SEARCH = "search";
- public static final String CD_ACTIVITY_ADD_PORTAL_ADMIN = "apa ";
- public static final String CD_ACTIVITY_DELETE_PORTAL_ADMIN = "dpa";
- public static final String CD_ACTIVITY_UPDATE_USER = "uu ";
- public static final String CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN = "uaa ";
- public static final String CD_ACTIVITY_STORE_ANALYTICS = "store_analytics";
-
- /**
- * Creates a new object with the created field set to the current date-time.
- */
- public EcompAuditLog() {
- setCreated(new Date());
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.util.Date; + +import org.openecomp.portalsdk.core.domain.AuditLog; + +public class EcompAuditLog extends AuditLog { + + private static final long serialVersionUID = 7970458389782626231L; + + // values of activity_cd column in table fu_lu_activity + // as loaded by DML sql script + public static final String CD_ACTIVITY_ADD_CHILD_ROLE = "add_child_role"; + public static final String CD_ACTIVITY_ADD_ROLE = "add_role"; + public static final String CD_ACTIVITY_ADD_ROLE_FUNCTION = "add_role_function"; + public static final String CD_ACTIVITY_ADD_USER_ROLE = "add_user_role"; + public static final String CD_ACTIVITY_APP_ACCESS = "app_access"; + public static final String CD_ACTIVITY_FUNCTIONAL_ACCESS = "functional_access"; + public static final String CD_ACTIVITY_GUEST_LOGIN = "guest_login"; + public static final String CD_ACTIVITY_LOGIN = "login"; + public static final String CD_ACTIVITY_LOGOUT = "logout"; + public static final String CD_ACTIVITY_MOBILE_LOGIN = "mobile_login"; + public static final String CD_ACTIVITY_MOBILE_LOGOUT = "mobile_logout"; + public static final String CD_ACTIVITY_REMOVE_CHILD_ROLE = "remove_child_role"; + public static final String CD_ACTIVITY_REMOVE_ROLE = "remove_role"; + public static final String CD_ACTIVITY_REMOVE_ROLE_FUNCTION = "remove_role_function"; + public static final String CD_ACTIVITY_REMOVE_USER_ROLE = "remove_user_role"; + public static final String CD_ACTIVITY_TAB_ACCESS = "tab_access"; + public static final String CD_ACTIVITY_SEARCH = "search"; + public static final String CD_ACTIVITY_ADD_PORTAL_ADMIN = "apa "; + public static final String CD_ACTIVITY_DELETE_PORTAL_ADMIN = "dpa"; + public static final String CD_ACTIVITY_UPDATE_USER = "uu "; + public static final String CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN = "uaa "; + public static final String CD_ACTIVITY_STORE_ANALYTICS = "store_analytics"; + + /** + * Creates a new object with the created field set to the current date-time. + */ + public EcompAuditLog() { + setCreated(new Date()); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EpUserAppRoles.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EpUserAppRoles.java index 1bfb1841..2649cfd0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EpUserAppRoles.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EpUserAppRoles.java @@ -1,63 +1,63 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-@Entity
-@JsonInclude(JsonInclude.Include.NON_NULL)
-public class EpUserAppRoles extends DomainVo {
-
- private static final long serialVersionUID = -1484592641766545668L;
-
- @Id
- @Column(name ="role_id")
- public Long roleId;
-
- @Id
- @Column(name ="app_id")
- public Long appId;
-
- public Long getRoleId() {
- return roleId;
- }
- public void setRoleId(Long roleId) {
- this.roleId = roleId;
- }
- public Long getAppId() {
- return appId;
- }
- public void setAppId(Long appId) {
- this.appId = appId;
- }
-
- @Override
- public String toString() {
- return "EpUserAppRoles [roleId=" + roleId + ", appId=" + appId + "]";
- }
-}
-
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@Entity +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EpUserAppRoles extends DomainVo { + + private static final long serialVersionUID = -1484592641766545668L; + + @Id + @Column(name ="role_id") + public Long roleId; + + @Id + @Column(name ="app_id") + public Long appId; + + public Long getRoleId() { + return roleId; + } + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + public Long getAppId() { + return appId; + } + public void setAppId(Long appId) { + this.appId = appId; + } + + @Override + public String toString() { + return "EpUserAppRoles [roleId=" + roleId + ", appId=" + appId + "]"; + } +} + diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/ExternalSystemAccess.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/ExternalSystemAccess.java index a0395bf8..fdbc0931 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/ExternalSystemAccess.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/ExternalSystemAccess.java @@ -1,49 +1,49 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-public class ExternalSystemAccess {
-
- private String key;
- private Boolean accessValue;
-
- public ExternalSystemAccess(String key, Boolean accessValue){
- this.key = key;
- this.accessValue = accessValue;
- }
-
- public String getKey() {
- return key;
- }
- public void setKey(String key) {
- this.key = key;
- }
-
- public Boolean getAccessValue() {
- return accessValue;
- }
-
- public void setAccessValue(Boolean accessValue) {
- this.accessValue = accessValue;
- }
-
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +public class ExternalSystemAccess { + + private String key; + private Boolean accessValue; + + public ExternalSystemAccess(String key, Boolean accessValue){ + this.key = key; + this.accessValue = accessValue; + } + + public String getKey() { + return key; + } + public void setKey(String key) { + this.key = key; + } + + public Boolean getAccessValue() { + return accessValue; + } + + public void setAccessValue(Boolean accessValue) { + this.accessValue = accessValue; + } + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/FunctionalMenuItemWithAppID.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/FunctionalMenuItemWithAppID.java index ac2bc6c4..d8c916bd 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/FunctionalMenuItemWithAppID.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/FunctionalMenuItemWithAppID.java @@ -1,96 +1,96 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.util.List;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Transient;
-/***
- *
- * This class is almost identical to org.openecomp.portalapp.portal.transport.FunctionalMenuItem
- * The only difference is the appId field. In FunctionMenuItem, we used @Transient as an attribute, and we are using @Column in this class.
- * In some sql queries, we need to have appId, but it's not a field in fn_menu_functional table.
- *
- * @author robertlo
- *
- */
-@Entity
-public class FunctionalMenuItemWithAppID{
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- @Column(name = "MENU_ID")
- public Long menuId;
-
- @Column(name = "COLUMN_NUM")
- public Integer column;
-
- @Column(name = "TEXT")
- public String text;
-
- @Column(name = "PARENT_MENU_ID")
- public Integer parentMenuId;
-
- @Column(name = "URL")
- public String url;
-
- @Column(name="ACTIVE_YN")
- public String active_yn;
-
- @Column(name="APP_ID")
- public Integer appid;
-
- @Transient
- public List<Integer> roles;
-
- @Transient
- public Boolean restrictedApp;
-
- public void normalize() {
- if (this.column == null)
- this.column = new Integer(1);
- this.text = (this.text == null) ? "" : this.text.trim();
- if (this.parentMenuId == null)
- this.parentMenuId = new Integer(-1);
- this.url = (this.url == null) ? "" : this.url.trim();
- }
-
- @Override
- public String toString() {
- return "FunctionalMenuItem [menuId=" + menuId + ", column=" + column + ", text=" + text + ", parentMenuId="
- + parentMenuId + ", url=" + url + ", active_yn=" + active_yn + ", appid=" + appid + ", roles=" + roles
- + ", restrictedApp=" + restrictedApp + "]";
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public void setRestrictedApp(Boolean restrictedApp) {
- this.restrictedApp = restrictedApp;
- }
-}
-
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Transient; +/*** + * + * This class is almost identical to org.openecomp.portalapp.portal.transport.FunctionalMenuItem + * The only difference is the appId field. In FunctionMenuItem, we used @Transient as an attribute, and we are using @Column in this class. + * In some sql queries, we need to have appId, but it's not a field in fn_menu_functional table. + * + * @author robertlo + * + */ +@Entity +public class FunctionalMenuItemWithAppID{ + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name = "MENU_ID") + public Long menuId; + + @Column(name = "COLUMN_NUM") + public Integer column; + + @Column(name = "TEXT") + public String text; + + @Column(name = "PARENT_MENU_ID") + public Integer parentMenuId; + + @Column(name = "URL") + public String url; + + @Column(name="ACTIVE_YN") + public String active_yn; + + @Column(name="APP_ID") + public Integer appid; + + @Transient + public List<Integer> roles; + + @Transient + public Boolean restrictedApp; + + public void normalize() { + if (this.column == null) + this.column = new Integer(1); + this.text = (this.text == null) ? "" : this.text.trim(); + if (this.parentMenuId == null) + this.parentMenuId = new Integer(-1); + this.url = (this.url == null) ? "" : this.url.trim(); + } + + @Override + public String toString() { + return "FunctionalMenuItem [menuId=" + menuId + ", column=" + column + ", text=" + text + ", parentMenuId=" + + parentMenuId + ", url=" + url + ", active_yn=" + active_yn + ", appid=" + appid + ", roles=" + roles + + ", restrictedApp=" + restrictedApp + "]"; + } + + public void setUrl(String url) { + this.url = url; + } + + public void setRestrictedApp(Boolean restrictedApp) { + this.restrictedApp = restrictedApp; + } +} + diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResult.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResult.java index 4669426a..c4b9489c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResult.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResult.java @@ -1,114 +1,114 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-@Entity
-@JsonInclude
-public class GetAccessResult implements Serializable{
-
-
- private static final long serialVersionUID = 5239527705869613411L;
-
- @Id
- @Column(name="row_id")
- private String rowId;
-
- @Column(name="role_id")
- private Long roleId;
-
- @Column(name="ecomp_function",nullable=true)
- private String ecompFunction;
-
- @Column(name="app_name")
- private String appName;
-
- @Column(name="app_mots_id",nullable=true)
- private Integer appMotsId;
-
- @Column(name="role_name")
- private String roleName;
-
- @Column(name="role_actv",nullable=true)
- private String roleActive;
-
-
- @Column(name="request_type",nullable=true)
- private String reqType;
-
-
-
- public final String getRowId() {
- return rowId;
- }
- public final void setRowId(String rowId) {
- this.rowId = rowId;
- }
- public final Long getRoleId() {
- return roleId;
- }
- public final void setRoleId(Long roleId) {
- this.roleId = roleId;
- }
- public String getEcompFunction() {
- return ecompFunction;
- }
- public void setEcompFunction(String ecompFunction) {
- this.ecompFunction = ecompFunction;
- }
- public String getAppName() {
- return appName;
- }
- public void setAppName(String appName) {
- this.appName = appName;
- }
- public Integer getAppMotsId() {
- return appMotsId;
- }
- public void setAppMotsId(Integer appMotsId) {
- this.appMotsId = appMotsId;
- }
- public String getRoleName() {
- return roleName;
- }
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
- public final String getRoleActive() {
- return roleActive;
- }
- public final void setRoleActive(String roleActive) {
- this.roleActive = roleActive;
- }
- public final String getReqType() {
- return reqType;
- }
- public final void setReqType(String reqType) {
- this.reqType = reqType;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@Entity +@JsonInclude +public class GetAccessResult implements Serializable{ + + + private static final long serialVersionUID = 5239527705869613411L; + + @Id + @Column(name="row_id") + private String rowId; + + @Column(name="role_id") + private Long roleId; + + @Column(name="ecomp_function",nullable=true) + private String ecompFunction; + + @Column(name="app_name") + private String appName; + + @Column(name="app_mots_id",nullable=true) + private Integer appMotsId; + + @Column(name="role_name") + private String roleName; + + @Column(name="role_actv",nullable=true) + private String roleActive; + + + @Column(name="request_type",nullable=true) + private String reqType; + + + + public String getRowId() { + return rowId; + } + public void setRowId(String rowId) { + this.rowId = rowId; + } + public Long getRoleId() { + return roleId; + } + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + public String getEcompFunction() { + return ecompFunction; + } + public void setEcompFunction(String ecompFunction) { + this.ecompFunction = ecompFunction; + } + public String getAppName() { + return appName; + } + public void setAppName(String appName) { + this.appName = appName; + } + public Integer getAppMotsId() { + return appMotsId; + } + public void setAppMotsId(Integer appMotsId) { + this.appMotsId = appMotsId; + } + public String getRoleName() { + return roleName; + } + public void setRoleName(String roleName) { + this.roleName = roleName; + } + public String getRoleActive() { + return roleActive; + } + public void setRoleActive(String roleActive) { + this.roleActive = roleActive; + } + public String getReqType() { + return reqType; + } + public void setReqType(String reqType) { + this.reqType = reqType; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResultId.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResultId.java index 0830bfd8..b0508138 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResultId.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResultId.java @@ -1,64 +1,64 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Id;
-
-public class GetAccessResultId implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- @Id
- @Column(name="ecomp_function")
- private String ecompFunction;
-
- @Id
- @Column(name="app_name")
- private String appName;
-
- @Id
- @Column(name="role_name")
- private String roleName;
-
- public String getEcompFunction() {
- return ecompFunction;
- }
- public void setEcompFunction(String ecompFunction) {
- this.ecompFunction = ecompFunction;
- }
- public String getAppName() {
- return appName;
- }
- public void setAppName(String appName) {
- this.appName = appName;
- }
- public String getRoleName() {
- return roleName;
- }
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Id; + +public class GetAccessResultId implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + @Id + @Column(name="ecomp_function") + private String ecompFunction; + + @Id + @Column(name="app_name") + private String appName; + + @Id + @Column(name="role_name") + private String roleName; + + public String getEcompFunction() { + return ecompFunction; + } + public void setEcompFunction(String ecompFunction) { + this.ecompFunction = ecompFunction; + } + public String getAppName() { + return appName; + } + public void setAppName(String appName) { + this.appName = appName; + } + public String getRoleName() { + return roleName; + } + public void setRoleName(String roleName) { + this.roleName = roleName; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/MicroserviceData.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/MicroserviceData.java index 91366ce8..a9ca2b68 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/MicroserviceData.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/MicroserviceData.java @@ -1,146 +1,146 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.util.List;
-
-import javax.persistence.Column;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-public class MicroserviceData extends DomainVo {
-
- private static final long serialVersionUID = 1L;
-
- public MicroserviceData() {
-
- }
-
- private Long id;
-
- private String name;
-
- private String active;
-
- private String desc;
-
- private long appId;
-
- private String url;
-
- private String securityType;
-
- private String username;
-
- private String password;
-
- private List<MicroserviceParameter> parameterList;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getActive() {
- return active;
- }
-
- public void setActive(String active) {
- this.active = active;
- }
-
- public String getDesc() {
- return desc;
- }
-
- public void setDesc(String desc) {
- this.desc = desc;
- }
-
- public long getAppId() {
- return appId;
- }
-
- public void setAppId(long appId) {
- this.appId = appId;
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public String getSecurityType() {
- return securityType;
- }
-
- public void setSecurityType(String securityType) {
- this.securityType = securityType;
- }
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- public List<MicroserviceParameter> getParameterList() {
- return parameterList;
- }
-
- public void setParameterList(List<MicroserviceParameter> parameterList) {
- this.parameterList = parameterList;
- }
-
- @Override
- public String toString() {
- return "MicroserviceData [id=" + id + ", name=" + name + ", desc=" + desc + ", appId=" + appId + ", url=" + url
- + ", securityType=" + securityType + ", username=" + username + ", password=" + password
- + ", parameterList=" + parameterList + "]";
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class MicroserviceData extends DomainVo { + + private static final long serialVersionUID = 1L; + + public MicroserviceData() { + + } + + private Long id; + + private String name; + + private String active; + + private String desc; + + private long appId; + + private String url; + + private String securityType; + + private String username; + + private String password; + + private List<MicroserviceParameter> parameterList; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getActive() { + return active; + } + + public void setActive(String active) { + this.active = active; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public long getAppId() { + return appId; + } + + public void setAppId(long appId) { + this.appId = appId; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getSecurityType() { + return securityType; + } + + public void setSecurityType(String securityType) { + this.securityType = securityType; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public List<MicroserviceParameter> getParameterList() { + return parameterList; + } + + public void setParameterList(List<MicroserviceParameter> parameterList) { + this.parameterList = parameterList; + } + + @Override + public String toString() { + return "MicroserviceData [id=" + id + ", name=" + name + ", desc=" + desc + ", appId=" + appId + ", url=" + url + + ", securityType=" + securityType + ", username=" + username + ", password=" + password + + ", parameterList=" + parameterList + "]"; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/MicroserviceParameter.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/MicroserviceParameter.java index 74a29370..0796a5a9 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/MicroserviceParameter.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/MicroserviceParameter.java @@ -1,82 +1,82 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import javax.persistence.Column;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-public class MicroserviceParameter extends DomainVo {
-
- private static final long serialVersionUID = 1L;
-
- public MicroserviceParameter() {
-
- }
-
- private Long id;
-
- private long serviceId;
-
- private String para_key;
-
- private String para_value;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public long getServiceId() {
- return serviceId;
- }
-
- public void setServiceId(long serviceId) {
- this.serviceId = serviceId;
- }
-
- public String getPara_key() {
- return para_key;
- }
-
- public void setPara_key(String para_key) {
- this.para_key = para_key;
- }
-
- public String getPara_value() {
- return para_value;
- }
-
- public void setPara_value(String para_value) {
- this.para_value = para_value;
- }
-
- @Override
- public String toString() {
- return "MicroserviceParameter [id=" + id + ", serviceId=" + serviceId + ", para_key=" + para_key
- + ", para_value=" + para_value + "]";
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import javax.persistence.Column; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class MicroserviceParameter extends DomainVo { + + private static final long serialVersionUID = 1L; + + public MicroserviceParameter() { + + } + + private Long id; + + private long serviceId; + + private String para_key; + + private String para_value; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public long getServiceId() { + return serviceId; + } + + public void setServiceId(long serviceId) { + this.serviceId = serviceId; + } + + public String getPara_key() { + return para_key; + } + + public void setPara_key(String para_key) { + this.para_key = para_key; + } + + public String getPara_value() { + return para_value; + } + + public void setPara_value(String para_value) { + this.para_value = para_value; + } + + @Override + public String toString() { + return "MicroserviceParameter [id=" + id + ", serviceId=" + serviceId + ", para_key=" + para_key + + ", para_value=" + para_value + "]"; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserAppSelection.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserAppSelection.java index 68875bf5..331cdb81 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserAppSelection.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserAppSelection.java @@ -1,78 +1,78 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-/**
- * Models a row in the table with personalization of user app selections.
- */
-public class PersUserAppSelection extends DomainVo {
-
- private static final long serialVersionUID = 1545308654500121206L;
-
- private Long userId;
-
- private Long appId;
-
- private String statusCode;
-
- public PersUserAppSelection() {}
-
- /**
- * Convenience constructor
- *
- * @param id
- * @param userId
- * @param appId
- * @param statusCode
- */
- public PersUserAppSelection(final Long id, final Long userId, final Long appId, final String statusCode) {
- super.id = id;
- this.userId = userId;
- this.appId = appId;
- this.statusCode = statusCode;
- }
-
- public Long getAppId() {
- return appId;
- }
-
- public void setAppId(Long appId) {
- this.appId = appId;
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public void setUserId(Long userId) {
- this.userId = userId;
- }
-
- public String getStatusCode() {
- return statusCode;
- }
-
- public void setStatusCode(String statusCode) {
- this.statusCode = statusCode;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +/** + * Models a row in the table with personalization of user app selections. + */ +public class PersUserAppSelection extends DomainVo { + + private static final long serialVersionUID = 1545308654500121206L; + + private Long userId; + + private Long appId; + + private String statusCode; + + public PersUserAppSelection() {} + + /** + * Convenience constructor + * + * @param id + * @param userId + * @param appId + * @param statusCode + */ + public PersUserAppSelection(final Long id, final Long userId, final Long appId, final String statusCode) { + super.id = id; + this.userId = userId; + this.appId = appId; + this.statusCode = statusCode; + } + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getStatusCode() { + return statusCode; + } + + public void setStatusCode(String statusCode) { + this.statusCode = statusCode; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserWidgetSelection.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserWidgetSelection.java index 4993b462..692479b4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserWidgetSelection.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserWidgetSelection.java @@ -1,81 +1,81 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-/**
- * Models a row in the table with personalization of user widget selections.
- */
-public class PersUserWidgetSelection extends DomainVo {
-
- /**
- *
- */
- private static final long serialVersionUID = -6547880514779039200L;
-
- private Long userId;
-
- private Long widgetId;
-
- private String statusCode;
-
- public PersUserWidgetSelection() {}
-
- /**
- * Convenience constructor
- *
- * @param id
- * @param userId
- * @param widgetId
- * @param statusCode
- */
- public PersUserWidgetSelection(final Long id, final Long userId, final Long widgetId, final String statusCode) {
- super.id = id;
- this.userId = userId;
- this.widgetId = widgetId;
- this.statusCode = statusCode;
- }
-
- public Long getWidgetId() {
- return widgetId;
- }
-
- public void setWidgetId(Long widgetId) {
- this.widgetId = widgetId;
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public void setUserId(Long userId) {
- this.userId = userId;
- }
-
- public String getStatusCode() {
- return statusCode;
- }
-
- public void setStatusCode(String statusCode) {
- this.statusCode = statusCode;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +/** + * Models a row in the table with personalization of user widget selections. + */ +public class PersUserWidgetSelection extends DomainVo { + + /** + * + */ + private static final long serialVersionUID = -6547880514779039200L; + + private Long userId; + + private Long widgetId; + + private String statusCode; + + public PersUserWidgetSelection() {} + + /** + * Convenience constructor + * + * @param id + * @param userId + * @param widgetId + * @param statusCode + */ + public PersUserWidgetSelection(final Long id, final Long userId, final Long widgetId, final String statusCode) { + super.id = id; + this.userId = userId; + this.widgetId = widgetId; + this.statusCode = statusCode; + } + + public Long getWidgetId() { + return widgetId; + } + + public void setWidgetId(Long widgetId) { + this.widgetId = widgetId; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getStatusCode() { + return statusCode; + } + + public void setStatusCode(String statusCode) { + this.statusCode = statusCode; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/RoleApp.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/RoleApp.java index ade24dcb..769016db 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/RoleApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/RoleApp.java @@ -1,114 +1,114 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.io.Serializable;
-import java.util.Set;
-
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToMany;
-import javax.persistence.ManyToOne;
-
-import com.fasterxml.jackson.annotation.JsonIgnore;
-
-//@Entity
-//@Table(name = "FN_ROLE")
-public class RoleApp implements Serializable{
- private static final long serialVersionUID = 1L;
-
- //@Id
- //@Column(name = "ROLE_ID")
- //@GeneratedValue(strategy=GenerationType.AUTO)
- private Long roleId;
-
-
- //@Column(name = "ROLE_Name")
- private String roleName;
-
- //@ManyToOne(fetch = FetchType.EAGER)
- //@JoinColumn(name="APP_ID")
- private App app;
-
- //@JsonIgnore
- //@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, mappedBy="widgetRoles")
- private Set<WidgetCatalog> widgets;
-
- /*@PreRemove
- private void removeGroupsFromUsers() {
- for (WidgetCatalog w : widgets) {
- w.getWidgetRoles().remove(this);
- }
- }*/
-
- /*@ManyToOne
- @JoinColumn(name = "WIDGET_ID", nullable = false)
- WidgetCatalog widgetCatalog;*/
-
- //@JsonIgnore
- //@ManyToMany(mappedBy = "widgetRoles")
- //@ManyToMany(fetch = FetchType.EAGER, mappedBy = "widgetRoles")
- //private Set<WidgetCatalog> widgets = new HashSet<WidgetCatalog>();
-
- public Long getRoleId() {
- return roleId;
- }
-
- public void setRoleId(Long roleId) {
- this.roleId = roleId;
- }
-
- public String getRoleName() {
- return roleName;
- }
-
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
-
- public App getApp() {
- return app;
- }
-
- public void setApp(App app) {
- this.app = app;
- }
-
-
-
- public Set<WidgetCatalog> getWidgets() {
- return widgets;
- }
-
- public void setWidgets(Set<WidgetCatalog> widgets) {
- this.widgets = widgets;
- }
-
- @Override
- public String toString() {
- return "Role [roleId=" + roleId + ", roleName=" + roleName + ", app=" + app + "]";
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.io.Serializable; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +//@Entity +//@Table(name = "FN_ROLE") +public class RoleApp implements Serializable{ + private static final long serialVersionUID = 1L; + + //@Id + //@Column(name = "ROLE_ID") + //@GeneratedValue(strategy=GenerationType.AUTO) + private Long roleId; + + + //@Column(name = "ROLE_Name") + private String roleName; + + //@ManyToOne(fetch = FetchType.EAGER) + //@JoinColumn(name="APP_ID") + private App app; + + //@JsonIgnore + //@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, mappedBy="widgetRoles") + private Set<WidgetCatalog> widgets; + + /*@PreRemove + private void removeGroupsFromUsers() { + for (WidgetCatalog w : widgets) { + w.getWidgetRoles().remove(this); + } + }*/ + + /*@ManyToOne + @JoinColumn(name = "WIDGET_ID", nullable = false) + WidgetCatalog widgetCatalog;*/ + + //@JsonIgnore + //@ManyToMany(mappedBy = "widgetRoles") + //@ManyToMany(fetch = FetchType.EAGER, mappedBy = "widgetRoles") + //private Set<WidgetCatalog> widgets = new HashSet<WidgetCatalog>(); + + public Long getRoleId() { + return roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + public App getApp() { + return app; + } + + public void setApp(App app) { + this.app = app; + } + + + + public Set<WidgetCatalog> getWidgets() { + return widgets; + } + + public void setWidgets(Set<WidgetCatalog> widgets) { + this.widgets = widgets; + } + + @Override + public String toString() { + return "Role [roleId=" + roleId + ", roleName=" + roleName + ", app=" + app + "]"; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/SharedContext.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/SharedContext.java index f966c964..49333c4c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/SharedContext.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/SharedContext.java @@ -1,161 +1,173 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.util.Date;
-
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-/**
- * A shared context is a key-value pair in a session. All shared-context objects
- * should be dropped when a session is destroyed. Because there's always a
- * chance of missing that event, this object notes its creation time so that it
- * can be expired after a suitable time interval.
- */
-@Entity
-@Table(name = "fn_shared_context")
-public class SharedContext extends DomainVo {
-
- // generated
- private static final long serialVersionUID = 7287469622586677888L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
- private Date create_time;
- private String context_id;
- private String ckey;
- private String cvalue;
-
- /**
- * Mandatory no-argument constructor
- */
- public SharedContext() {
- }
-
- /**
- * Convenience constructor. The database ID and creation timestamp are
- * populated when the object is added to the database.
- */
- public SharedContext(final String contextId, final String key, final String value) {
- this.context_id = contextId;
- this.ckey = key;
- this.cvalue = value;
- }
-
- /**
- * Gets the database row ID.
- *
- * @return Database row ID
- */
- public Long getId() {
- return id;
- }
-
- /**
- * Sets the database row ID.
- *
- * @param id
- */
- public void setId(final Long id) {
- this.id = id;
- }
-
- /**
- * Gets the creation time
- *
- * @return Creation time as a Date
- */
- public Date getCreate_time() {
- return create_time;
- }
-
- /**
- * Sets the creation time
- *
- * @param create_time
- */
- public void setCreate_time(final Date create_time) {
- this.create_time = create_time;
- }
-
- /**
- * Gets the context ID
- *
- * @return Context ID
- */
- public String getContext_id() {
- return context_id;
- }
-
- /**
- * Sets the context ID
- *
- * @param context_id
- */
- public void setContext_id(final String context_id) {
- this.context_id = context_id;
- }
-
- /**
- * Gets the key of the key-value pair. Called ckey because "key" is a
- * reserved word in Mysql.
- *
- * @return The key
- */
- public String getCkey() {
- return ckey;
- }
-
- /**
- * Sets the key of the key-value pair.
- *
- * @param ckey
- */
- public void setCkey(final String ckey) {
- this.ckey = ckey;
- }
-
- /**
- * Gets the value of the key-value pair. Called cvalue because "value" is a
- * reserved word in Mysql.
- *
- * @return
- */
- public String getCvalue() {
- return cvalue;
- }
-
- /**
- * Sets the value of the key-value pair.
- *
- * @param cvalue
- */
- public void setCvalue(final String cvalue) {
- this.cvalue = cvalue;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +/** + * A shared context is a key-value pair in a session. All shared-context objects + * should be dropped when a session is destroyed. Because there's always a + * chance of missing that event, this object notes its creation time so that it + * can be expired after a suitable time interval. + */ +@Entity +@Table(name = "fn_shared_context") +public class SharedContext extends DomainVo { + + // generated + private static final long serialVersionUID = 7287469622586677888L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private Date create_time; + private String context_id; + private String ckey; + private String cvalue; + + /** + * Mandatory no-argument constructor + */ + public SharedContext() { + } + + /** + * Convenience constructor. The database ID and creation timestamp are + * populated when the object is added to the database. + * + * @param contextId + * context ID + * @param key + * context key + * @param value + * context value + */ + public SharedContext(final String contextId, final String key, final String value) { + this.context_id = contextId; + this.ckey = key; + this.cvalue = value; + } + + /** + * Gets the database row ID. + * + * @return Database row ID + */ + public Long getId() { + return id; + } + + /** + * Sets the database row ID. + * + * @param id + * database row ID + */ + public void setId(final Long id) { + this.id = id; + } + + /** + * Gets the creation time + * + * @return Creation time as a Date + */ + public Date getCreate_time() { + return create_time; + } + + /** + * Sets the creation time + * + * @param create_time + * Date + */ + public void setCreate_time(final Date create_time) { + this.create_time = create_time; + } + + /** + * Gets the context ID + * + * @return Context ID + */ + public String getContext_id() { + return context_id; + } + + /** + * Sets the context ID + * + * @param context_id + * String + */ + public void setContext_id(final String context_id) { + this.context_id = context_id; + } + + /** + * Gets the key of the key-value pair. Called ckey because "key" is a + * reserved word in Mysql. + * + * @return The key + */ + public String getCkey() { + return ckey; + } + + /** + * Sets the key of the key-value pair. + * + * @param ckey + * String + */ + public void setCkey(final String ckey) { + this.ckey = ckey; + } + + /** + * Gets the value of the key-value pair. Called cvalue because "value" is a + * reserved word in Mysql. + * + * @return value + */ + public String getCvalue() { + return cvalue; + } + + /** + * Sets the value of the key-value pair. + * + * @param cvalue + * value + */ + public void setCvalue(final String cvalue) { + this.cvalue = cvalue; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/UserRoles.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/UserRoles.java index 1483f34a..83cce3e3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/UserRoles.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/UserRoles.java @@ -1,113 +1,113 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-
-public class UserRoles implements Serializable {
- private static final long serialVersionUID = 1L;
-
- /*
- private static final HashMap<Long, String> rolesDictionary;
- // remove hard coded roles
- static {
- rolesDictionary = new HashMap<Long, String>();
- rolesDictionary.put(Long.valueOf(SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID)).longValue(), "superAdmin");
- rolesDictionary.put(Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID)).longValue(), "admin");
- }
- */
-
- public UserRoles(UserRole user) {
- setOrgUserId(user.getOrgUserId());
- setFirstName(user.getFirstName());
- setLastName(user.getLastName());
- setGuestSession(user.getUser_Id()==-1 ? true : false);
-
- addRole(user.getRoleName());
- }
-
- public void addRole(String roleName) {
- //String normalizedRole = normalizeRole(roleId);
- if (!getRoles().contains(roleName)) {
- this.roles.add(roleName);
- }
- }
-
- /*
- public static String normalizeRole(Long role) {
- String roleTranslated = rolesDictionary.get(role);
- return roleTranslated == null ? "user" : roleTranslated;
- }
- */
-
- private String orgUserId;
- private String firstName;
- private String lastName;
- private boolean guestSession;
-
- // TODO: Make into set
- private List<String> roles = new ArrayList<String>();
-
- public String getFirstName() {
- return firstName;
- }
-
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
-
- public String getLastName() {
- return lastName;
- }
-
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
-
- public String getOrgUserId() {
- return orgUserId;
- }
-
- public void setOrgUserId(String orgUserId) {
- this.orgUserId = orgUserId;
- }
-
- public List<String> getRoles() {
- return roles;
- }
-
- public void setRoles(List<String> roles) {
- this.roles = roles;
- }
-
- public void setGuestSession(boolean guestSession) {
- this.guestSession = guestSession;
- }
-
- public boolean getGuestSession() {
- return this.guestSession;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; + +public class UserRoles implements Serializable { + private static final long serialVersionUID = 1L; + + /* + private static final HashMap<Long, String> rolesDictionary; + // remove hard coded roles + static { + rolesDictionary = new HashMap<Long, String>(); + rolesDictionary.put(Long.valueOf(SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID)).longValue(), "superAdmin"); + rolesDictionary.put(Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID)).longValue(), "admin"); + } + */ + + public UserRoles(UserRole user) { + setOrgUserId(user.getOrgUserId()); + setFirstName(user.getFirstName()); + setLastName(user.getLastName()); + setGuestSession(user.getUser_Id()==-1 ? true : false); + + addRole(user.getRoleName()); + } + + public void addRole(String roleName) { + //String normalizedRole = normalizeRole(roleId); + if (!getRoles().contains(roleName)) { + this.roles.add(roleName); + } + } + + /* + public static String normalizeRole(Long role) { + String roleTranslated = rolesDictionary.get(role); + return roleTranslated == null ? "user" : roleTranslated; + } + */ + + private String orgUserId; + private String firstName; + private String lastName; + private boolean guestSession; + + // TODO: Make into set + private List<String> roles = new ArrayList<String>(); + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getOrgUserId() { + return orgUserId; + } + + public void setOrgUserId(String orgUserId) { + this.orgUserId = orgUserId; + } + + public List<String> getRoles() { + return roles; + } + + public void setRoles(List<String> roles) { + this.roles = roles; + } + + public void setGuestSession(boolean guestSession) { + this.guestSession = guestSession; + } + + public boolean getGuestSession() { + return this.guestSession; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/Widget.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/Widget.java index c2ef3c00..302195f0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/Widget.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/Widget.java @@ -1,105 +1,105 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import org.apache.commons.lang.StringUtils;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-public class Widget extends DomainVo {
-
- private static final long serialVersionUID = 1L;
-
- private String name;
-
- private Integer width;
-
- private Integer height;
-
- private String url;
-
- private Long appId;
-
- public Widget() {
- // Attention!!!
- // We set here all default values. We also place protection
- // into setters for fields with default values.
- // If we don't use such protection we are able to place null
- // to these fields and save such fields into DB even if DB has
- // default values for these fields.
- this.name = "";
- this.width = new Integer(0);
- this.height = new Integer(0);
- this.url = "";
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- if (StringUtils.isEmpty(name)) {
- name = "";
- }
- this.name = name;
- }
-
- public Integer getWidth() {
- return width;
- }
-
- public void setWidth(Integer width) {
- if (width == null) {
- width = new Integer(0);
- }
- this.width = width;
- }
-
- public Integer getHeight() {
- return height;
- }
-
- public void setHeight(Integer height) {
- if (height == null) {
- height = new Integer(0);
- }
- this.height = height;
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- if (StringUtils.isEmpty(url)) {
- url = "";
- }
- this.url = url;
- }
-
- public Long getAppId() {
- return appId;
- }
-
- public void setAppId(Long appId) {
- this.appId = appId;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import org.apache.commons.lang.StringUtils; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class Widget extends DomainVo { + + private static final long serialVersionUID = 1L; + + private String name; + + private Integer width; + + private Integer height; + + private String url; + + private Long appId; + + public Widget() { + // Attention!!! + // We set here all default values. We also place protection + // into setters for fields with default values. + // If we don't use such protection we are able to place null + // to these fields and save such fields into DB even if DB has + // default values for these fields. + this.name = ""; + this.width = new Integer(0); + this.height = new Integer(0); + this.url = ""; + } + + public String getName() { + return name; + } + + public void setName(String name) { + if (StringUtils.isEmpty(name)) { + name = ""; + } + this.name = name; + } + + public Integer getWidth() { + return width; + } + + public void setWidth(Integer width) { + if (width == null) { + width = new Integer(0); + } + this.width = width; + } + + public Integer getHeight() { + return height; + } + + public void setHeight(Integer height) { + if (height == null) { + height = new Integer(0); + } + this.height = height; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + if (StringUtils.isEmpty(url)) { + url = ""; + } + this.url = url; + } + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetCatalog.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetCatalog.java index 605a41d2..5481a22f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetCatalog.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetCatalog.java @@ -1,109 +1,109 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.io.Serializable;
-import java.util.Set;
-
-public class WidgetCatalog implements Serializable{
-
- private static final long serialVersionUID = 1L;
-
- private long id;
-
- private String name;
-
- private String desc;
-
- private String fileLocation;
-
- private String allowAllUser;
-
- private Long serviceId;
-
- private String sortOrder;
-
- private String statusCode;
-
- private Set<RoleApp> widgetRoles;
-
- public long getId() {
- return id;
- }
- public void setId(long id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
-
- public Long getServiceId() {
- return serviceId;
- }
- public void setServiceId(Long serviceId) {
- this.serviceId = serviceId;
- }
- public String getDesc() {
- return desc;
- }
- public void setDesc(String desc) {
- this.desc = desc;
- }
- public String getFileLocation() {
- return fileLocation;
- }
- public void setFileLocation(String fileLocation) {
- this.fileLocation = fileLocation;
- }
-
- public String getAllowAllUser() {
- return allowAllUser;
- }
- public void setAllowAllUser(String allowAllUser) {
- this.allowAllUser = allowAllUser;
- }
- public Set<RoleApp> getWidgetRoles() {
- return widgetRoles;
- }
- public void setWidgetRoles(Set<RoleApp> widgetRoles) {
- this.widgetRoles = widgetRoles;
- }
-
- public String getSortOrder() {
- return sortOrder;
- }
- public void setSortOrder(String sortOrder) {
- this.sortOrder = sortOrder;
- }
- public String getStatusCode() {
- return statusCode;
- }
- public void setStatusCode(String statusCode) {
- this.statusCode = statusCode;
- }
- @Override
- public String toString() {
- return "WidgetCatalog [id=" + id + ", name=" + name + ", desc=" + desc + ", fileLocation=" + fileLocation
- + ", allowAllUser=" + allowAllUser + "]";
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.io.Serializable; +import java.util.Set; + +public class WidgetCatalog implements Serializable{ + + private static final long serialVersionUID = 1L; + + private long id; + + private String name; + + private String desc; + + private String fileLocation; + + private String allowAllUser; + + private Long serviceId; + + private String sortOrder; + + private String statusCode; + + private Set<RoleApp> widgetRoles; + + public long getId() { + return id; + } + public void setId(long id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public Long getServiceId() { + return serviceId; + } + public void setServiceId(Long serviceId) { + this.serviceId = serviceId; + } + public String getDesc() { + return desc; + } + public void setDesc(String desc) { + this.desc = desc; + } + public String getFileLocation() { + return fileLocation; + } + public void setFileLocation(String fileLocation) { + this.fileLocation = fileLocation; + } + + public String getAllowAllUser() { + return allowAllUser; + } + public void setAllowAllUser(String allowAllUser) { + this.allowAllUser = allowAllUser; + } + public Set<RoleApp> getWidgetRoles() { + return widgetRoles; + } + public void setWidgetRoles(Set<RoleApp> widgetRoles) { + this.widgetRoles = widgetRoles; + } + + public String getSortOrder() { + return sortOrder; + } + public void setSortOrder(String sortOrder) { + this.sortOrder = sortOrder; + } + public String getStatusCode() { + return statusCode; + } + public void setStatusCode(String statusCode) { + this.statusCode = statusCode; + } + @Override + public String toString() { + return "WidgetCatalog [id=" + id + ", name=" + name + ", desc=" + desc + ", fileLocation=" + fileLocation + + ", allowAllUser=" + allowAllUser + "]"; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetCatalogParameter.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetCatalogParameter.java index c72780aa..6e750db9 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetCatalogParameter.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetCatalogParameter.java @@ -1,90 +1,90 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-public class WidgetCatalogParameter extends DomainVo{
-
- private static final long serialVersionUID = 1L;
-
- public WidgetCatalogParameter() {
-
- }
- private Long id;
-
- private Long widgetId;
-
- private Long userId;
-
- private Long paramId;
-
- private String user_value;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Long getWidgetId() {
- return widgetId;
- }
-
- public void setWidgetId(Long widgetId) {
- this.widgetId = widgetId;
- }
-
- public String getUser_value() {
- return user_value;
- }
-
- public void setUser_value(String user_value) {
- this.user_value = user_value;
- }
-
- public Long getParamId() {
- return paramId;
- }
-
- public void setParamId(Long paramId) {
- this.paramId = paramId;
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public void setUserId(Long userId) {
- this.userId = userId;
- }
-
- @Override
- public String toString() {
- return "WidgetCatalogParameter [id=" + id + ", widgetId=" + widgetId + ", userId=" + userId + ", paramId="
- + paramId + ", user_value=" + user_value + "]";
- }
-
-
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class WidgetCatalogParameter extends DomainVo{ + + private static final long serialVersionUID = 1L; + + public WidgetCatalogParameter() { + + } + private Long id; + + private Long widgetId; + + private Long userId; + + private Long paramId; + + private String user_value; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getWidgetId() { + return widgetId; + } + + public void setWidgetId(Long widgetId) { + this.widgetId = widgetId; + } + + public String getUser_value() { + return user_value; + } + + public void setUser_value(String user_value) { + this.user_value = user_value; + } + + public Long getParamId() { + return paramId; + } + + public void setParamId(Long paramId) { + this.paramId = paramId; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + @Override + public String toString() { + return "WidgetCatalogParameter [id=" + id + ", widgetId=" + widgetId + ", userId=" + userId + ", paramId=" + + paramId + ", user_value=" + user_value + "]"; + } + + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetParameterResult.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetParameterResult.java index 884ec141..b41f985e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetParameterResult.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetParameterResult.java @@ -1,70 +1,70 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-public class WidgetParameterResult {
-
- private Long param_id;
-
- private String param_key;
-
- private String user_value;
-
- private String default_value;
-
- public Long getParam_id() {
- return param_id;
- }
-
- public void setParam_id(Long param_id) {
- this.param_id = param_id;
- }
-
- public String getParam_key() {
- return param_key;
- }
-
- public void setParam_key(String param_key) {
- this.param_key = param_key;
- }
-
- public String getUser_value() {
- return user_value;
- }
-
- public void setUser_value(String user_value) {
- this.user_value = user_value;
- }
-
- public String getDefault_value() {
- return default_value;
- }
-
- public void setDefault_value(String default_value) {
- this.default_value = default_value;
- }
-
- @Override
- public String toString() {
- return "WidgetParameterResult [param_id=" + param_id + ", param_key=" + param_key + ", user_value=" + user_value
- + ", default_value=" + default_value + "]";
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +public class WidgetParameterResult { + + private Long param_id; + + private String param_key; + + private String user_value; + + private String default_value; + + public Long getParam_id() { + return param_id; + } + + public void setParam_id(Long param_id) { + this.param_id = param_id; + } + + public String getParam_key() { + return param_key; + } + + public void setParam_key(String param_key) { + this.param_key = param_key; + } + + public String getUser_value() { + return user_value; + } + + public void setUser_value(String user_value) { + this.user_value = user_value; + } + + public String getDefault_value() { + return default_value; + } + + public void setDefault_value(String default_value) { + this.default_value = default_value; + } + + @Override + public String toString() { + return "WidgetParameterResult [param_id=" + param_id + ", param_key=" + param_key + ", user_value=" + user_value + + ", default_value=" + default_value + "]"; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetServiceHeaders.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetServiceHeaders.java index 9200adda..c53df6ca 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetServiceHeaders.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/WidgetServiceHeaders.java @@ -1,54 +1,54 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.domain;
-
-import java.nio.charset.Charset;
-
-import org.apache.commons.codec.binary.Base64;
-import org.springframework.http.HttpHeaders;
-
-import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-
-public class WidgetServiceHeaders {
-
- private static HttpHeaders widgetHeaders;
-
- private WidgetServiceHeaders(){}
-
- public static HttpHeaders getInstance() throws Exception{
- if(null == widgetHeaders){
- return new HttpHeaders(){{
-
- String username = EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user");
- String password = CipherUtil.decrypt(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"));
- String auth = username + ":" + password;
- byte[] encodedAuth = Base64.encodeBase64(
- auth.getBytes(Charset.forName("US-ASCII")) );
- String authHeader = "Basic " + new String( encodedAuth );
- set( "Authorization", authHeader );
- }
- };
- }
- else
- return widgetHeaders;
-
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.domain; + +import java.nio.charset.Charset; + +import org.apache.commons.codec.binary.Base64; +import org.springframework.http.HttpHeaders; + +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; + +public class WidgetServiceHeaders { + + private static HttpHeaders widgetHeaders; + + private WidgetServiceHeaders(){} + + public static HttpHeaders getInstance() throws Exception{ + if(null == widgetHeaders){ + return new HttpHeaders(){{ + + String username = EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user"); + String password = CipherUtil.decrypt(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password")); + String auth = username + ":" + password; + byte[] encodedAuth = Base64.encodeBase64( + auth.getBytes(Charset.forName("US-ASCII")) ); + String authHeader = "Basic " + new String( encodedAuth ); + set( "Authorization", authHeader ); + } + }; + } + else + return widgetHeaders; + + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCatalogItem.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCatalogItem.java index ec20b4f3..9cce4c0f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCatalogItem.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCatalogItem.java @@ -1,249 +1,258 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.ecomp.model;
-
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-/**
- * This model of an application catalog entry has some EPApp fields plus
- * additional fields to indicate access(ible) and select(ed) statuses.
- */
-@Entity
-@JsonInclude(JsonInclude.Include.NON_NULL)
-public class AppCatalogItem extends DomainVo {
-
- private static final long serialVersionUID = 6619663784935017846L;
-
- @Id
- private Long id;
- private String name;
- private String imageUrl;
- private String description;
- private String notes;
- private String url;
- private String alternateUrl;
- private Boolean restricted;
- private Boolean open;
- private Boolean access;
- private Boolean select;
- private Boolean pending;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getImageUrl() {
- return imageUrl;
- }
-
- public void setImageUrl(String imageUrl) {
- this.imageUrl = imageUrl;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getNotes() {
- return notes;
- }
-
- public void setNotes(String notes) {
- this.notes = notes;
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public String getAlternateUrl() {
- return alternateUrl;
- }
-
- public void setAlternateUrl(String alternateUrl) {
- this.alternateUrl = alternateUrl;
- }
-
- public Boolean getRestricted() {
- return restricted;
- }
-
- public void setRestricted(Boolean restricted) {
- this.restricted = restricted;
- }
-
- public Boolean getOpen() {
- return open;
- }
-
- public void setOpen(Boolean open) {
- this.open = open;
- }
-
- public Boolean getAccess() {
- return access;
- }
-
- public void setAccess(Boolean access) {
- this.access = access;
- }
-
- public Boolean getSelect() {
- return select;
- }
-
- public void setSelect(Boolean select) {
- this.select = select;
- }
-
- public Boolean getPending() {
- return pending;
- }
-
- public void setPending(Boolean pending) {
- this.pending = pending;
- }
-
- public static long getSerialversionuid() {
- return serialVersionUID;
- }
-
- @Override
- public String toString() {
- return "AppCatalogItem [id=" + id + ", name=" + name + ", access=" + access + ", select=" + select
- + ", pending=" + pending + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((access == null) ? 0 : access.hashCode());
- result = prime * result + ((alternateUrl == null) ? 0 : alternateUrl.hashCode());
- result = prime * result + ((description == null) ? 0 : description.hashCode());
- result = prime * result + ((id == null) ? 0 : id.hashCode());
- result = prime * result + ((imageUrl == null) ? 0 : imageUrl.hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((notes == null) ? 0 : notes.hashCode());
- result = prime * result + ((open == null) ? 0 : open.hashCode());
- result = prime * result + ((pending == null) ? 0 : pending.hashCode());
- result = prime * result + ((restricted == null) ? 0 : restricted.hashCode());
- result = prime * result + ((select == null) ? 0 : select.hashCode());
- result = prime * result + ((url == null) ? 0 : url.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- AppCatalogItem other = (AppCatalogItem) obj;
- if (access == null) {
- if (other.access != null)
- return false;
- } else if (!access.equals(other.access))
- return false;
- if (alternateUrl == null) {
- if (other.alternateUrl != null)
- return false;
- } else if (!alternateUrl.equals(other.alternateUrl))
- return false;
- if (description == null) {
- if (other.description != null)
- return false;
- } else if (!description.equals(other.description))
- return false;
- if (id == null) {
- if (other.id != null)
- return false;
- } else if (!id.equals(other.id))
- return false;
- if (imageUrl == null) {
- if (other.imageUrl != null)
- return false;
- } else if (!imageUrl.equals(other.imageUrl))
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- if (notes == null) {
- if (other.notes != null)
- return false;
- } else if (!notes.equals(other.notes))
- return false;
- if (open == null) {
- if (other.open != null)
- return false;
- } else if (!open.equals(other.open))
- return false;
- if (pending == null) {
- if (other.pending != null)
- return false;
- } else if (!pending.equals(other.pending))
- return false;
- if (restricted == null) {
- if (other.restricted != null)
- return false;
- } else if (!restricted.equals(other.restricted))
- return false;
- if (select == null) {
- if (other.select != null)
- return false;
- } else if (!select.equals(other.select))
- return false;
- if (url == null) {
- if (other.url != null)
- return false;
- } else if (!url.equals(other.url))
- return false;
- return true;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ecomp.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; +import com.fasterxml.jackson.annotation.JsonInclude; + +/** + * This model of an application catalog entry has some EPApp fields plus + * additional fields to indicate access(ible) and select(ed) statuses. + */ +@Entity +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AppCatalogItem extends DomainVo { + + private static final long serialVersionUID = 6619663784935017846L; + + @Id + private Long id; + private String name; + private String mlAppName; + private String imageUrl; + private String description; + private String notes; + private String url; + private String alternateUrl; + private Boolean restricted; + private Boolean open; + private Boolean access; + private Boolean select; + private Boolean pending; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMlAppName() { + return mlAppName; + } + + public void setMlAppName(String mlAppName) { + this.mlAppName = mlAppName; + } + + public String getImageUrl() { + return imageUrl; + } + + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getNotes() { + return notes; + } + + public void setNotes(String notes) { + this.notes = notes; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getAlternateUrl() { + return alternateUrl; + } + + public void setAlternateUrl(String alternateUrl) { + this.alternateUrl = alternateUrl; + } + + public Boolean getRestricted() { + return restricted; + } + + public void setRestricted(Boolean restricted) { + this.restricted = restricted; + } + + public Boolean getOpen() { + return open; + } + + public void setOpen(Boolean open) { + this.open = open; + } + + public Boolean getAccess() { + return access; + } + + public void setAccess(Boolean access) { + this.access = access; + } + + public Boolean getSelect() { + return select; + } + + public void setSelect(Boolean select) { + this.select = select; + } + + public Boolean getPending() { + return pending; + } + + public void setPending(Boolean pending) { + this.pending = pending; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } + + @Override + public String toString() { + return "AppCatalogItem [id=" + id + ", name=" + name + ", access=" + access + ", select=" + select + + ", pending=" + pending + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((access == null) ? 0 : access.hashCode()); + result = prime * result + ((alternateUrl == null) ? 0 : alternateUrl.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((imageUrl == null) ? 0 : imageUrl.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((notes == null) ? 0 : notes.hashCode()); + result = prime * result + ((open == null) ? 0 : open.hashCode()); + result = prime * result + ((pending == null) ? 0 : pending.hashCode()); + result = prime * result + ((restricted == null) ? 0 : restricted.hashCode()); + result = prime * result + ((select == null) ? 0 : select.hashCode()); + result = prime * result + ((url == null) ? 0 : url.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AppCatalogItem other = (AppCatalogItem) obj; + if (access == null) { + if (other.access != null) + return false; + } else if (!access.equals(other.access)) + return false; + if (alternateUrl == null) { + if (other.alternateUrl != null) + return false; + } else if (!alternateUrl.equals(other.alternateUrl)) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (imageUrl == null) { + if (other.imageUrl != null) + return false; + } else if (!imageUrl.equals(other.imageUrl)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (notes == null) { + if (other.notes != null) + return false; + } else if (!notes.equals(other.notes)) + return false; + if (open == null) { + if (other.open != null) + return false; + } else if (!open.equals(other.open)) + return false; + if (pending == null) { + if (other.pending != null) + return false; + } else if (!pending.equals(other.pending)) + return false; + if (restricted == null) { + if (other.restricted != null) + return false; + } else if (!restricted.equals(other.restricted)) + return false; + if (select == null) { + if (other.select != null) + return false; + } else if (!select.equals(other.select)) + return false; + if (url == null) { + if (other.url != null) + return false; + } else if (!url.equals(other.url)) + return false; + return true; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCategoryFunctionsItem.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCategoryFunctionsItem.java index b1601431..9b35beb0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCategoryFunctionsItem.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCategoryFunctionsItem.java @@ -1,140 +1,140 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.ecomp.model;
-
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-/**
- * Carries row information for the functional table on the Contact Us page.
- */
-@Entity
-@JsonInclude(JsonInclude.Include.NON_NULL)
-public class AppCategoryFunctionsItem extends DomainVo {
-
- private static final long serialVersionUID = -1573834082471206458L;
-
- @Id
- private String rowId;
- private String appId;
- private String application;
- private String category;
- private String functions;
-
- public String getRowId() {
- return rowId;
- }
-
- public void setRowId(String rowId) {
- this.rowId = rowId;
- }
-
- public String getAppId() {
- return appId;
- }
-
- public void setAppId(String appId) {
- this.appId = appId;
- }
-
- public String getApplication() {
- return application;
- }
-
- public void setApplication(String appName) {
- this.application = appName;
- }
-
- public String getCategory() {
- return category;
- }
-
- public void setCategory(String category) {
- this.category = category;
- }
-
- public String getFunctions() {
- return functions;
- }
-
- public void setFunctions(String functions) {
- this.functions = functions;
- }
-
- @Override
- public String toString() {
- return "AppCategoryFunctionsItem [rowId=" + rowId + ", appId=" + appId + ", application=" + application
- + ", category=" + category + ", functions=" + functions + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((appId == null) ? 0 : appId.hashCode());
- result = prime * result + ((application == null) ? 0 : application.hashCode());
- result = prime * result + ((category == null) ? 0 : category.hashCode());
- result = prime * result + ((functions == null) ? 0 : functions.hashCode());
- result = prime * result + ((rowId == null) ? 0 : rowId.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- AppCategoryFunctionsItem other = (AppCategoryFunctionsItem) obj;
- if (appId == null) {
- if (other.appId != null)
- return false;
- } else if (!appId.equals(other.appId))
- return false;
- if (application == null) {
- if (other.application != null)
- return false;
- } else if (!application.equals(other.application))
- return false;
- if (category == null) {
- if (other.category != null)
- return false;
- } else if (!category.equals(other.category))
- return false;
- if (functions == null) {
- if (other.functions != null)
- return false;
- } else if (!functions.equals(other.functions))
- return false;
- if (rowId == null) {
- if (other.rowId != null)
- return false;
- } else if (!rowId.equals(other.rowId))
- return false;
- return true;
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ecomp.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; +import com.fasterxml.jackson.annotation.JsonInclude; + +/** + * Carries row information for the functional table on the Contact Us page. + */ +@Entity +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AppCategoryFunctionsItem extends DomainVo { + + private static final long serialVersionUID = -1573834082471206458L; + + @Id + private String rowId; + private String appId; + private String application; + private String category; + private String functions; + + public String getRowId() { + return rowId; + } + + public void setRowId(String rowId) { + this.rowId = rowId; + } + + public String getAppId() { + return appId; + } + + public void setAppId(String appId) { + this.appId = appId; + } + + public String getApplication() { + return application; + } + + public void setApplication(String appName) { + this.application = appName; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getFunctions() { + return functions; + } + + public void setFunctions(String functions) { + this.functions = functions; + } + + @Override + public String toString() { + return "AppCategoryFunctionsItem [rowId=" + rowId + ", appId=" + appId + ", application=" + application + + ", category=" + category + ", functions=" + functions + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((appId == null) ? 0 : appId.hashCode()); + result = prime * result + ((application == null) ? 0 : application.hashCode()); + result = prime * result + ((category == null) ? 0 : category.hashCode()); + result = prime * result + ((functions == null) ? 0 : functions.hashCode()); + result = prime * result + ((rowId == null) ? 0 : rowId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AppCategoryFunctionsItem other = (AppCategoryFunctionsItem) obj; + if (appId == null) { + if (other.appId != null) + return false; + } else if (!appId.equals(other.appId)) + return false; + if (application == null) { + if (other.application != null) + return false; + } else if (!application.equals(other.application)) + return false; + if (category == null) { + if (other.category != null) + return false; + } else if (!category.equals(other.category)) + return false; + if (functions == null) { + if (other.functions != null) + return false; + } else if (!functions.equals(other.functions)) + return false; + if (rowId == null) { + if (other.rowId != null) + return false; + } else if (!rowId.equals(other.rowId)) + return false; + return true; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppContactUsItem.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppContactUsItem.java index 5dc7bf57..1cfb6644 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppContactUsItem.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppContactUsItem.java @@ -1,171 +1,171 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.ecomp.model;
-
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-/**
- * An easily serializable version of row information from the fn_app_contact_us
- * table; specifically this has an app ID instead of an EPApp object.
- */
-@Entity
-@JsonInclude(JsonInclude.Include.NON_NULL)
-public class AppContactUsItem extends DomainVo {
-
- private static final long serialVersionUID = 6964210807573346262L;
-
- @Id
- private Long appId;
- private String appName;
- private String description;
- private String contactName;
- private String contactEmail;
- private String url;
- private String activeYN;
-
- public Long getAppId() {
- return appId;
- }
-
- public void setAppId(Long appId) {
- this.appId = appId;
- }
-
- public String getAppName() {
- return appName;
- }
-
- public void setAppName(String appName) {
- this.appName = appName;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getContactName() {
- return contactName;
- }
-
- public void setContactName(String contactName) {
- this.contactName = contactName;
- }
-
- public String getContactEmail() {
- return contactEmail;
- }
-
- public void setContactEmail(String contactEmail) {
- this.contactEmail = contactEmail;
- }
-
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public String getActiveYN() {
- return activeYN;
- }
-
- public void setActiveYN(String activeYN) {
- this.activeYN = activeYN;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((activeYN == null) ? 0 : activeYN.hashCode());
- result = prime * result + ((appId == null) ? 0 : appId.hashCode());
- result = prime * result + ((appName == null) ? 0 : appName.hashCode());
- result = prime * result + ((contactEmail == null) ? 0 : contactEmail.hashCode());
- result = prime * result + ((contactName == null) ? 0 : contactName.hashCode());
- result = prime * result + ((description == null) ? 0 : description.hashCode());
- result = prime * result + ((url == null) ? 0 : url.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- AppContactUsItem other = (AppContactUsItem) obj;
- if (activeYN == null) {
- if (other.activeYN != null)
- return false;
- } else if (!activeYN.equals(other.activeYN))
- return false;
- if (appId == null) {
- if (other.appId != null)
- return false;
- } else if (!appId.equals(other.appId))
- return false;
- if (appName == null) {
- if (other.appName != null)
- return false;
- } else if (!appName.equals(other.appName))
- return false;
- if (contactEmail == null) {
- if (other.contactEmail != null)
- return false;
- } else if (!contactEmail.equals(other.contactEmail))
- return false;
- if (contactName == null) {
- if (other.contactName != null)
- return false;
- } else if (!contactName.equals(other.contactName))
- return false;
- if (description == null) {
- if (other.description != null)
- return false;
- } else if (!description.equals(other.description))
- return false;
- if (url == null) {
- if (other.url != null)
- return false;
- } else if (!url.equals(other.url))
- return false;
- return true;
- }
-
- @Override
- public String toString() {
- return "AppContactUsItem [appId=" + appId + ", appName=" + appName + ", description=" + description
- + ", contactName=" + contactName + ", contactEmail=" + contactEmail + ", url=" + url + ", activeYN="
- + activeYN + "]";
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ecomp.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; +import com.fasterxml.jackson.annotation.JsonInclude; + +/** + * An easily serializable version of row information from the fn_app_contact_us + * table; specifically this has an app ID instead of an EPApp object. + */ +@Entity +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AppContactUsItem extends DomainVo { + + private static final long serialVersionUID = 6964210807573346262L; + + @Id + private Long appId; + private String appName; + private String description; + private String contactName; + private String contactEmail; + private String url; + private String activeYN; + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getContactName() { + return contactName; + } + + public void setContactName(String contactName) { + this.contactName = contactName; + } + + public String getContactEmail() { + return contactEmail; + } + + public void setContactEmail(String contactEmail) { + this.contactEmail = contactEmail; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getActiveYN() { + return activeYN; + } + + public void setActiveYN(String activeYN) { + this.activeYN = activeYN; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((activeYN == null) ? 0 : activeYN.hashCode()); + result = prime * result + ((appId == null) ? 0 : appId.hashCode()); + result = prime * result + ((appName == null) ? 0 : appName.hashCode()); + result = prime * result + ((contactEmail == null) ? 0 : contactEmail.hashCode()); + result = prime * result + ((contactName == null) ? 0 : contactName.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((url == null) ? 0 : url.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AppContactUsItem other = (AppContactUsItem) obj; + if (activeYN == null) { + if (other.activeYN != null) + return false; + } else if (!activeYN.equals(other.activeYN)) + return false; + if (appId == null) { + if (other.appId != null) + return false; + } else if (!appId.equals(other.appId)) + return false; + if (appName == null) { + if (other.appName != null) + return false; + } else if (!appName.equals(other.appName)) + return false; + if (contactEmail == null) { + if (other.contactEmail != null) + return false; + } else if (!contactEmail.equals(other.contactEmail)) + return false; + if (contactName == null) { + if (other.contactName != null) + return false; + } else if (!contactName.equals(other.contactName)) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (url == null) { + if (other.url != null) + return false; + } else if (!url.equals(other.url)) + return false; + return true; + } + + @Override + public String toString() { + return "AppContactUsItem [appId=" + appId + ", appName=" + appName + ", description=" + description + + ", contactName=" + contactName + ", contactEmail=" + contactEmail + ", url=" + url + ", activeYN=" + + activeYN + "]"; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/CommonWidgetsEnum.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/CommonWidgetsEnum.java index 994108dd..cb712a22 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/CommonWidgetsEnum.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/CommonWidgetsEnum.java @@ -1,36 +1,36 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.ecomp.model;
-
-public enum CommonWidgetsEnum{
- NEWS("news"),
- EVENTS("events"),
- RESOURCES("resources");
-
- private String value;
- private CommonWidgetsEnum(String value){
- this.value = value;
- }
-
- @Override
- public String toString() {
- return value;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ecomp.model; + +public enum CommonWidgetsEnum{ + NEWS("news"), + EVENTS("events"), + RESOURCES("resources"); + + private String value; + private CommonWidgetsEnum(String value){ + this.value = value; + } + + @Override + public String toString() { + return value; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestResponse.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestResponse.java index 3572d6a6..21c6dfe7 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestResponse.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestResponse.java @@ -1,101 +1,101 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.ecomp.model;
-
-public class PortalRestResponse<T> {
-
- private PortalRestStatusEnum status;
- private String message;
-
- private T response;
-
- public PortalRestResponse(){};
-
- public PortalRestResponse(PortalRestStatusEnum status, String message, T response){
- this.status = status;
- this.message = message;
- this.response = response;
- }
-
- public PortalRestStatusEnum getStatus() {
- return status;
- }
-
- public void setStatus(PortalRestStatusEnum status) {
- this.status = status;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public T getResponse() {
- return response;
- }
-
- public void setResponse(T response) {
- this.response = response;
- }
-
- @Override
- public String toString() {
- return "PortalRestResponse [status=" + status + ", message=" + message + ", response=" + response + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((message == null) ? 0 : message.hashCode());
- result = prime * result + ((response == null) ? 0 : response.hashCode());
- result = prime * result + ((status == null) ? 0 : status.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- PortalRestResponse other = (PortalRestResponse) obj;
- if (message == null) {
- if (other.message != null)
- return false;
- } else if (!message.equals(other.message))
- return false;
- if (response == null) {
- if (other.response != null)
- return false;
- } else if (!response.equals(other.response))
- return false;
- if (status != other.status)
- return false;
- return true;
- };
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ecomp.model; + +public class PortalRestResponse<T> { + + private PortalRestStatusEnum status; + private String message; + + private T response; + + public PortalRestResponse(){}; + + public PortalRestResponse(PortalRestStatusEnum status, String message, T response){ + this.status = status; + this.message = message; + this.response = response; + } + + public PortalRestStatusEnum getStatus() { + return status; + } + + public void setStatus(PortalRestStatusEnum status) { + this.status = status; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public T getResponse() { + return response; + } + + public void setResponse(T response) { + this.response = response; + } + + @Override + public String toString() { + return "PortalRestResponse [status=" + status + ", message=" + message + ", response=" + response + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((message == null) ? 0 : message.hashCode()); + result = prime * result + ((response == null) ? 0 : response.hashCode()); + result = prime * result + ((status == null) ? 0 : status.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PortalRestResponse other = (PortalRestResponse) obj; + if (message == null) { + if (other.message != null) + return false; + } else if (!message.equals(other.message)) + return false; + if (response == null) { + if (other.response != null) + return false; + } else if (!response.equals(other.response)) + return false; + if (status != other.status) + return false; + return true; + }; + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestStatusEnum.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestStatusEnum.java index b4dc63ab..6c264ee2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestStatusEnum.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestStatusEnum.java @@ -1,36 +1,36 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.ecomp.model;
-
-public enum PortalRestStatusEnum{
- OK("ok"),
- WARN("WARNING"),
- ERROR("error");
-
- private String value;
- private PortalRestStatusEnum(String value){
- this.value = value;
- }
-
- @Override
- public String toString() {
- return value;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ecomp.model; + +public enum PortalRestStatusEnum{ + OK("ok"), + WARN("WARNING"), + ERROR("error"); + + private String value; + private PortalRestStatusEnum(String value){ + this.value = value; + } + + @Override + public String toString() { + return value; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/SearchResultItem.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/SearchResultItem.java index c6538470..dde9bc27 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/SearchResultItem.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ecomp/model/SearchResultItem.java @@ -1,86 +1,86 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.ecomp.model;
-
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-@Entity
-@JsonInclude(JsonInclude.Include.NON_NULL)
-public class SearchResultItem extends DomainVo{
-
- @Id
- private String rowId;
-
- @JsonProperty("category")
- private String category;
-
- @JsonProperty("name")
- private String name;
-
- @JsonProperty("target")
- private String target;
-
- @JsonProperty("uuid")
- private String uuid;
-
- public String getUuid() {
- return uuid;
- }
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
- public String getRowId() {
- return rowId;
- }
- public void setRowId(String rowId) {
- this.rowId = rowId;
- }
- public String getCategory() {
- return category;
- }
- public void setCategory(String category) {
- this.category = category;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
-
- public String getTarget() {
- return target;
- }
- public void setTarget(String target) {
- this.target = target;
- }
- @Override
- public String toString() {
- return "SearchResultItem [rowId=" + rowId + ", category=" + category + ", name=" + name + ", target=" + target
- + ", uuid=" + uuid + "]";
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ecomp.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +@Entity +@JsonInclude(JsonInclude.Include.NON_NULL) +public class SearchResultItem extends DomainVo{ + + @Id + private String rowId; + + @JsonProperty("category") + private String category; + + @JsonProperty("name") + private String name; + + @JsonProperty("target") + private String target; + + @JsonProperty("uuid") + private String uuid; + + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public String getRowId() { + return rowId; + } + public void setRowId(String rowId) { + this.rowId = rowId; + } + public String getCategory() { + return category; + } + public void setCategory(String category) { + this.category = category; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public String getTarget() { + return target; + } + public void setTarget(String target) { + this.target = target; + } + @Override + public String toString() { + return "SearchResultItem [rowId=" + rowId + ", category=" + category + ", name=" + name + ", target=" + target + + ", uuid=" + uuid + "]"; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/exceptions/NoHealthyServiceException.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/exceptions/NoHealthyServiceException.java index ce0366c8..55872f2d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/exceptions/NoHealthyServiceException.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/exceptions/NoHealthyServiceException.java @@ -1,36 +1,36 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.exceptions;
-
-import com.ecwid.consul.ConsulException;
-
-public class NoHealthyServiceException extends ConsulException{
-
- private static final long serialVersionUID = -7089437673127729813L;
-
- public NoHealthyServiceException(String message){
- super(message);
- }
-
- @Override
- public String toString() {
- return "NoHealthyServiceException [] " + this.getMessage();
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.exceptions; + +import com.ecwid.consul.ConsulException; + +public class NoHealthyServiceException extends ConsulException{ + + private static final long serialVersionUID = -7089437673127729813L; + + public NoHealthyServiceException(String message){ + super(message); + } + + @Override + public String toString() { + return "NoHealthyServiceException [] " + this.getMessage(); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/interceptor/PortalResourceInterceptor.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/interceptor/PortalResourceInterceptor.java index 9a2fc4de..ba4f2af1 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/interceptor/PortalResourceInterceptor.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/interceptor/PortalResourceInterceptor.java @@ -18,7 +18,6 @@ * ================================================================================*/ package org.openecomp.portalapp.portal.interceptor; -import java.net.URL; import java.nio.charset.Charset; import java.util.Base64; import java.util.Set; @@ -59,7 +58,7 @@ public class PortalResourceInterceptor extends ResourceInterceptor { private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class); @Autowired - private RemoteWebServiceCallService remoteWebServiceCallService; + private RemoteWebServiceCallService remoteWebServiceCallService; @Autowired private ManageService manageService; @@ -196,11 +195,12 @@ public class PortalResourceInterceptor extends ResourceInterceptor { * @throws Exception */ private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception { - String uri = request.getRequestURI().toString(); uri = uri.substring(uri.indexOf("/", 1)); - + final String authHeader = request.getHeader("Authorization"); + + // Unauthorized access due to missing HTTP Authorization request header if (authHeader == null) { final String msg = "no authorization found"; logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg); @@ -210,7 +210,7 @@ public class PortalResourceInterceptor extends ResourceInterceptor { String[] accountNamePassword = getUserNamePassword(authHeader); if (accountNamePassword == null || accountNamePassword.length != 2) { - final String msg = "failed to get username and password from auth header"; + final String msg = "failed to get username and password from Atuhorization header"; logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg); sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg); return false; @@ -218,54 +218,48 @@ public class PortalResourceInterceptor extends ResourceInterceptor { BasicAuthCredentials creds; try { - creds = basicAuthService.getBasicAuthCredentialByAppName(accountNamePassword[0]); + creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0], + encrypted(accountNamePassword[1])); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e); final String msg = "Failed while getting basic authentication credential: " + e.toString(); sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); throw e; } - - boolean isAllowedEp = false; - for(EPEndpoint ep: creds.getEndpoints()){ - if(ep.getName().equals(uri)){ - isAllowedEp = true; - break; - } - } - if(!isAllowedEp){ - response.setStatus(401); - response.setContentType("application/json"); - response.getWriter().write("{\"error\":\"Unauthorized: Endpoint access denied\"}"); - response.getWriter().flush(); - response.getWriter().close(); + + // Unauthorized access due to invalid credentials (username and + // password) + if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) { + final String msg = "Unauthorized: Access denied"; + logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg); + sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg); return false; } - - if (creds == null) { - final String msg = "failed to find match for credentials"; + + // Unauthorized access due to inactive account + if (creds.getIsActive().equals("N")) { + final String msg = "Unauthorized: The account is inactive"; logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg); sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg); return false; } - - boolean isAuth; - try { - isAuth = authorization(authHeader, creds.getApplicationName(), creds.getPassword()); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to check authorization", e); - final String msg = "failed while checking authorization: " + e.toString(); - sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); - throw e; + boolean isAllowedEp = false; + for (EPEndpoint ep : creds.getEndpoints()) { + if (ep.getName().equals(uri)) { + isAllowedEp = true; + break; + } } - if (!isAuth) { - response.setStatus(401); - response.setContentType("application/json"); - response.getWriter().write("{\"error\":\"Unauthorized: Invalid username or password\"}"); - response.getWriter().flush(); - response.getWriter().close(); - final String msg = "Unauthorized: Access denied"; + // If user doesn't specify any endpoint, allow all endpoints for that + // account + if (creds.getEndpoints().size() == 0) + isAllowedEp = true; + + // Unauthorized access due to the invalid endpoints + if (!isAllowedEp) { + final String msg = "Unauthorized: Endpoint access denied"; + logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg); sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg); return false; } @@ -274,32 +268,6 @@ public class PortalResourceInterceptor extends ResourceInterceptor { return true; } - /** - * - * Basic Authorization check - * - * @param auth - * @param security_user - * @param security_pass - * @return - * @throws Exception - */ - - protected boolean authorization(String auth, String security_user, String security_pass) throws Exception { - - if (auth != null && auth.startsWith("Basic")) { - String[] usernamePassword = getUserNamePassword(auth); - if (security_user.equals(usernamePassword[0]) && decrypted(security_pass).equals(usernamePassword[1])) - return true; - } - return false; - } - - public static void main(String str[]) { - System.out.println(new PortalResourceInterceptor().getUserNamePassword("Basic Qy1CVVM6X3Bhc3M=")[0]); - System.out.println(new PortalResourceInterceptor().getUserNamePassword("Basic Qy1CVVM6X3Bhc3M=")[1]); - } - private String[] getUserNamePassword(String authValue) { String base64Credentials = authValue.substring("Basic".length()).trim(); String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8")); @@ -320,6 +288,20 @@ public class PortalResourceInterceptor extends ResourceInterceptor { return result; } + private String encrypted(String decryptedPwd) throws Exception { + String result = ""; + if (decryptedPwd != null & decryptedPwd.length() > 0) { + try { + result = CipherUtil.encrypt(decryptedPwd, + SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e); + throw e; + } + } + return result; + } + private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) { for (String roleFunction : roleFunctions) { if (portalApiPath.matches(roleFunction)) diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/listener/HealthMonitor.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/listener/HealthMonitor.java index b8e608cd..9de7a4c9 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/listener/HealthMonitor.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/listener/HealthMonitor.java @@ -1,355 +1,341 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.listener;
-
-import java.util.List;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-
-import org.hibernate.Query;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.ueb.EPUebHelper;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.transaction.annotation.Transactional;
-
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class HealthMonitor {
-
- @Autowired
- private SessionFactory sessionFactory;
-
- @Autowired
- private EPUebHelper epUebHelper;
-
- private static boolean databaseUp;
- private static boolean uebUp;
- private static boolean frontEndUp;
- private static boolean backEndUp;
- private static boolean dbClusterStatusOk;
- private static boolean dbPermissionsOk;
- public static boolean isSuspended = false;
-
- Thread healthMonitorThread;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthMonitor.class);
-
- public HealthMonitor() {
-
- }
-
- public static boolean isDatabaseUp() {
- return databaseUp;
- }
-
- public static boolean isClusterStatusOk() {
- return dbClusterStatusOk;
- }
-
- public static boolean isDatabasePermissionsOk() {
- return dbPermissionsOk;
- }
-
- public static boolean isUebUp() {
- return uebUp;
- }
-
- public static boolean isFrontEndUp() {
- return frontEndUp;
- }
-
- public static boolean isBackEndUp() {
- return backEndUp;
- }
-
- private void monitorEPHealth() throws InterruptedException {
-
- int numIntervalsDatabaseHasBeenDown = 0;
- int numIntervalsClusterNotHealthy = 0;
- int numIntervalsDatabasePermissionsIncorrect = 0;
- int numIntervalsUebHasBeenDown = 0;
-
- logger.debug(EELFLoggerDelegate.debugLogger, "==> Health Monitor thread started");
-
- long sleepInterval = (Long
- .valueOf(SystemProperties.getProperty(EPCommonSystemProperties.HEALTH_POLL_INTERVAL_SECONDS)) * 1000);
- long numIntervalsBetweenAlerts = Long
- .valueOf(SystemProperties.getProperty(EPCommonSystemProperties.HEALTHFAIL_ALERT_EVERY_X_INTERVALS));
- logger.debug(EELFLoggerDelegate.debugLogger,
- "Polling health every " + sleepInterval + " milliseconds. Alerting every "
- + (sleepInterval * numIntervalsBetweenAlerts) / 1000 + " seconds when component remains down.");
-
- while (true) {
- //
- // Get DB status. If down, signal alert once every X intervals.
- //
- databaseUp = this.checkIfDatabaseUp();
- if (databaseUp == false) {
-
- if ((numIntervalsDatabaseHasBeenDown % numIntervalsBetweenAlerts) == 0) {
- // Write a Log entry that will generate an alert
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHealthCheckMySqlError);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "Database down, logging to error log to trigger alert.");
- numIntervalsDatabaseHasBeenDown++;
- } else {
- numIntervalsDatabaseHasBeenDown = 0;
- }
- }
-
- dbClusterStatusOk = this.checkClusterStatus();
- if (dbClusterStatusOk == false) {
-
- if ((numIntervalsClusterNotHealthy % numIntervalsBetweenAlerts) == 0) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHealthCheckMySqlError);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "Cluster nodes appear to be down, logging to error log to trigger alert.");
- numIntervalsClusterNotHealthy++;
- } else {
- numIntervalsClusterNotHealthy = 0;
- }
- }
-
- dbPermissionsOk = this.checkDatabaseAndPermissions();
- if (dbPermissionsOk == false) {
-
- if ((numIntervalsDatabasePermissionsIncorrect % numIntervalsBetweenAlerts) == 0) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHealthCheckMySqlError);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "Database permissions don't seem correct, logging to error log to trigger alert.");
- numIntervalsDatabasePermissionsIncorrect++;
- } else {
- numIntervalsDatabasePermissionsIncorrect = 0;
- }
- }
-
- //
- // Get UEB status. Publish a bogus message to EP inbox, if 200 OK
- // returned, status is Up.
- // If down, signal alert once every X intervals.
- // EP will ignore this bogus message.
- //
- uebUp = this.checkIfUebUp();
- if (uebUp == false) {
-
- if ((numIntervalsUebHasBeenDown % numIntervalsBetweenAlerts) == 0) {
- // Write a Log entry that will generate an alert
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHealthCheckUebClusterError);
- logger.debug(EELFLoggerDelegate.debugLogger, "UEB down, logging to error log to trigger alert");
- numIntervalsUebHasBeenDown++;
- } else {
- numIntervalsUebHasBeenDown = 0;
- }
- }
-
- // The front end should be up because the API is called through
- // proxy front end server.
- frontEndUp = true;
-
- // If the rest API called, the backend is always up
- backEndUp = true;
-
- //
- // future nice to have...get Partner status
- //
- // For all apps exposing a rest url, query one of the rest
- // urls(/roles?) and manage a list
- // of app name/status. We might not return back a non 200 OK in
- // health check, but we
- // could return information in the json content of a health check.
- //
-
- //
- // Get DB status. If down, signal alert once every X intervals.
- //
- if (Thread.interrupted()) {
- logger.info(EELFLoggerDelegate.errorLogger, "==> UebMainHandler exiting");
- break;
- }
-
- try {
- Thread.sleep(sleepInterval);
- } catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "monitorEPHealth interrupted", e);
- Thread.currentThread().interrupt();
- }
- }
- }
-
- @PostConstruct
- public void initHealthMonitor() {
-
- healthMonitorThread = new Thread("EP HealthMonitor thread") {
- public void run() {
- try {
- monitorEPHealth();
- } catch (InterruptedException e) {
- logger.debug(EELFLoggerDelegate.debugLogger, "healthMonitorThread interrupted", e);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "healthMonitorThread failed", e);
- }
- }
- };
- if (healthMonitorThread != null) {
- healthMonitorThread.start();
- }
- }
-
- @PreDestroy
- public void closeHealthMonitor() {
- this.healthMonitorThread.interrupt();
- }
-
- private boolean checkIfDatabaseUp() {
-
- boolean isUp = false;
-
- Session localSession = null;
-
- try {
- localSession = sessionFactory.openSession();
-
- if (localSession != null) {
-
- String sql = "select app_name from fn_app where app_id=1";
- Query query = localSession.createSQLQuery(sql);
- @SuppressWarnings("unchecked")
- List<String> queryList = query.list();
- if (queryList != null) {
- isUp = true;
- }
- localSession.close();
- }
- } catch (Exception e) {
- logger.debug(EELFLoggerDelegate.debugLogger, "checkIfDatabaseUp failed", e);
- isUp = false;
- }
-
- return isUp;
- }
-
- private boolean checkClusterStatus() {
-
- boolean isUp = false;
-
- Session localSession = null;
-
- try {
- localSession = sessionFactory.openSession();
- if (localSession != null) {
- // If all nodes are unhealthy in a cluster, this will throw an
- // exception
- String sql = "select * from mysql.user";
- Query query = localSession.createSQLQuery(sql);
- @SuppressWarnings("unchecked")
- List<String> queryList = query.list();
- if (queryList != null) {
- isUp = true;
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "checkClusterStatus failed", e);
- if ((e.getCause() != null) && (e.getCause().getMessage() != null)) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "checkClusterStatus() exception msg = " + e.getCause().getMessage());
- }
- isUp = false;
- } finally {
- if (localSession != null) {
- localSession.close();
- }
- }
-
- return isUp;
-
- }
-
- private boolean checkDatabaseAndPermissions() {
-
- boolean isUp = false;
-
- Session localSession = null;
-
- try {
- localSession = sessionFactory.openSession();
- if (localSession != null) {
- String sql = "SHOW GRANTS FOR CURRENT_USER";
- Query query = localSession.createSQLQuery(sql);
- @SuppressWarnings("unchecked")
- List<String> grantsList = query.list();
- for (String str : grantsList) {
- if ((str.toUpperCase().contains("ALL"))
- || (str.toUpperCase().contains("DELETE") && str.toUpperCase().contains("SELECT")
- && str.toUpperCase().contains("UPDATE") && str.toUpperCase().contains("INSERT"))) {
- isUp = true;
- break;
- }
- }
- if (isUp == false) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "checkDatabaseAndPermissions() returning false. SHOW GRANTS FOR CURRENT_USER being dumped:");
- for (String str : grantsList) {
- logger.error(EELFLoggerDelegate.errorLogger, "grants output item = [" + str + "]");
- }
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "checkDatabaseAndPermissions failed", e);
- if ((e.getCause() != null) && (e.getCause().getMessage() != null)) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "checkDatabaseAndPermissions() exception msg = " + e.getCause().getMessage());
- }
- isUp = false;
- } finally {
- if (localSession != null) {
- localSession.close();
- }
- }
-
- return isUp;
-
- }
-
- private boolean checkIfUebUp() {
- boolean uebUp = false;
- try {
- boolean isAvailable = epUebHelper.checkAvailability();
- boolean messageCanBeSent = epUebHelper.MessageCanBeSentToTopic();
- uebUp = (isAvailable && messageCanBeSent);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "checkIfUebUp failed", e);
- }
-
- return uebUp;
-
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.listener; + +import java.util.Date; +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.openecomp.portalapp.portal.domain.SharedContext; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.service.SharedContextService; +import org.openecomp.portalapp.portal.ueb.EPUebHelper; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class HealthMonitor { + + @Autowired + private SessionFactory sessionFactory; + + @Autowired + private EPUebHelper epUebHelper; + + @Autowired + private SharedContextService sharedContextService; + + private static boolean databaseUp; + private static boolean uebUp; + private static boolean frontEndUp; + private static boolean backEndUp; + private static boolean dbClusterStatusOk; + private static boolean dbPermissionsOk; + public static boolean isSuspended = false; + + private Thread healthMonitorThread; + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthMonitor.class); + + public HealthMonitor() { + + } + + public static boolean isDatabaseUp() { + return databaseUp; + } + + public static boolean isClusterStatusOk() { + return dbClusterStatusOk; + } + + public static boolean isDatabasePermissionsOk() { + return dbPermissionsOk; + } + + public static boolean isUebUp() { + return uebUp; + } + + public static boolean isFrontEndUp() { + return frontEndUp; + } + + public static boolean isBackEndUp() { + return backEndUp; + } + + private void monitorEPHealth() throws InterruptedException { + + int numIntervalsDatabaseHasBeenDown = 0; + int numIntervalsClusterNotHealthy = 0; + int numIntervalsDatabasePermissionsIncorrect = 0; + int numIntervalsUebHasBeenDown = 0; + + logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth started"); + + long sleepInterval = (Long + .valueOf(SystemProperties.getProperty(EPCommonSystemProperties.HEALTH_POLL_INTERVAL_SECONDS)) * 1000); + long numIntervalsBetweenAlerts = Long + .valueOf(SystemProperties.getProperty(EPCommonSystemProperties.HEALTHFAIL_ALERT_EVERY_X_INTERVALS)); + logger.debug(EELFLoggerDelegate.debugLogger, + "monitorEPHealth: Polling health every " + sleepInterval + " milliseconds. Alerting every " + + (sleepInterval * numIntervalsBetweenAlerts) / 1000 + " seconds when component remains down."); + + while (true) { + // + // Get DB status. If down, signal alert once every X intervals. + // + databaseUp = this.checkIfDatabaseUp(); + if (databaseUp == false) { + if ((numIntervalsDatabaseHasBeenDown % numIntervalsBetweenAlerts) == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "monitorEPHealth: database down, logging to error log to trigger alert."); + // Write a Log entry that will generate an alert + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHealthCheckMySqlError); + numIntervalsDatabaseHasBeenDown++; + } else { + numIntervalsDatabaseHasBeenDown = 0; + } + } + + dbClusterStatusOk = this.checkClusterStatus(); + if (dbClusterStatusOk == false) { + if ((numIntervalsClusterNotHealthy % numIntervalsBetweenAlerts) == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "monitorEPHealth: cluster nodes down, logging to error log to trigger alert."); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHealthCheckMySqlError); + numIntervalsClusterNotHealthy++; + } else { + numIntervalsClusterNotHealthy = 0; + } + } + + dbPermissionsOk = this.checkDatabasePermissions(); + if (dbPermissionsOk == false) { + if ((numIntervalsDatabasePermissionsIncorrect % numIntervalsBetweenAlerts) == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "monitorEPHealth: database permissions not correct, logging to error log to trigger alert."); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHealthCheckMySqlError); + numIntervalsDatabasePermissionsIncorrect++; + } else { + numIntervalsDatabasePermissionsIncorrect = 0; + } + } + + // + // Get UEB status. Publish a bogus message to EP inbox, if 200 OK + // returned, status is Up. + // If down, signal alert once every X intervals. + // EP will ignore this bogus message. + // + uebUp = this.checkIfUebUp(); + if (uebUp == false) { + if ((numIntervalsUebHasBeenDown % numIntervalsBetweenAlerts) == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, "UEB down, logging to error log to trigger alert"); + // Write a Log entry that will generate an alert + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHealthCheckUebClusterError); + numIntervalsUebHasBeenDown++; + } else { + numIntervalsUebHasBeenDown = 0; + } + } + + // The front end should be up because the API is called through + // proxy front end server. + frontEndUp = true; + + // If the rest API called, the backend is always up + backEndUp = true; + + // + // future nice to have...get Partner status + // + // For all apps exposing a rest url, query one of the rest + // urls(/roles?) and manage a list + // of app name/status. We might not return back a non 200 OK in + // health check, but we + // could return information in the json content of a health check. + // + + if (Thread.interrupted()) { + logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth: interrupted, leaving loop"); + break; + } + + try { + Thread.sleep(sleepInterval); + } catch (InterruptedException e) { + logger.error(EELFLoggerDelegate.errorLogger, "monitorEPHealth interrupted", e); + Thread.currentThread().interrupt(); + } + } + } + + @PostConstruct + public void initHealthMonitor() { + + healthMonitorThread = new Thread("EP HealthMonitor thread") { + public void run() { + try { + monitorEPHealth(); + } catch (InterruptedException e) { + logger.debug(EELFLoggerDelegate.debugLogger, "healthMonitorThread interrupted", e); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "healthMonitorThread failed", e); + } + } + }; + if (healthMonitorThread != null) { + healthMonitorThread.start(); + } + } + + @PreDestroy + public void closeHealthMonitor() { + this.healthMonitorThread.interrupt(); + } + + /** + * Writes and reads the database; cleans up when finished. + * + * @return True on success; false otherwise. + */ + private boolean checkIfDatabaseUp() { + boolean isUp = false; + try { + final Date now = new Date(); + final String contextId = "checkIfDatabaseUp-" + Long.toString(now.getTime()); + final String key = "checkIfDatabaseUp-key"; + final String value = "checkIfDatabaseUp-value"; + sharedContextService.addSharedContext(contextId, key, value); + SharedContext sc = sharedContextService.getSharedContext(contextId, key); + if (sc == null || sc.getCvalue() == null || !value.equals(sc.getCvalue())) + throw new Exception("Failed to retrieve shared context"); + int removed = sharedContextService.deleteSharedContexts(contextId); + if (removed != 1) + throw new Exception("Failed to delete shared context"); + isUp = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "checkIfDatabaseUp failed", e); + isUp = false; + } + return isUp; + } + + private boolean checkClusterStatus() { + boolean isUp = false; + Session localSession = null; + try { + localSession = sessionFactory.openSession(); + if (localSession != null) { + // If all nodes are unhealthy in a cluster, this will throw an + // exception + String sql = "select * from mysql.user"; + Query query = localSession.createSQLQuery(sql); + @SuppressWarnings("unchecked") + List<String> queryList = query.list(); + if (queryList != null) { + isUp = true; + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "checkClusterStatus failed", e); + if ((e.getCause() != null) && (e.getCause().getMessage() != null)) { + logger.error(EELFLoggerDelegate.errorLogger, + "checkClusterStatus() exception cause", e.getCause()); + } + isUp = false; + } finally { + if (localSession != null) { + localSession.close(); + } + } + return isUp; + } + + private boolean checkDatabasePermissions() { + boolean isUp = false; + Session localSession = null; + try { + localSession = sessionFactory.openSession(); + if (localSession != null) { + String sql = "SHOW GRANTS FOR CURRENT_USER"; + Query query = localSession.createSQLQuery(sql); + @SuppressWarnings("unchecked") + List<String> grantsList = query.list(); + for (String str : grantsList) { + if ((str.toUpperCase().contains("ALL")) + || (str.toUpperCase().contains("DELETE") && str.toUpperCase().contains("SELECT") + && str.toUpperCase().contains("UPDATE") && str.toUpperCase().contains("INSERT"))) { + isUp = true; + break; + } + } + if (isUp == false) { + logger.error(EELFLoggerDelegate.errorLogger, + "checkDatabaseAndPermissions() returning false. SHOW GRANTS FOR CURRENT_USER being dumped:"); + for (String str : grantsList) { + logger.error(EELFLoggerDelegate.errorLogger, "grants output item = [" + str + "]"); + } + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "checkDatabasePermissions failed", e); + if ((e.getCause() != null) && (e.getCause().getMessage() != null)) { + logger.error(EELFLoggerDelegate.errorLogger, + "checkDatabasePermissions() exception msg = ", e.getCause()); + } + isUp = false; + } finally { + if (localSession != null) { + localSession.close(); + } + } + return isUp; + } + + private boolean checkIfUebUp() { + boolean uebUp = false; + try { + boolean isAvailable = epUebHelper.checkAvailability(); + boolean messageCanBeSent = epUebHelper.MessageCanBeSentToTopic(); + uebUp = (isAvailable && messageCanBeSent); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "checkIfUebUp failed", e); + } + return uebUp; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/listener/UserContextListener.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/listener/UserContextListener.java index 05af7388..e2176ee9 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/listener/UserContextListener.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/listener/UserContextListener.java @@ -1,51 +1,51 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.listener;
-
-import java.util.HashMap;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletContextEvent;
-import javax.servlet.ServletContextListener;
-import javax.servlet.annotation.WebListener;
-
-@WebListener
-public class UserContextListener implements ServletContextListener{
- @SuppressWarnings("rawtypes")
- public void contextInitialized(ServletContextEvent event){
- ServletContext context = event.getServletContext();
- //
- // instanciate a map to store references to all the active
- // sessions and bind it to context scope.
- //
- HashMap activeUsers = new HashMap();
- context.setAttribute("activeUsers", activeUsers);
- }
-
- /**
- * Needed for the ServletContextListener interface.
- */
- public void contextDestroyed(ServletContextEvent event){
- // To overcome the problem with losing the session references
- // during server restarts, put code here to serialize the
- // activeUsers HashMap. Then put code in the contextInitialized
- // method that reads and reloads it if it exists...
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.listener; + +import java.util.HashMap; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +@WebListener +public class UserContextListener implements ServletContextListener{ + @SuppressWarnings("rawtypes") + public void contextInitialized(ServletContextEvent event){ + ServletContext context = event.getServletContext(); + // + // instanciate a map to store references to all the active + // sessions and bind it to context scope. + // + HashMap activeUsers = new HashMap(); + context.setAttribute("activeUsers", activeUsers); + } + + /** + * Needed for the ServletContextListener interface. + */ + public void contextDestroyed(ServletContextEvent event){ + // To overcome the problem with losing the session references + // during server restarts, put code here to serialize the + // activeUsers HashMap. Then put code in the contextInitialized + // method that reads and reloads it if it exists... + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPAuditLog.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPAuditLog.java index 965866c8..bfe81a2b 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPAuditLog.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPAuditLog.java @@ -1,31 +1,31 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.logging.aop;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-@Target({ElementType.METHOD, ElementType.TYPE})
-@Retention(RetentionPolicy.RUNTIME)
-public @interface EPAuditLog {
- String value() default "";
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.logging.aop; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface EPAuditLog { + String value() default ""; +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPMetricsLog.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPMetricsLog.java index ab8a3672..ce98b1c6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPMetricsLog.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPMetricsLog.java @@ -1,31 +1,31 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.logging.aop;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-@Target({ElementType.METHOD, ElementType.TYPE})
-@Retention(RetentionPolicy.RUNTIME)
-public @interface EPMetricsLog {
- String value() default "";
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.logging.aop; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface EPMetricsLog { + String value() default ""; +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/ApplicationCodes.properties b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/ApplicationCodes.properties index 6ee63b24..cd686ce2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/ApplicationCodes.properties +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/ApplicationCodes.properties @@ -1,141 +1,141 @@ -###
-# ================================================================================
-# ECOMP Portal
-# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property
-# ================================================================================
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ================================================================================
-###
-########################################################################
-#Resource key=Error Code|Message text|Resolution text |Description text
-#######
-#Newlines can be utilized to add some clarity ensuring continuing line
-#has atleast one leading space
-#ResourceKey=\
-# ERR0000E\
-# Sample error msg txt\
-# Sample resolution msg\
-# Sample description txt
-#
-######
-#Error code classification category
-#100 Permission errors
-#200 Availability errors/Timeouts
-#300 Data errors
-#400 Schema Interface type/validation errors
-#500 Business process errors
-#900 Unknown errors
-#
-########################################################################
-
-# Define Alarm Codes Specific to ECOMP Portal
-BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT= ||Reason: {0}.|\
- An Authentication failure occurred during access to UEB server. Please check that UEB keys are configured correctly under fusion.properties file.
-
-BERESTAPIAUTHENTICATIONERROR = |||Please check application credentials defined in Database or portal.properties file.
-
-INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT=||Description: {0}.|Please check the logs for more information.
-
-INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT=||Description: {0}.|Please check the logs for more information.
-
-INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT=||Description: {0}.|Please check the logs for more information.
-
-INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT=||Description: {0}.|Please check the logs for more information.
-
-BEHEALTHCHECKERROR= |||Please check the logs for more information.
-
-BEHEALTHCHECKMYSQLERROR= ||Please check the logs for more information.|\
- Check connectivity to MYSQL is configured correctly under system.properties file.
-
-BEHEALTHCHECKUEBCLUSTERERROR= ||Please check the logs for more information.|\
- Check connectivity to UEB cluster which is configured under portal.properties file.
-
-FEHEALTHCHECKERROR= |||Please check connectivity from this FE instance towards BE or BE Load Balancer.
-
-BEHEALTHCHECKRECOVERY= |||Please check logs for more specific information about the problem.
-
-BEHEALTHCHECKMYSQLRECOVERY= |||Please check logs for more specific information about the problem.
-
-BEHEALTHCHECKUEBCLUSTERRECOVERY= |||Please check logs for more specific information about the problem.
-
-FEHEALTHCHECKRECOVERY= |||Please check logs for more specific information about the problem.
-
-#UEB communication
-BEUEBCONNECTIONERROR_ONE_ARGUMENT= ||Reason: {0}.|\
- Please check UEB server list and keys configured under Portal.Properties file.
-
-BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT= ||Cannot reach host {0}.|\
- Please check UEB server list and keys configured under Portal.Properties file.
-
-#Onboarding apps
-BEUEBREGISTERONBOARDINGAPPERROR= ||Reason: {0}.|\
- Please check UEB server list and keys configured under Portal.Properties file.
-
-#HTTP communication
-BEHTTPCONNECTIONERROR_ONE_ARGUMENT= ||Reason: {0}.|Please check the logs for more information.
-
-INTERNALCONNECTIONINFO_ONE_ARGUMENT= ||Description: {0}.|Please check the logs for more information.
-
-INTERNALCONNECTIONWARNING_ONE_ARGUMENT= ||Description: {0}.|Please check the logs for more information.
-
-INTERNALCONNECTIONERROR_ONE_ARGUMENT= ||Description: {0}.|Please check the logs for more information.
-
-INTERNALCONNECTIONFATAL_ONE_ARGUMENT= ||Description: {0}.|Please check the logs for more information.
-
-BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT= ||Data not found: {0}.|\
- An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic.
-
-#Login error codes
-BEUSERMISSINGERROR_ONE_ARGUMENT= |||\
- User {0} must be added to the corresponding application with proper user roles.
-
-BEUSERINACTIVEWARNING_ONE_ARGUMENT= |||\
- User {0} must be added to the corresponding application with proper user roles.
-
-BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT= |||\
- User {0} should be given proper administrator role for the corresponding application to perform the necessary actions.
-
-BEINVALIDJSONINPUT= |||Please check error logs for more information.
-
-BEINCORRECTHTTPSTATUSERROR= |||Please check logs for more information.
-
-BEINITIALIZATIONERROR= |||Please check logs for more information.
-
-BEUEBSYSTEMERROR= ||\
- Operation: {0}.|\
- An error occurred in {1} distribution mechanism. Please check the logs for more information.
-
-BEDAOSYSTEMERROR= |||Please check MySQL DB health or look at the logs for more details.
-
-BESYSTEMERROR= |||Please check logs for more information.
-
-BEEXECUTEROLLBACKERROR= |||Please check MYSQL DB health or look at the logs for more details.
-
-FEHTTPLOGGINGERROR= |||Please check MYSQL DB health or look at the logs for more details.
-
-FEPORTALSERVLETERROR= |||Please check logs for more specific information about the problem.
-
-BEDAOCLOSESESSIONERROR= |||Please check MYSQL DB health or look at the logs form more details.
-
-BERESTAPIGENERALERROR= |||Please check error log for more information.
-
-FEHEALTHCHECKGENERALERROR= |||Please check error log for more information.
-
-INTERNALUNEXPECTEDINFO_ONE_ARGUMENT= |||Description: {0}.
-
-INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT= |||Description: {0}.
-
-INTERNALUNEXPECTEDERROR_ONE_ARGUMENT= |||Description: {0}.
-
-INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT= |||Description: {0}.
+### +# ================================================================================ +# ECOMP Portal +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ================================================================================ +### +######################################################################## +#Resource key=Error Code|Message text|Resolution text |Description text +####### +#Newlines can be utilized to add some clarity ensuring continuing line +#has atleast one leading space +#ResourceKey=\ +# ERR0000E\ +# Sample error msg txt\ +# Sample resolution msg\ +# Sample description txt +# +###### +#Error code classification category +#100 Permission errors +#200 Availability errors/Timeouts +#300 Data errors +#400 Schema Interface type/validation errors +#500 Business process errors +#900 Unknown errors +# +######################################################################## + +# Define Alarm Codes Specific to ECOMP Portal +BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT= ||Reason: {0}.|\ + An Authentication failure occurred during access to UEB server. Please check that UEB keys are configured correctly under fusion.properties file. + +BERESTAPIAUTHENTICATIONERROR = |||Please check application credentials defined in Database or portal.properties file. + +INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT=||Description: {0}.|Please check the logs for more information. + +INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT=||Description: {0}.|Please check the logs for more information. + +INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT=||Description: {0}.|Please check the logs for more information. + +INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT=||Description: {0}.|Please check the logs for more information. + +BEHEALTHCHECKERROR= |||Please check the logs for more information. + +BEHEALTHCHECKMYSQLERROR= ||Please check the logs for more information.|\ + Check connectivity to MYSQL is configured correctly under system.properties file. + +BEHEALTHCHECKUEBCLUSTERERROR= ||Please check the logs for more information.|\ + Check connectivity to UEB cluster which is configured under portal.properties file. + +FEHEALTHCHECKERROR= |||Please check connectivity from this FE instance towards BE or BE Load Balancer. + +BEHEALTHCHECKRECOVERY= |||Please check logs for more specific information about the problem. + +BEHEALTHCHECKMYSQLRECOVERY= |||Please check logs for more specific information about the problem. + +BEHEALTHCHECKUEBCLUSTERRECOVERY= |||Please check logs for more specific information about the problem. + +FEHEALTHCHECKRECOVERY= |||Please check logs for more specific information about the problem. + +#UEB communication +BEUEBCONNECTIONERROR_ONE_ARGUMENT= ||Reason: {0}.|\ + Please check UEB server list and keys configured under Portal.Properties file. + +BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT= ||Cannot reach host {0}.|\ + Please check UEB server list and keys configured under Portal.Properties file. + +#Onboarding apps +BEUEBREGISTERONBOARDINGAPPERROR= ||Reason: {0}.|\ + Please check UEB server list and keys configured under Portal.Properties file. + +#HTTP communication +BEHTTPCONNECTIONERROR_ONE_ARGUMENT= ||Reason: {0}.|Please check the logs for more information. + +INTERNALCONNECTIONINFO_ONE_ARGUMENT= ||Description: {0}.|Please check the logs for more information. + +INTERNALCONNECTIONWARNING_ONE_ARGUMENT= ||Description: {0}.|Please check the logs for more information. + +INTERNALCONNECTIONERROR_ONE_ARGUMENT= ||Description: {0}.|Please check the logs for more information. + +INTERNALCONNECTIONFATAL_ONE_ARGUMENT= ||Description: {0}.|Please check the logs for more information. + +BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT= ||Data not found: {0}.|\ + An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic. + +#Login error codes +BEUSERMISSINGERROR_ONE_ARGUMENT= |||\ + User {0} must be added to the corresponding application with proper user roles. + +BEUSERINACTIVEWARNING_ONE_ARGUMENT= |||\ + User {0} must be added to the corresponding application with proper user roles. + +BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT= |||\ + User {0} should be given proper administrator role for the corresponding application to perform the necessary actions. + +BEINVALIDJSONINPUT= |||Please check error logs for more information. + +BEINCORRECTHTTPSTATUSERROR= |||Please check logs for more information. + +BEINITIALIZATIONERROR= |||Please check logs for more information. + +BEUEBSYSTEMERROR= ||\ + Operation: {0}.|\ + An error occurred in {1} distribution mechanism. Please check the logs for more information. + +BEDAOSYSTEMERROR= |||Please check MySQL DB health or look at the logs for more details. + +BESYSTEMERROR= |||Please check logs for more information. + +BEEXECUTEROLLBACKERROR= |||Please check MYSQL DB health or look at the logs for more details. + +FEHTTPLOGGINGERROR= |||Please check MYSQL DB health or look at the logs for more details. + +FEPORTALSERVLETERROR= |||Please check logs for more specific information about the problem. + +BEDAOCLOSESESSIONERROR= |||Please check MYSQL DB health or look at the logs form more details. + +BERESTAPIGENERALERROR= |||Please check error log for more information. + +FEHEALTHCHECKGENERALERROR= |||Please check error log for more information. + +INTERNALUNEXPECTEDINFO_ONE_ARGUMENT= |||Description: {0}. + +INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT= |||Description: {0}. + +INTERNALUNEXPECTEDERROR_ONE_ARGUMENT= |||Description: {0}. + +INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT= |||Description: {0}. diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java index a9cb2e4c..82c3ad37 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java @@ -1,260 +1,260 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.logging.format;
-
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.format.ErrorSeverityEnum;
-import org.openecomp.portalsdk.core.logging.format.ErrorTypeEnum;
-
-/**
- *
- * @author rc580q
- * Add ECOMP Portal Specific Error Code Enums here, for generic
- * ones (ones you think are useful not only Portal but also SDK), add it
- * to the enum class AppMessagesEnum defined in SDK.
- */
-public enum EPAppMessagesEnum {
- /*
- 100-199 Security/Permission Related
- - Authentication problems (from external client, to external server)
- - Certification errors
- -
-
- 200-299 Availability/Timeout Related
- - connectivity error
- - connection timeout
-
- 300-399 Data Access/Integrity Related
- - Data in graph in invalid(E.g. no creator is found for service)
- - Artifact is missing in ES, but exists in graph.
-
- 400-499 Schema Interface Type/Validation
- - received Pay-load checksum is invalid
- - received JSON is not valid
-
- 500-599 Business/Flow Processing Related
- - check out to service is not allowed
- - Roll-back is done
- - failed to generate heat file
-
-
- 600-899 Reserved - do not use
-
- 900-999 Unknown Errors
- - Unexpected exception
- */
-
- BeUebAuthenticationError(EPErrorCodesEnum.BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR100E", "An Authentication failure occurred during access to UEB server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
-
- BeRestApiAuthenticationError(EPErrorCodesEnum.BERESTAPIAUTHENTICATIONERROR, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR101E", "Rejected an incoming REST API request due to invalid credentials", "", "Please check application credentials defined in Database or properties files."),
-
- InternalAuthenticationInfo(EPErrorCodesEnum.INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR199I", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
-
- InternalAuthenticationWarning(EPErrorCodesEnum.INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
- "ERR199W", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
-
- InternalAuthenticationError(EPErrorCodesEnum.INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR199E", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
-
- InternalAuthenticationFatal(EPErrorCodesEnum.INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL,
- "ERR199F", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
-
- BeHealthCheckError(EPErrorCodesEnum.BeHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR200E", "ECOMP-PORTAL Back-end probably lost connectivity to either one of the following components: MySQL DB, UEB Cluster", "", "Please check the logs for more information."),
-
- BeHealthCheckMySqlError(EPErrorCodesEnum.BEHEALTHCHECKMYSQLERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR201E", "ECOMP-PORTAL Back-end probably lost connectivity to MySQL DB", "", "Check connectivity to MYSQL is configured correctly under system.properties file."),
-
- BeHealthCheckUebClusterError(EPErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR203E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "", "Check connectivity to UEB cluster which is configured under portal.properties file."),
-
- FeHealthCheckError(EPErrorCodesEnum.FEHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR204E", "Unable to connect to a valid ECOMP-PORTAL Back-end Server.", "", "Please check connectivity from this FE instance towards BE or BE Load Balancer."),
-
- BeHealthCheckRecovery(EPErrorCodesEnum.BEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR205I", "ECOMP-PORTAL Back-end Recovery to either one of the following components: MySQL DB, UEB Cluster", "", "Please check logs for more specific information about the problem."),
-
- BeHealthCheckMySqlRecovery(EPErrorCodesEnum.BEHEALTHCHECKMYSQLRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR206I", "ECOMP-PORTAL Back-end connection recovery to MySQL DB", "", "Please check logs for more specific information about the problem."),
-
- BeHealthCheckUebClusterRecovery(EPErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR208I", "ECOMP-PORTAL Back-end connection recovery to UEB Cluster", "", "Please check logs for more specific information about the problem."),
-
- FeHealthCheckRecovery(EPErrorCodesEnum.FEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR209I", "Connectivity to ECOMP-PORTAL Front-end Server is recovered", "", "Please check logs for more specific information about the problem."),
-
- BeUebConnectionError(EPErrorCodesEnum.BEUEBCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR210E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
-
- BeUebUnkownHostError(EPErrorCodesEnum.BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR211E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Cannot reach host: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
-
- BeUebRegisterOnboardingAppError(EPErrorCodesEnum.BEUEBREGISTERONBOARDINGAPPERROR, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR212E", "Failed to register the On-boarding application with UEB Communication server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
-
- BeHttpConnectionError(EPErrorCodesEnum.BEHTTPCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR213E", "It could be that communication to an external application might resulted an exception or failed to reach the external application",
- "Details: {0}.", "Please check logs for more information."),
-
- InternalConnectionInfo(EPErrorCodesEnum.INTERNALCONNECTIONINFO_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR299I", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
-
- InternalConnectionWarning(EPErrorCodesEnum.INTERNALCONNECTIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
- "ERR299W", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
-
- InternalConnectionError(EPErrorCodesEnum.INTERNALCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR299E", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
-
- InternalConnectionFatal(EPErrorCodesEnum.INTERNALCONNECTIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL,
- "ERR299F", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
-
- BeUebObjectNotFoundError(EPErrorCodesEnum.BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR303E", "Error occurred during access to U-EB Server.", "Data not found: {0}.", "An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic."),
-
- BeUserMissingError(EPErrorCodesEnum.BEUSERMISSINGERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR310E", "User is not found", "", "User {0} must be added to the corresponding application with proper user roles."),
-
- BeUserInactiveWarning(EPErrorCodesEnum.BEUSERINACTIVEWARNING_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
- "ERR313W", "User is found but in-active", "", "User {0} must be added to the corresponding application with proper user roles."),
-
- BeUserAdminPrivilegesInfo(EPErrorCodesEnum.BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
- "ERR314W", "User is found but don't have administrative privileges", "", "User {0} should be given administrator role for the corresponding application to perform the necessary actions."),
-
- BeInvalidJsonInput(EPErrorCodesEnum.BEINVALIDJSONINPUT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR405E", "Failed to convert JSON input to object", "", "Please check logs for more information."),
-
- BeIncorrectHttpStatusError(EPErrorCodesEnum.BEINCORRECTHTTPSTATUSERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR407E", "Communication to an external application is resulted in with Incorrect Http response code", "", "Please check logs for more information."),
-
- BeInitializationError(EPErrorCodesEnum.BEINITIALIZATIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR500E", "ECOMP-PORTAL Back-end was not initialized properly", "", "Please check logs for more information."),
-
- BeUebSystemError(EPErrorCodesEnum.BEUEBSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR502E", "Error occurred during access to U-EB Server", "Details: {0}.", "An error occurred in {1} distribution mechanism. Please check the logs for more information."),
-
- BeDaoSystemError(EPErrorCodesEnum.BEDAOSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR505E", "Performing DDL or DML operations on database might have failed", "", "Please check MySQL DB health or look at the logs for more details."),
-
- BeSystemError(EPErrorCodesEnum.BESYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR506E", "Unexpected error during operation", "", "Please check logs for more information."),
-
- BeExecuteRollbackError(EPErrorCodesEnum.BEEXECUTEROLLBACKERROR, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR507E", "Roll-back operation towards database has failed", "", "Please check MYSQL DB health or look at the logs for more details."),
-
- FeHttpLoggingError(EPErrorCodesEnum.FEHTTPLOGGINGERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.ERROR,
- "ERR517E", "Error when logging FE HTTP request/response", "", "Please check MYSQL DB health or look at the logs for more details."),
-
- FePortalServletError(EPErrorCodesEnum.FEPORTALSERVLETERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR518E", "Error when trying to access FE Portal page.", "", "Please check logs for more information."),
-
- BeDaoCloseSessionError(EPErrorCodesEnum.BEDAOCLOSESESSIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR519E", "Close local session operation with database failed", "", "Please check MYSQL DB health or look at the logs form more details."),
-
- BeRestApiGeneralError(EPErrorCodesEnum.BERESTAPIGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR900E", "Unexpected error during ECOMP-PORTAL Back-end REST API execution", "", "Please check error log for more information."),
-
- FeHealthCheckGeneralError(EPErrorCodesEnum.FEHEALTHCHECKGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
- "ERR901E", "General error during FE Health Check", "", "Please check error log for more information."),
-
- InternalUnexpectedInfo(EPErrorCodesEnum.INTERNALUNEXPECTEDINFO_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
- "ERR999I", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
-
- InternalUnexpectedWarning(EPErrorCodesEnum.INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
- "ERR999W", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
-
- InternalUnexpectedError(EPErrorCodesEnum.INTERNALUNEXPECTEDERROR_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
- "ERR999E", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
-
- InternalUnexpectedFatal(EPErrorCodesEnum.INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL,
- "ERR999F", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
-
- ;
-
- ErrorTypeEnum eType;
- AlarmSeverityEnum alarmSeverity;
- EPErrorCodesEnum messageCode;
- ErrorSeverityEnum errorSeverity;
- String errorCode;
- String errorDescription;
- String details;
- String resolution;
-
- EPAppMessagesEnum(EPErrorCodesEnum messageCode, ErrorTypeEnum eType, AlarmSeverityEnum alarmSeverity, ErrorSeverityEnum errorSeverity, String errorCode, String errorDescription,
- String details, String resolution) {
- this.messageCode = messageCode;
- this.eType = eType;
- this.alarmSeverity = alarmSeverity;
- this.errorSeverity = errorSeverity;
- this.errorCode = errorCode;
- this.errorDescription = errorDescription;
- this.details = details;
- this.resolution = resolution;
- }
-
- public String getDetails() {
- return this.details;
- }
-
- public String getResolution() {
- return this.resolution;
- }
- public String getErrorCode() {
- return this.errorCode;
- }
-
- public String getErrorDescription() {
- return this.errorDescription;
- }
-
- public ErrorSeverityEnum getErrorSeverity() {
- return this.errorSeverity;
- }
-
- public void setErrorSeverity(ErrorSeverityEnum errorSeverity) {
- this.errorSeverity = errorSeverity;
- }
-
- public EPErrorCodesEnum getMessageCode() {
- return messageCode;
- }
-
- public void setMessageCode(EPErrorCodesEnum messageCode) {
- this.messageCode = messageCode;
- }
-
- public AlarmSeverityEnum getAlarmSeverity() {
- return alarmSeverity;
- }
-
- public void setAlarmSeverity(AlarmSeverityEnum alarmSeverity) {
- this.alarmSeverity = alarmSeverity;
- }
-
- public ErrorTypeEnum getErrorType() {
- return eType;
- }
-
- public void setErrorType(ErrorTypeEnum eType) {
- this.eType = eType;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.logging.format; + +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.format.ErrorSeverityEnum; +import org.openecomp.portalsdk.core.logging.format.ErrorTypeEnum; + +/** + * + * @author rc580q + * Add ECOMP Portal Specific Error Code Enums here, for generic + * ones (ones you think are useful not only Portal but also SDK), add it + * to the enum class AppMessagesEnum defined in SDK. + */ +public enum EPAppMessagesEnum { + /* + 100-199 Security/Permission Related + - Authentication problems (from external client, to external server) + - Certification errors + - + + 200-299 Availability/Timeout Related + - connectivity error + - connection timeout + + 300-399 Data Access/Integrity Related + - Data in graph in invalid(E.g. no creator is found for service) + - Artifact is missing in ES, but exists in graph. + + 400-499 Schema Interface Type/Validation + - received Pay-load checksum is invalid + - received JSON is not valid + + 500-599 Business/Flow Processing Related + - check out to service is not allowed + - Roll-back is done + - failed to generate heat file + + + 600-899 Reserved - do not use + + 900-999 Unknown Errors + - Unexpected exception + */ + + BeUebAuthenticationError(EPErrorCodesEnum.BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR100E", "An Authentication failure occurred during access to UEB server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."), + + BeRestApiAuthenticationError(EPErrorCodesEnum.BERESTAPIAUTHENTICATIONERROR, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR101E", "Rejected an incoming REST API request due to invalid credentials", "", "Please check application credentials defined in Database or properties files."), + + InternalAuthenticationInfo(EPErrorCodesEnum.INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR199I", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), + + InternalAuthenticationWarning(EPErrorCodesEnum.INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, + "ERR199W", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), + + InternalAuthenticationError(EPErrorCodesEnum.INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR199E", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), + + InternalAuthenticationFatal(EPErrorCodesEnum.INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL, + "ERR199F", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), + + BeHealthCheckError(EPErrorCodesEnum.BeHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR200E", "ECOMP-PORTAL Back-end probably lost connectivity to either one of the following components: MySQL DB, UEB Cluster", "", "Please check the logs for more information."), + + BeHealthCheckMySqlError(EPErrorCodesEnum.BEHEALTHCHECKMYSQLERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR201E", "ECOMP-PORTAL Back-end probably lost connectivity to MySQL DB", "", "Check connectivity to MYSQL is configured correctly under system.properties file."), + + BeHealthCheckUebClusterError(EPErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR203E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "", "Check connectivity to UEB cluster which is configured under portal.properties file."), + + FeHealthCheckError(EPErrorCodesEnum.FEHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR204E", "Unable to connect to a valid ECOMP-PORTAL Back-end Server.", "", "Please check connectivity from this FE instance towards BE or BE Load Balancer."), + + BeHealthCheckRecovery(EPErrorCodesEnum.BEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR205I", "ECOMP-PORTAL Back-end Recovery to either one of the following components: MySQL DB, UEB Cluster", "", "Please check logs for more specific information about the problem."), + + BeHealthCheckMySqlRecovery(EPErrorCodesEnum.BEHEALTHCHECKMYSQLRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR206I", "ECOMP-PORTAL Back-end connection recovery to MySQL DB", "", "Please check logs for more specific information about the problem."), + + BeHealthCheckUebClusterRecovery(EPErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR208I", "ECOMP-PORTAL Back-end connection recovery to UEB Cluster", "", "Please check logs for more specific information about the problem."), + + FeHealthCheckRecovery(EPErrorCodesEnum.FEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR209I", "Connectivity to ECOMP-PORTAL Front-end Server is recovered", "", "Please check logs for more specific information about the problem."), + + BeUebConnectionError(EPErrorCodesEnum.BEUEBCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR210E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."), + + BeUebUnkownHostError(EPErrorCodesEnum.BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR211E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Cannot reach host: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."), + + BeUebRegisterOnboardingAppError(EPErrorCodesEnum.BEUEBREGISTERONBOARDINGAPPERROR, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR212E", "Failed to register the On-boarding application with UEB Communication server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."), + + BeHttpConnectionError(EPErrorCodesEnum.BEHTTPCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR213E", "It could be that communication to an external application might resulted an exception or failed to reach the external application", + "Details: {0}.", "Please check logs for more information."), + + InternalConnectionInfo(EPErrorCodesEnum.INTERNALCONNECTIONINFO_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR299I", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), + + InternalConnectionWarning(EPErrorCodesEnum.INTERNALCONNECTIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, + "ERR299W", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), + + InternalConnectionError(EPErrorCodesEnum.INTERNALCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR299E", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), + + InternalConnectionFatal(EPErrorCodesEnum.INTERNALCONNECTIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL, + "ERR299F", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), + + BeUebObjectNotFoundError(EPErrorCodesEnum.BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR303E", "Error occurred during access to U-EB Server.", "Data not found: {0}.", "An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic."), + + BeUserMissingError(EPErrorCodesEnum.BEUSERMISSINGERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR310E", "User is not found", "", "User {0} must be added to the corresponding application with proper user roles."), + + BeUserInactiveWarning(EPErrorCodesEnum.BEUSERINACTIVEWARNING_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, + "ERR313W", "User is found but in-active", "", "User {0} must be added to the corresponding application with proper user roles."), + + BeUserAdminPrivilegesInfo(EPErrorCodesEnum.BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, + "ERR314W", "User is found but don't have administrative privileges", "", "User {0} should be given administrator role for the corresponding application to perform the necessary actions."), + + BeInvalidJsonInput(EPErrorCodesEnum.BEINVALIDJSONINPUT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR405E", "Failed to convert JSON input to object", "", "Please check logs for more information."), + + BeIncorrectHttpStatusError(EPErrorCodesEnum.BEINCORRECTHTTPSTATUSERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR407E", "Communication to an external application is resulted in with Incorrect Http response code", "", "Please check logs for more information."), + + BeInitializationError(EPErrorCodesEnum.BEINITIALIZATIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR500E", "ECOMP-PORTAL Back-end was not initialized properly", "", "Please check logs for more information."), + + BeUebSystemError(EPErrorCodesEnum.BEUEBSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR502E", "Error occurred during access to U-EB Server", "Details: {0}.", "An error occurred in {1} distribution mechanism. Please check the logs for more information."), + + BeDaoSystemError(EPErrorCodesEnum.BEDAOSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR505E", "Performing DDL or DML operations on database might have failed", "", "Please check MySQL DB health or look at the logs for more details."), + + BeSystemError(EPErrorCodesEnum.BESYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR506E", "Unexpected error during operation", "", "Please check logs for more information."), + + BeExecuteRollbackError(EPErrorCodesEnum.BEEXECUTEROLLBACKERROR, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR507E", "Roll-back operation towards database has failed", "", "Please check MYSQL DB health or look at the logs for more details."), + + FeHttpLoggingError(EPErrorCodesEnum.FEHTTPLOGGINGERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.ERROR, + "ERR517E", "Error when logging FE HTTP request/response", "", "Please check MYSQL DB health or look at the logs for more details."), + + FePortalServletError(EPErrorCodesEnum.FEPORTALSERVLETERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR518E", "Error when trying to access FE Portal page.", "", "Please check logs for more information."), + + BeDaoCloseSessionError(EPErrorCodesEnum.BEDAOCLOSESESSIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR519E", "Close local session operation with database failed", "", "Please check MYSQL DB health or look at the logs form more details."), + + BeRestApiGeneralError(EPErrorCodesEnum.BERESTAPIGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR900E", "Unexpected error during ECOMP-PORTAL Back-end REST API execution", "", "Please check error log for more information."), + + FeHealthCheckGeneralError(EPErrorCodesEnum.FEHEALTHCHECKGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR, + "ERR901E", "General error during FE Health Check", "", "Please check error log for more information."), + + InternalUnexpectedInfo(EPErrorCodesEnum.INTERNALUNEXPECTEDINFO_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, + "ERR999I", "Unexpected error", "Details: {0}.", "Please check logs for more information."), + + InternalUnexpectedWarning(EPErrorCodesEnum.INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN, + "ERR999W", "Unexpected error", "Details: {0}.", "Please check logs for more information."), + + InternalUnexpectedError(EPErrorCodesEnum.INTERNALUNEXPECTEDERROR_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR999E", "Unexpected error", "Details: {0}.", "Please check logs for more information."), + + InternalUnexpectedFatal(EPErrorCodesEnum.INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL, + "ERR999F", "Unexpected error", "Details: {0}.", "Please check logs for more information."), + + ; + + ErrorTypeEnum eType; + AlarmSeverityEnum alarmSeverity; + EPErrorCodesEnum messageCode; + ErrorSeverityEnum errorSeverity; + String errorCode; + String errorDescription; + String details; + String resolution; + + EPAppMessagesEnum(EPErrorCodesEnum messageCode, ErrorTypeEnum eType, AlarmSeverityEnum alarmSeverity, ErrorSeverityEnum errorSeverity, String errorCode, String errorDescription, + String details, String resolution) { + this.messageCode = messageCode; + this.eType = eType; + this.alarmSeverity = alarmSeverity; + this.errorSeverity = errorSeverity; + this.errorCode = errorCode; + this.errorDescription = errorDescription; + this.details = details; + this.resolution = resolution; + } + + public String getDetails() { + return this.details; + } + + public String getResolution() { + return this.resolution; + } + public String getErrorCode() { + return this.errorCode; + } + + public String getErrorDescription() { + return this.errorDescription; + } + + public ErrorSeverityEnum getErrorSeverity() { + return this.errorSeverity; + } + + public void setErrorSeverity(ErrorSeverityEnum errorSeverity) { + this.errorSeverity = errorSeverity; + } + + public EPErrorCodesEnum getMessageCode() { + return messageCode; + } + + public void setMessageCode(EPErrorCodesEnum messageCode) { + this.messageCode = messageCode; + } + + public AlarmSeverityEnum getAlarmSeverity() { + return alarmSeverity; + } + + public void setAlarmSeverity(AlarmSeverityEnum alarmSeverity) { + this.alarmSeverity = alarmSeverity; + } + + public ErrorTypeEnum getErrorType() { + return eType; + } + + public void setErrorType(ErrorTypeEnum eType) { + this.eType = eType; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java index cbfb4fa3..498bfcfe 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java @@ -1,95 +1,95 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.logging.format;
-
-import com.att.eelf.i18n.EELFResolvableErrorEnum;
-import com.att.eelf.i18n.EELFResourceManager;
-
-/**
- *
- * @author rc580q
- * Add ECOMP Portal Specific Error Code Enums here, for generic
- * ones (ones you think are useful not only Portal but also SDK), add it
- * to the enum class AppMessagesEnum defined in SDK.
- */
-public enum EPErrorCodesEnum implements EELFResolvableErrorEnum {
- BERESTAPIAUTHENTICATIONERROR,
- BEHTTPCONNECTIONERROR_ONE_ARGUMENT,
- BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT,
-
- INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT,
- INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT,
- INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT,
- INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT,
-
- BEHEALTHCHECKRECOVERY,
- BEHEALTHCHECKMYSQLRECOVERY,
- BEHEALTHCHECKUEBCLUSTERRECOVERY,
- FEHEALTHCHECKRECOVERY,
- BeHEALTHCHECKERROR,
-
- BEHEALTHCHECKMYSQLERROR,
- BEHEALTHCHECKUEBCLUSTERERROR,
- FEHEALTHCHECKERROR,
- BEUEBCONNECTIONERROR_ONE_ARGUMENT,
- BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT,
- BEUEBREGISTERONBOARDINGAPPERROR,
-
- INTERNALCONNECTIONINFO_ONE_ARGUMENT,
- INTERNALCONNECTIONWARNING_ONE_ARGUMENT,
- INTERNALCONNECTIONERROR_ONE_ARGUMENT,
- INTERNALCONNECTIONFATAL_ONE_ARGUMENT,
-
- BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT,
- BEUSERMISSINGERROR_ONE_ARGUMENT,
-
- BEUSERINACTIVEWARNING_ONE_ARGUMENT,
- BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT,
-
- BEINVALIDJSONINPUT,
- BEINCORRECTHTTPSTATUSERROR,
-
- BEINITIALIZATIONERROR,
- BEUEBSYSTEMERROR,
- BEDAOSYSTEMERROR,
- BESYSTEMERROR,
- BEEXECUTEROLLBACKERROR,
-
- FEHTTPLOGGINGERROR,
- FEPORTALSERVLETERROR,
- BEDAOCLOSESESSIONERROR,
-
- BERESTAPIGENERALERROR,
- FEHEALTHCHECKGENERALERROR,
-
- INTERNALUNEXPECTEDINFO_ONE_ARGUMENT,
- INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT,
- INTERNALUNEXPECTEDERROR_ONE_ARGUMENT,
- INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT,
- ;
-
- /**
- * Static initializer to ensure the resource bundles for this class are loaded...
- * Here this application loads messages from three bundles
- */
- static {
- EELFResourceManager.loadMessageBundle("org/openecomp/portalapp/portal/logging/format/ApplicationCodes");
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.logging.format; + +import com.att.eelf.i18n.EELFResolvableErrorEnum; +import com.att.eelf.i18n.EELFResourceManager; + +/** + * + * @author rc580q + * Add ECOMP Portal Specific Error Code Enums here, for generic + * ones (ones you think are useful not only Portal but also SDK), add it + * to the enum class AppMessagesEnum defined in SDK. + */ +public enum EPErrorCodesEnum implements EELFResolvableErrorEnum { + BERESTAPIAUTHENTICATIONERROR, + BEHTTPCONNECTIONERROR_ONE_ARGUMENT, + BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT, + + INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT, + INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT, + INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT, + INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT, + + BEHEALTHCHECKRECOVERY, + BEHEALTHCHECKMYSQLRECOVERY, + BEHEALTHCHECKUEBCLUSTERRECOVERY, + FEHEALTHCHECKRECOVERY, + BeHEALTHCHECKERROR, + + BEHEALTHCHECKMYSQLERROR, + BEHEALTHCHECKUEBCLUSTERERROR, + FEHEALTHCHECKERROR, + BEUEBCONNECTIONERROR_ONE_ARGUMENT, + BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT, + BEUEBREGISTERONBOARDINGAPPERROR, + + INTERNALCONNECTIONINFO_ONE_ARGUMENT, + INTERNALCONNECTIONWARNING_ONE_ARGUMENT, + INTERNALCONNECTIONERROR_ONE_ARGUMENT, + INTERNALCONNECTIONFATAL_ONE_ARGUMENT, + + BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT, + BEUSERMISSINGERROR_ONE_ARGUMENT, + + BEUSERINACTIVEWARNING_ONE_ARGUMENT, + BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT, + + BEINVALIDJSONINPUT, + BEINCORRECTHTTPSTATUSERROR, + + BEINITIALIZATIONERROR, + BEUEBSYSTEMERROR, + BEDAOSYSTEMERROR, + BESYSTEMERROR, + BEEXECUTEROLLBACKERROR, + + FEHTTPLOGGINGERROR, + FEPORTALSERVLETERROR, + BEDAOCLOSESESSIONERROR, + + BERESTAPIGENERALERROR, + FEHEALTHCHECKGENERALERROR, + + INTERNALUNEXPECTEDINFO_ONE_ARGUMENT, + INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT, + INTERNALUNEXPECTEDERROR_ONE_ARGUMENT, + INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT, + ; + + /** + * Static initializer to ensure the resource bundles for this class are loaded... + * Here this application loads messages from three bundles + */ + static { + EELFResourceManager.loadMessageBundle("org/openecomp/portalapp/portal/logging/format/ApplicationCodes"); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/logic/EPLogUtil.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/logic/EPLogUtil.java index aa86765b..ebda67e6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/logic/EPLogUtil.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/logic/EPLogUtil.java @@ -1,270 +1,285 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.logging.logic;
-
-import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
-
-import java.text.MessageFormat;
-
-import org.slf4j.MDC;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
-import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
-import org.openecomp.portalsdk.core.logging.format.ErrorSeverityEnum;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.web.support.UserUtils;
-import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
-
-public class EPLogUtil {
-
- // This class has no logger. It uses loggers passed to it.
-
- /**
- * Formats and writes a message to the error log with the class name and the
- * specified parameters, using log level info, warn or error appropriate for
- * the specified severity
- *
- * @param classLogger
- * Logger for the class where the error occurred; the logger
- * carries the class name.
- * @param epMessageEnum
- * Enum carrying alarm and error severity
- * @param param
- * Values used to build the message.
- */
- public static void logEcompError(EELFLoggerDelegate classLogger, EPAppMessagesEnum epMessageEnum, String... param) {
- logEcompError(classLogger, epMessageEnum, null, param);
- }
-
- /**
- * Formats and writes a message to the error log with the class name and the
- * specified parameters, using log level info, warn or error appropriate for
- * the specified severity
- *
- * @param classLogger
- * Logger for the class where the error occurred; the logger
- * carries the class name.
- * @param epMessageEnum
- * Enum carrying alarm and error severity
- * @param param
- * Values used to build the message.
- */
- private static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();
- public static void logEcompError(EPAppMessagesEnum epMessageEnum, String... param) {
- try {
- AlarmSeverityEnum alarmSeverityEnum = epMessageEnum.getAlarmSeverity();
- ErrorSeverityEnum errorSeverityEnum = epMessageEnum.getErrorSeverity();
-
- MDC.put(MDC_ALERT_SEVERITY, alarmSeverityEnum.name());
- MDC.put("ErrorCode", epMessageEnum.getErrorCode());
- MDC.put("ErrorDescription", epMessageEnum.getErrorDescription());
- MDC.put("ClassName", EPLogUtil.class.getName());
-
- String resolution = EPLogUtil.formatMessage(epMessageEnum.getDetails() + " " + epMessageEnum.getResolution(), (Object[]) param);
- if (errorSeverityEnum == ErrorSeverityEnum.WARN) {
- errorLogger.warn(resolution);
- } else if(errorSeverityEnum == ErrorSeverityEnum.INFO) {
- errorLogger.info(resolution);
- } else {
- errorLogger.error(resolution);
- }
- } catch(Exception e) {
- errorLogger.error("Failed to log the error code. Details: " + UserUtils.getStackTrace(e));
- } finally {
- MDC.remove("ErrorCode");
- MDC.remove("ErrorDescription");
- MDC.remove("ClassName");
- MDC.remove(MDC_ALERT_SEVERITY);
- }
- }
-
- /**
- * Formats and writes a message to the error log with the class name,
- * throwable and the specified parameters, using log level info, warn or
- * error appropriate for the specified severity
- *
- * @param classLogger
- * Logger for the class where the error occurred; the logger
- * carries the class name.
- * @param epMessageEnum
- * Enum carrying alarm and error severity
- * @param th
- * Throwable; ignored if null
- * @param param
- * Array of Strings used to build the message.
- */
- @SuppressWarnings("static-access")
- public static void logEcompError(EELFLoggerDelegate classLogger, EPAppMessagesEnum epMessageEnum, Throwable th,
- String... param) {
-
- AlarmSeverityEnum alarmSeverityEnum = epMessageEnum.getAlarmSeverity();
- ErrorSeverityEnum errorSeverityEnum = epMessageEnum.getErrorSeverity();
-
- MDC.put(MDC_ALERT_SEVERITY, alarmSeverityEnum.name());
- MDC.put("ErrorCode", epMessageEnum.getErrorCode());
- MDC.put("ErrorDescription", epMessageEnum.getErrorDescription());
-
- final String message = EPLogUtil.formatMessage(epMessageEnum.getDetails() + " " + epMessageEnum.getResolution(),
- (Object[]) param);
- if (errorSeverityEnum == ErrorSeverityEnum.INFO) {
- if (th == null)
- classLogger.info(classLogger.errorLogger, message);
- else
- classLogger.info(classLogger.errorLogger, message, th);
- } else if (errorSeverityEnum == ErrorSeverityEnum.WARN) {
- if (th == null)
- classLogger.warn(classLogger.errorLogger, message);
- else
- classLogger.warn(classLogger.errorLogger, message, th);
- } else {
- if (th == null)
- classLogger.error(classLogger.errorLogger, message);
- else
- classLogger.error(classLogger.errorLogger, message, th);
- }
-
- // Clean up
- MDC.remove(MDC_ALERT_SEVERITY);
- MDC.remove("ErrorCode");
- MDC.remove("ErrorDescription");
- }
-
- /**
- * Builds a string using the format and parameters.
- * @param message
- * @param args
- * @return
- */
- private static String formatMessage(String message, Object... args) {
- StringBuilder sbFormattedMessage = new StringBuilder();
- if (args != null && args.length > 0 && message != null && message != "") {
- MessageFormat mf = new MessageFormat(message);
- sbFormattedMessage.append(mf.format(args));
- } else {
- sbFormattedMessage.append(message);
- }
- return sbFormattedMessage.toString();
- }
-
- /**
- * Builds a comma-separated string of values to document a user action.
- *
- * @param action
- * @param activity
- * @param userId
- * @param affectedId
- * @param comment
- * @return Value suitable for writing to the audit log file.
- */
- public static String formatAuditLogMessage(String action, String activity, String userId, String affectedId,
- String comment) {
- StringBuilder auditLogMsg = new StringBuilder();
- auditLogMsg.append("Click_A:[");
- if (action != null && !action.equals("")) {
- auditLogMsg.append(" Action: ");
- auditLogMsg.append(action);
- }
-
- if (activity != null && !activity.equals("")) {
- auditLogMsg.append(",Activity CD: ");
- auditLogMsg.append(activity);
- }
-
- if (userId != null && !userId.equals("")) {
- auditLogMsg.append(",User ID: ");
- auditLogMsg.append(userId);
- }
-
- if (affectedId != null && !affectedId.equals("")) {
- auditLogMsg.append(",Affected ID: ");
- auditLogMsg.append(affectedId);
- }
-
- if (comment != null && !comment.equals("")) {
- auditLogMsg.append(",Comment: ");
- auditLogMsg.append(comment);
- }
- auditLogMsg.append("]");
- return auditLogMsg.toString();
- }
-
- /**
- * Builds a comma-separated string of values to document a user browser
- * action.
- *
- * @param orgUserId
- * @param action
- * @param activity
- * @param actionLink
- * @param page
- * @param function
- * @param type
- * @return Value suitable for writing to the audit log file.
- */
- public static String formatStoreAnalyticsAuditLogMessage(String orgUserId, String appName, String action, String activity,
- String actionLink, String page, String function, String type) {
- StringBuilder auditLogStoreAnalyticsMsg = new StringBuilder();
- auditLogStoreAnalyticsMsg.append("Click_Analytics:[");
- if (orgUserId != null && !orgUserId.equals("")) {
- auditLogStoreAnalyticsMsg.append(" Organization User ID: ");
- auditLogStoreAnalyticsMsg.append(orgUserId);
- }
-
- if (appName != null && !appName.equals("")) {
- auditLogStoreAnalyticsMsg.append(",AppName: ");
- auditLogStoreAnalyticsMsg.append(appName);
- }
-
- if (action != null && !action.equals("")) {
- auditLogStoreAnalyticsMsg.append(",Action: ");
- auditLogStoreAnalyticsMsg.append(action);
- }
-
- if (activity != null && !activity.equals("")) {
- auditLogStoreAnalyticsMsg.append(",Activity: ");
- auditLogStoreAnalyticsMsg.append(activity);
- }
-
- if (actionLink != null && !actionLink.equals("")) {
- auditLogStoreAnalyticsMsg.append(",ActionLink: ");
- auditLogStoreAnalyticsMsg.append(actionLink);
- }
-
- if (page != null && !page.equals("")) {
- auditLogStoreAnalyticsMsg.append(",Page: ");
- auditLogStoreAnalyticsMsg.append(page);
- }
-
- if (function != null && !function.equals("")) {
- auditLogStoreAnalyticsMsg.append(",Function: ");
- auditLogStoreAnalyticsMsg.append(function);
- }
-
- if (type != null && !type.equals("")) {
- auditLogStoreAnalyticsMsg.append(",Type: ");
- auditLogStoreAnalyticsMsg.append(type);
- }
- auditLogStoreAnalyticsMsg.append("]");
- return auditLogStoreAnalyticsMsg.toString();
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.logging.logic; + +import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY; + +import java.text.MessageFormat; + +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.format.ErrorSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.slf4j.MDC; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class EPLogUtil { + + // This class has no logger of its own; it uses loggers passed to it. + private static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + + /** + * Formats and writes a message to the error log with the class name and the + * specified parameters, using log level info, warn or error appropriate for + * the specified severity + * + * @param classLogger + * Logger for the class where the error occurred; the logger + * carries the class name. + * @param epMessageEnum + * Enum carrying alarm and error severity + * @param param + * Values used to build the message. + */ + public static void logEcompError(EELFLoggerDelegate classLogger, EPAppMessagesEnum epMessageEnum, String... param) { + logEcompError(classLogger, epMessageEnum, null, param); + } + + /** + * Formats and writes a message to the error log with the class name and the + * specified parameters, using log level info, warn or error appropriate for + * the specified severity + * + * @param classLogger + * Logger for the class where the error occurred; the logger + * carries the class name. + * @param epMessageEnum + * Enum carrying alarm and error severity + * @param param + * Values used to build the message. + */ + public static void logEcompError(EPAppMessagesEnum epMessageEnum, String... param) { + try { + AlarmSeverityEnum alarmSeverityEnum = epMessageEnum.getAlarmSeverity(); + ErrorSeverityEnum errorSeverityEnum = epMessageEnum.getErrorSeverity(); + + MDC.put(MDC_ALERT_SEVERITY, alarmSeverityEnum.name()); + MDC.put("ErrorCode", epMessageEnum.getErrorCode()); + MDC.put("ErrorDescription", epMessageEnum.getErrorDescription()); + MDC.put("ClassName", EPLogUtil.class.getName()); + + String resolution = EPLogUtil + .formatMessage(epMessageEnum.getDetails() + " " + epMessageEnum.getResolution(), (Object[]) param); + if (errorSeverityEnum == ErrorSeverityEnum.WARN) { + errorLogger.warn(resolution); + } else if (errorSeverityEnum == ErrorSeverityEnum.INFO) { + errorLogger.info(resolution); + } else { + errorLogger.error(resolution); + } + } catch (Exception e) { + errorLogger.error("Failed to log the error code. Details: " + UserUtils.getStackTrace(e)); + } finally { + MDC.remove("ErrorCode"); + MDC.remove("ErrorDescription"); + MDC.remove("ClassName"); + MDC.remove(MDC_ALERT_SEVERITY); + } + } + + /** + * Formats and writes a message to the error log with the class name, + * throwable and the specified parameters, using log level info, warn or + * error appropriate for the specified severity + * + * @param classLogger + * Logger for the class where the error occurred; the logger + * carries the class name. + * @param epMessageEnum + * Enum carrying alarm and error severity + * @param th + * Throwable; ignored if null + * @param param + * Array of Strings used to build the message. + */ + @SuppressWarnings("static-access") + public static void logEcompError(EELFLoggerDelegate classLogger, EPAppMessagesEnum epMessageEnum, Throwable th, + String... param) { + + AlarmSeverityEnum alarmSeverityEnum = epMessageEnum.getAlarmSeverity(); + ErrorSeverityEnum errorSeverityEnum = epMessageEnum.getErrorSeverity(); + + MDC.put(MDC_ALERT_SEVERITY, alarmSeverityEnum.name()); + MDC.put("ErrorCode", epMessageEnum.getErrorCode()); + MDC.put("ErrorDescription", epMessageEnum.getErrorDescription()); + + final String message = EPLogUtil.formatMessage(epMessageEnum.getDetails() + " " + epMessageEnum.getResolution(), + (Object[]) param); + if (errorSeverityEnum == ErrorSeverityEnum.INFO) { + if (th == null) + classLogger.info(classLogger.errorLogger, message); + else + classLogger.info(classLogger.errorLogger, message, th); + } else if (errorSeverityEnum == ErrorSeverityEnum.WARN) { + if (th == null) + classLogger.warn(classLogger.errorLogger, message); + else + classLogger.warn(classLogger.errorLogger, message, th); + } else { + if (th == null) + classLogger.error(classLogger.errorLogger, message); + else + classLogger.error(classLogger.errorLogger, message, th); + } + + // Clean up + MDC.remove(MDC_ALERT_SEVERITY); + MDC.remove("ErrorCode"); + MDC.remove("ErrorDescription"); + } + + /** + * Builds a string using the format and parameters. + * + * @param message + * @param args + * @return + */ + private static String formatMessage(String message, Object... args) { + StringBuilder sbFormattedMessage = new StringBuilder(); + if (args != null && args.length > 0 && message != null && message != "") { + MessageFormat mf = new MessageFormat(message); + sbFormattedMessage.append(mf.format(args)); + } else { + sbFormattedMessage.append(message); + } + return sbFormattedMessage.toString(); + } + + /** + * Builds a comma-separated string of values to document a user action. + * + * @param action + * String + * @param activity + * String + * @param userId + * String + * @param affectedId + * String + * @param comment + * String + * @return Value suitable for writing to the audit log file. + */ + public static String formatAuditLogMessage(String action, String activity, String userId, String affectedId, + String comment) { + StringBuilder auditLogMsg = new StringBuilder(); + auditLogMsg.append("Click_A:["); + if (action != null && !action.equals("")) { + auditLogMsg.append(" Action: "); + auditLogMsg.append(action); + } + + if (activity != null && !activity.equals("")) { + auditLogMsg.append(",Activity CD: "); + auditLogMsg.append(activity); + } + + if (userId != null && !userId.equals("")) { + auditLogMsg.append(",User ID: "); + auditLogMsg.append(userId); + } + + if (affectedId != null && !affectedId.equals("")) { + auditLogMsg.append(",Affected ID: "); + auditLogMsg.append(affectedId); + } + + if (comment != null && !comment.equals("")) { + auditLogMsg.append(",Comment: "); + auditLogMsg.append(comment); + } + auditLogMsg.append("]"); + return auditLogMsg.toString(); + } + + /** + * Builds a comma-separated string of values to document a user browser + * action. + * + * @param orgUserId + * String + * @param appName + * String + * @param action + * String + * @param activity + * String + * @param actionLink + * String + * @param page + * String + * @param function + * String + * @param type + * String + * @return String value suitable for writing to the audit log file. + */ + public static String formatStoreAnalyticsAuditLogMessage(String orgUserId, String appName, String action, + String activity, String actionLink, String page, String function, String type) { + StringBuilder auditLogStoreAnalyticsMsg = new StringBuilder(); + auditLogStoreAnalyticsMsg.append("Click_Analytics:["); + if (orgUserId != null && !orgUserId.equals("")) { + auditLogStoreAnalyticsMsg.append(" Organization User ID: "); + auditLogStoreAnalyticsMsg.append(orgUserId); + } + + if (appName != null && !appName.equals("")) { + auditLogStoreAnalyticsMsg.append(",AppName: "); + auditLogStoreAnalyticsMsg.append(appName); + } + + if (action != null && !action.equals("")) { + auditLogStoreAnalyticsMsg.append(",Action: "); + auditLogStoreAnalyticsMsg.append(action); + } + + if (activity != null && !activity.equals("")) { + auditLogStoreAnalyticsMsg.append(",Activity: "); + auditLogStoreAnalyticsMsg.append(activity); + } + + if (actionLink != null && !actionLink.equals("")) { + auditLogStoreAnalyticsMsg.append(",ActionLink: "); + auditLogStoreAnalyticsMsg.append(actionLink); + } + + if (page != null && !page.equals("")) { + auditLogStoreAnalyticsMsg.append(",Page: "); + auditLogStoreAnalyticsMsg.append(page); + } + + if (function != null && !function.equals("")) { + auditLogStoreAnalyticsMsg.append(",Function: "); + auditLogStoreAnalyticsMsg.append(function); + } + + if (type != null && !type.equals("")) { + auditLogStoreAnalyticsMsg.append(",Type: "); + auditLogStoreAnalyticsMsg.append(type); + } + auditLogStoreAnalyticsMsg.append("]"); + return auditLogStoreAnalyticsMsg.toString(); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesService.java index a1016e1c..529581d2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesService.java @@ -1,56 +1,56 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalapp.portal.domain.EPRole;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole;
-
-public interface AdminRolesService {
-
- public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId);
-
- public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles);
-
- /**
- * Attention! User roles in ECOMP PORTAL cannot be managed by this function.
- * @param user
- * @return 'true' if user has Super Administrator role SYS_ADMIN_ROLE_ID (1 for now) in ECOMP PORTAL, 'false' otherwise
- */
- public boolean isSuperAdmin(EPUser user);
-
- /**
- * Attention! User roles in ECOMP PORTAL cannot be managed by this function.
- * @param user
- * @return 'true' if user has Account Administrator role ACCOUNT_ADMIN_ROLE_ID (999 for now) for any application except ECOMP Portal, 'false' otherwise
- */
- public boolean isAccountAdmin(EPUser user);
-
- /**
- * Attention! User roles in ECOMP PORTAL cannot be managed by this function.
- * @param user
- * @return 'true' if user has any remote(!) role within any application (ECOMP Portal roles are not included), 'false' otherwise
- */
- public boolean isUser(EPUser user);
-
- List<EPRole> getRolesByApp(EPUser user, Long appId);
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole; + +public interface AdminRolesService { + + public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId); + + public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles); + + /** + * Attention! User roles in ECOMP PORTAL cannot be managed by this function. + * @param user + * @return 'true' if user has Super Administrator role SYS_ADMIN_ROLE_ID (1 for now) in ECOMP PORTAL, 'false' otherwise + */ + public boolean isSuperAdmin(EPUser user); + + /** + * Attention! User roles in ECOMP PORTAL cannot be managed by this function. + * @param user + * @return 'true' if user has Account Administrator role ACCOUNT_ADMIN_ROLE_ID (999 for now) for any application except ECOMP Portal, 'false' otherwise + */ + public boolean isAccountAdmin(EPUser user); + + /** + * Attention! User roles in ECOMP PORTAL cannot be managed by this function. + * @param user + * @return 'true' if user has any remote(!) role within any application (ECOMP Portal roles are not included), 'false' otherwise + */ + public boolean isUser(EPUser user); + + List<EPRole> getRolesByApp(EPUser user, Long appId); +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java index 50e7348e..20daa4fc 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java @@ -1,329 +1,329 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import javax.annotation.PostConstruct;
-
-import org.apache.cxf.common.util.StringUtils;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.Transaction;
-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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EPRole;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EPUserApp;
-import org.openecomp.portalapp.portal.domain.UserIdRoleId;
-import org.openecomp.portalapp.portal.domain.UserRole;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin;
-import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-
-@Service("adminRolesService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-
-public class AdminRolesServiceImpl implements AdminRolesService {
-
- private Long SYS_ADMIN_ROLE_ID = 1L;
- private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
- private Long ECOMP_APP_ID = 1L;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesServiceImpl.class);
-
- @Autowired
- private SessionFactory sessionFactory;
- @Autowired
- private DataAccessService dataAccessService;
- @Autowired
- SearchService searchService;
- @Autowired
- EPAppService appsService;
-
- @PostConstruct
- private void init() {
- try {
- SYS_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID));
- ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
- ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID));
- } catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- }
- }
-
- @Override
- @EPMetricsLog
- @SuppressWarnings("unchecked")
- public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) {
- AppsListWithAdminRole appsListWithAdminRole = null;
-
- try {
- List<EPUser> userList = dataAccessService.getList(EPUser.class, " where orgUserId = '" + orgUserId + "'", null,
- null);
- HashMap<Long, Long> appsUserAdmin = new HashMap<Long, Long>();
- if (userList.size() > 0) {
- EPUser user = userList.get(0);
- List<EPUserApp> userAppList = null;
- try {
- userAppList = dataAccessService.getList(EPUserApp.class,
- " where userId = " + user.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null, null);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
- }
- for (EPUserApp userApp : userAppList) {
- appsUserAdmin.put(userApp.getAppId(), userApp.getUserId());
- }
- }
-
- appsListWithAdminRole = new AppsListWithAdminRole();
- appsListWithAdminRole.orgUserId = orgUserId;
- List<EPApp> appsList = null;
- try {
- appsList = dataAccessService.getList(EPApp.class, " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", null, null);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
- }
- for (EPApp app : appsList) {
- AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin();
- appNameIdIsAdmin.id = app.getId();
- appNameIdIsAdmin.appName = app.getName();
- appNameIdIsAdmin.isAdmin = new Boolean(appsUserAdmin.containsKey(app.getId()));
- appNameIdIsAdmin.restrictedApp = app.isRestrictedApp();
- appsListWithAdminRole.appsRoles.add(appNameIdIsAdmin);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing AdminRolesServiceImpl.getAppsWithAdminRoleStateForUser operation, Details:"
- + EcompPortalUtils.getStackTrace(e));
- }
-
- return appsListWithAdminRole;
- }
-
- private static final Object syncRests = new Object();
-
- @Override
- @EPMetricsLog
- @SuppressWarnings("unchecked")
- public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
- boolean result = false;
- // No changes if no new roles list or no userId.
- if (!StringUtils.isEmpty(newAppsListWithAdminRoles.orgUserId) && newAppsListWithAdminRoles.appsRoles != null) {
- synchronized (syncRests) {
- List<EPApp> apps = appsService.getAppsFullList();
- HashMap<Long, EPApp> enabledApps = new HashMap<Long, EPApp>();
- for (EPApp app : apps) {
- if (app.getEnabled().booleanValue() || app.getId() == ECOMP_APP_ID) {
- enabledApps.put(app.getId(), app);
- }
- }
- List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<AppNameIdIsAdmin>();
- for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.appsRoles) {
- // user Admin role may be added only for enabled apps
- if (adminRole.isAdmin.booleanValue() && enabledApps.containsKey(adminRole.id)) {
- newAppsWhereUserIsAdmin.add(adminRole);
- }
- }
- EPUser user = null;
- boolean createNewUser = false;
- String orgUserId = newAppsListWithAdminRoles.orgUserId.trim();
- List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where org_user_id='" + orgUserId + "'",
- null, null);
- List<EPUserApp> oldAppsWhereUserIsAdmin = new ArrayList<EPUserApp>();
- if (localUserList.size() > 0) {
- EPUser tmpUser = localUserList.get(0);
- oldAppsWhereUserIsAdmin = dataAccessService.getList(EPUserApp.class,
- " where userId = " + tmpUser.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null,
- null);
- if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
- user = tmpUser;
- }
- } else if (newAppsWhereUserIsAdmin.size() > 0) {
- // we create new user only if he has Admin Role for any App
- createNewUser = true;
- }
- if (user != null || createNewUser) {
- Session localSession = null;
- Transaction transaction = null;
- try {
- localSession = sessionFactory.openSession();
- transaction = localSession.beginTransaction();
- if (createNewUser) {
- user = this.searchService.searchUserByUserId(orgUserId);
- if (user != null) {
- // insert the user with active true in order to
- // pass login phase.
- user.setActive(true);
- localSession.save(EPUser.class.getName(), user);
- }
- }
- for (EPUserApp oldUserApp : oldAppsWhereUserIsAdmin) {
- // user Admin role may be deleted only for enabled
- // apps
- if (enabledApps.containsKey(oldUserApp.getAppId())) {
- localSession.delete(oldUserApp);
- }
- }
- for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
- EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
- EPRole role = (EPRole) localSession.get(EPRole.class, new Long(ACCOUNT_ADMIN_ROLE_ID));
- EPUserApp newUserApp = new EPUserApp();
- newUserApp.setUserId(user.getId());
- newUserApp.setApp(app);
- newUserApp.setRole(role);
- localSession.save(EPUserApp.class.getName(), newUserApp);
- }
- transaction.commit();
- result = true;
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 2", e);
- try {
- transaction.rollback();
- } catch (Exception ex) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
- logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 3", ex);
- }
- } finally {
- try {
- localSession.close();
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
- logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 4", e);
- }
- }
- }
- }
- }
-
- return result;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public boolean isSuperAdmin(EPUser user) {
- if ((user != null) /* && (user.getId() == null) */ && (user.getOrgUserId() != null)) {
- String sql = "SELECT user.USER_ID, user.org_user_id, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole "
- + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.org_user_id = '"
- + user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' "
- + "AND userrole.APP_ID = '" + ECOMP_APP_ID + "';";
- try {
- List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserIdRoleId.class, null);
- if (userRoleList != null && userRoleList.size() > 0) {
- return true;
- }
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isSuperAdmin operation", e);
- }
- }
- // else
- // {
- // User currentUser = user != null ? (User)
- // dataAccessService.getDomainObject(User.class, user.getId(), null) :
- // null;
- // if (currentUser != null && currentUser.getId() != null) {
- // for (UserApp userApp : currentUser.getUserApps()) {
- // if (userApp.getApp().getId().equals(ECOMP_APP_ID) &&
- // userApp.getRole().getId().equals(SYS_ADMIN_ROLE_ID)) {
- // // Super Administrator role is global, no need to keep iterating
- // return true;
- // }
- // }
- // }
- // }
- return false;
- }
-
- public boolean isAccountAdmin(EPUser user) {
- try {
- EPUser currentUser = user != null
- ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null;
- if (currentUser != null && currentUser.getId() != null) {
- for (EPUserApp userApp : currentUser.getEPUserApps()) {
- if (//!userApp.getApp().getId().equals(ECOMP_APP_ID)
- // &&
- userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
- // Account Administrator sees only the applications
- // he/she is Administrator
- return true;
- }
- }
- }
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isAccountAdmin operation", e);
- }
- return false;
- }
-
- public boolean isUser(EPUser user) {
- try {
- EPUser currentUser = user != null
- ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null;
- if (currentUser != null && currentUser.getId() != null) {
- for (EPUserApp userApp : currentUser.getEPUserApps()) {
- if (!userApp.getApp().getId().equals(ECOMP_APP_ID)) {
- EPRole role = userApp.getRole();
- if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
- if (role.getActive()) {
- return true;
- }
- }
- }
- }
- }
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", e);
- }
- return false;
- }
-
- @Override
- @EPMetricsLog
- public List<EPRole> getRolesByApp(EPUser user, Long appId) {
- List<EPRole> list = new ArrayList<>();
- String sql = "SELECT * FROM FN_ROLE WHERE APP_ID = " + appId;
- @SuppressWarnings("unchecked")
- List<EPRole> roles = dataAccessService.executeSQLQuery(sql, EPRole.class, null);
- for (EPRole role: roles) {
- list.add(role);
- }
- return list;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.apache.cxf.common.util.StringUtils; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.domain.UserIdRoleId; +import org.openecomp.portalapp.portal.domain.UserRole; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin; +import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; + +@Service("adminRolesService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy + +public class AdminRolesServiceImpl implements AdminRolesService { + + private Long SYS_ADMIN_ROLE_ID = 1L; + private Long ACCOUNT_ADMIN_ROLE_ID = 999L; + private Long ECOMP_APP_ID = 1L; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesServiceImpl.class); + + @Autowired + private SessionFactory sessionFactory; + @Autowired + private DataAccessService dataAccessService; + @Autowired + SearchService searchService; + @Autowired + EPAppService appsService; + + @PostConstruct + private void init() { + try { + SYS_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID)); + ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID)); + ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID)); + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + @Override + @EPMetricsLog + @SuppressWarnings("unchecked") + public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) { + AppsListWithAdminRole appsListWithAdminRole = null; + + try { + List<EPUser> userList = dataAccessService.getList(EPUser.class, " where orgUserId = '" + orgUserId + "'", null, + null); + HashMap<Long, Long> appsUserAdmin = new HashMap<Long, Long>(); + if (userList.size() > 0) { + EPUser user = userList.get(0); + List<EPUserApp> userAppList = null; + try { + userAppList = dataAccessService.getList(EPUserApp.class, + " where userId = " + user.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError); + } + for (EPUserApp userApp : userAppList) { + appsUserAdmin.put(userApp.getAppId(), userApp.getUserId()); + } + } + + appsListWithAdminRole = new AppsListWithAdminRole(); + appsListWithAdminRole.orgUserId = orgUserId; + List<EPApp> appsList = null; + try { + appsList = dataAccessService.getList(EPApp.class, " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", null, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError); + } + for (EPApp app : appsList) { + AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin(); + appNameIdIsAdmin.id = app.getId(); + appNameIdIsAdmin.appName = app.getName(); + appNameIdIsAdmin.isAdmin = new Boolean(appsUserAdmin.containsKey(app.getId())); + appNameIdIsAdmin.restrictedApp = app.isRestrictedApp(); + appsListWithAdminRole.appsRoles.add(appNameIdIsAdmin); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing AdminRolesServiceImpl.getAppsWithAdminRoleStateForUser operation, Details:" + + EcompPortalUtils.getStackTrace(e)); + } + + return appsListWithAdminRole; + } + + private static final Object syncRests = new Object(); + + @Override + @EPMetricsLog + @SuppressWarnings("unchecked") + public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) { + boolean result = false; + // No changes if no new roles list or no userId. + if (!StringUtils.isEmpty(newAppsListWithAdminRoles.orgUserId) && newAppsListWithAdminRoles.appsRoles != null) { + synchronized (syncRests) { + List<EPApp> apps = appsService.getAppsFullList(); + HashMap<Long, EPApp> enabledApps = new HashMap<Long, EPApp>(); + for (EPApp app : apps) { + if (app.getEnabled().booleanValue() || app.getId() == ECOMP_APP_ID) { + enabledApps.put(app.getId(), app); + } + } + List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<AppNameIdIsAdmin>(); + for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.appsRoles) { + // user Admin role may be added only for enabled apps + if (adminRole.isAdmin.booleanValue() && enabledApps.containsKey(adminRole.id)) { + newAppsWhereUserIsAdmin.add(adminRole); + } + } + EPUser user = null; + boolean createNewUser = false; + String orgUserId = newAppsListWithAdminRoles.orgUserId.trim(); + List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where org_user_id='" + orgUserId + "'", + null, null); + List<EPUserApp> oldAppsWhereUserIsAdmin = new ArrayList<EPUserApp>(); + if (localUserList.size() > 0) { + EPUser tmpUser = localUserList.get(0); + oldAppsWhereUserIsAdmin = dataAccessService.getList(EPUserApp.class, + " where userId = " + tmpUser.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null, + null); + if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) { + user = tmpUser; + } + } else if (newAppsWhereUserIsAdmin.size() > 0) { + // we create new user only if he has Admin Role for any App + createNewUser = true; + } + if (user != null || createNewUser) { + Session localSession = null; + Transaction transaction = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + if (createNewUser) { + user = this.searchService.searchUserByUserId(orgUserId); + if (user != null) { + // insert the user with active true in order to + // pass login phase. + user.setActive(true); + localSession.save(EPUser.class.getName(), user); + } + } + for (EPUserApp oldUserApp : oldAppsWhereUserIsAdmin) { + // user Admin role may be deleted only for enabled + // apps + if (enabledApps.containsKey(oldUserApp.getAppId())) { + localSession.delete(oldUserApp); + } + } + for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) { + EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id); + EPRole role = (EPRole) localSession.get(EPRole.class, new Long(ACCOUNT_ADMIN_ROLE_ID)); + EPUserApp newUserApp = new EPUserApp(); + newUserApp.setUserId(user.getId()); + newUserApp.setApp(app); + newUserApp.setRole(role); + localSession.save(EPUserApp.class.getName(), newUserApp); + } + transaction.commit(); + result = true; + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 2", e); + try { + transaction.rollback(); + } catch (Exception ex) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e); + logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 3", ex); + } + } finally { + try { + localSession.close(); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e); + logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 4", e); + } + } + } + } + } + + return result; + } + + @SuppressWarnings("unchecked") + @Override + public boolean isSuperAdmin(EPUser user) { + if ((user != null) /* && (user.getId() == null) */ && (user.getOrgUserId() != null)) { + String sql = "SELECT user.USER_ID, user.org_user_id, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole " + + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.org_user_id = '" + + user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' " + + "AND userrole.APP_ID = '" + ECOMP_APP_ID + "';"; + try { + List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserIdRoleId.class, null); + if (userRoleList != null && userRoleList.size() > 0) { + return true; + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isSuperAdmin operation", e); + } + } + // else + // { + // User currentUser = user != null ? (User) + // dataAccessService.getDomainObject(User.class, user.getId(), null) : + // null; + // if (currentUser != null && currentUser.getId() != null) { + // for (UserApp userApp : currentUser.getUserApps()) { + // if (userApp.getApp().getId().equals(ECOMP_APP_ID) && + // userApp.getRole().getId().equals(SYS_ADMIN_ROLE_ID)) { + // // Super Administrator role is global, no need to keep iterating + // return true; + // } + // } + // } + // } + return false; + } + + public boolean isAccountAdmin(EPUser user) { + try { + EPUser currentUser = user != null + ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null; + if (currentUser != null && currentUser.getId() != null) { + for (EPUserApp userApp : currentUser.getEPUserApps()) { + if (//!userApp.getApp().getId().equals(ECOMP_APP_ID) + // && + userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)) { + // Account Administrator sees only the applications + // he/she is Administrator + return true; + } + } + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isAccountAdmin operation", e); + } + return false; + } + + public boolean isUser(EPUser user) { + try { + EPUser currentUser = user != null + ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null; + if (currentUser != null && currentUser.getId() != null) { + for (EPUserApp userApp : currentUser.getEPUserApps()) { + if (!userApp.getApp().getId().equals(ECOMP_APP_ID)) { + EPRole role = userApp.getRole(); + if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) { + if (role.getActive()) { + return true; + } + } + } + } + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", e); + } + return false; + } + + @Override + @EPMetricsLog + public List<EPRole> getRolesByApp(EPUser user, Long appId) { + List<EPRole> list = new ArrayList<>(); + String sql = "SELECT * FROM FN_ROLE WHERE APP_ID = " + appId; + @SuppressWarnings("unchecked") + List<EPRole> roles = dataAccessService.executeSQLQuery(sql, EPRole.class, null); + for (EPRole role: roles) { + list.add(role); + } + return list; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsService.java index e8ef64fd..d71e80fe 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsService.java @@ -1,55 +1,55 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalapp.portal.ecomp.model.AppCategoryFunctionsItem;
-import org.openecomp.portalapp.portal.ecomp.model.AppContactUsItem;
-
-public interface AppContactUsService {
-
- /**
- * Gets a list of contact-us information for all entries in
- * the fn_app_contact_us table, sorted by app name. If an application is active but has no fn_app_contact_us entry, it will have no entry in this result.
- *
- * @return List of AppContactUsItem, one for each item in fn_app_contact_us table.
- * @throws Exception
- */
- public List<AppContactUsItem> getAppContactUs() throws Exception;
-
- /**
- * Gets a list of contact-us information for all applications
- * in the fn_app table, extended with any information in the fn_app_contact_us table.
- *
- * @return List of AppContactUsItem, one for each item in fn_app table.
- * @throws Exception
- */
- public List<AppContactUsItem> getAppsAndContacts() throws Exception;
-
- public List<AppCategoryFunctionsItem> getAppCategoryFunctions() throws Exception;
-
- public String saveAppContactUs(List<AppContactUsItem> contactUs) throws Exception;
-
- public String saveAppContactUs(AppContactUsItem contactUs) throws Exception;
-
- public String deleteContactUs(Long id) throws Exception;
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.ecomp.model.AppCategoryFunctionsItem; +import org.openecomp.portalapp.portal.ecomp.model.AppContactUsItem; + +public interface AppContactUsService { + + /** + * Gets a list of contact-us information for all entries in + * the fn_app_contact_us table, sorted by app name. If an application is active but has no fn_app_contact_us entry, it will have no entry in this result. + * + * @return List of AppContactUsItem, one for each item in fn_app_contact_us table. + * @throws Exception + */ + public List<AppContactUsItem> getAppContactUs() throws Exception; + + /** + * Gets a list of contact-us information for all applications + * in the fn_app table, extended with any information in the fn_app_contact_us table. + * + * @return List of AppContactUsItem, one for each item in fn_app table. + * @throws Exception + */ + public List<AppContactUsItem> getAppsAndContacts() throws Exception; + + public List<AppCategoryFunctionsItem> getAppCategoryFunctions() throws Exception; + + public String saveAppContactUs(List<AppContactUsItem> contactUs) throws Exception; + + public String saveAppContactUs(AppContactUsItem contactUs) throws Exception; + + public String deleteContactUs(Long id) throws Exception; + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsServiceImpl.java index 41c5d9fd..628414d9 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsServiceImpl.java @@ -1,189 +1,189 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.transaction.annotation.Transactional;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalapp.portal.domain.AppContactUs;
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.ecomp.model.AppCategoryFunctionsItem;
-import org.openecomp.portalapp.portal.ecomp.model.AppContactUsItem;
-
-/**
- * Provides database access for the contact-us page controllers.
- */
-@Transactional
-@org.springframework.context.annotation.Configuration
-public class AppContactUsServiceImpl implements AppContactUsService {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppContactUsServiceImpl.class);
-
- @Autowired
- private DataAccessService dataAccessService;
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalapp.portal.service.AppContactUsService#
- * getAppContactUs()
- */
- @SuppressWarnings("unchecked")
- @Override
- public List<AppContactUsItem> getAppContactUs() throws Exception {
- List<AppContactUsItem> contactUsItemList = (List<AppContactUsItem>) getDataAccessService()
- .executeNamedQuery("getAppContactUsItems", null, null);
- Collections.sort(contactUsItemList, new AppContactUsItemCompare());
- return contactUsItemList;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalapp.portal.service.AppContactUsService#
- * getAllAppsAndContacts()
- */
- @SuppressWarnings("unchecked")
- @Override
- public List<AppContactUsItem> getAppsAndContacts() throws Exception {
- List<AppContactUsItem> contactUsItemList = (List<AppContactUsItem>) getDataAccessService()
- .executeNamedQuery("getAppsAndContacts", null, null);
- Collections.sort(contactUsItemList, new AppContactUsItemCompare());
- return contactUsItemList;
- }
-
- /**
- * Assists in sorting app-contact-us items by application name.
- */
- class AppContactUsItemCompare implements Comparator<AppContactUsItem> {
- @Override
- public int compare(AppContactUsItem o1, AppContactUsItem o2) {
- return o1.getAppName().compareTo(o2.getAppName());
- }
- }
-
- /**
- * Gets a table of category and function details for apps that participate
- * in the functional menu.
- */
- @Override
- public List<AppCategoryFunctionsItem> getAppCategoryFunctions() throws Exception {
- @SuppressWarnings("unchecked")
- // This named query requires no parameters.
- List<AppCategoryFunctionsItem> list = (List<AppCategoryFunctionsItem>) dataAccessService
- .executeNamedQuery("getAppCategoryFunctions", null, null);
- logger.debug(EELFLoggerDelegate.debugLogger, "getAppCategoryFunctions: result list size is " + list.size());
- return list;
- }
-
- /**
- * Saves the list of contact-us objects to the database.
- */
- @Override
- @Transactional(rollbackFor = Exception.class)
- public String saveAppContactUs(List<AppContactUsItem> contactUsModelList) throws Exception {
- try {
- for (AppContactUsItem contactUs : contactUsModelList) {
- String status = saveAppContactUs(contactUs);
- if (!status.equals("success"))
- throw new Exception("saveAppContaatUsFailed: service returned " + status);
- }
- return "success";
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "", e);
- throw new Exception(e);
- }
-
- }
-
- /**
- * Saves a single contact-us object to the database, either creating a new
- * row or updating if the argument has the ID of an existing row.
- */
- @Override
- @Transactional(rollbackFor = Exception.class)
- public String saveAppContactUs(AppContactUsItem contactUsModel) throws Exception {
- try {
- HashMap<String, Object> map = new HashMap<String, Object>();
- AppContactUs contactUs = null;
- try {
- contactUs = (AppContactUs) getDataAccessService().getDomainObject(AppContactUs.class,
- contactUsModel.getAppId(), map);
- } catch (Exception e) {
- logger.debug(EELFLoggerDelegate.debugLogger, "saveAppContactUs: not found for App {}, adding new entry",
- contactUsModel.getAppName());
- contactUs = new AppContactUs();
- }
-
- // Populate the AppContactUs model for the database.
- EPApp app = (EPApp) getDataAccessService().getDomainObject(EPApp.class, contactUsModel.getAppId(), map);
- if (app == null || app.getId() == null)
- throw new Exception("saveAppContactus: App not found for Id " + contactUsModel.getAppId());
- contactUs.setApp(app);
- contactUs.setDescription(contactUsModel.getDescription());
- contactUs.setContactName(contactUsModel.getContactName());
- contactUs.setContactEmail(contactUsModel.getContactEmail());
- contactUs.setActiveYN(contactUsModel.getActiveYN());
- contactUs.setUrl(contactUsModel.getUrl());
- getDataAccessService().saveDomainObject(contactUs, map);
- return "success";
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "saveAppContactUs failed", e);
- throw e;
- // return "failure";
- }
- }
-
- /**
- * Deletes the row from the app contact us table with the specified ID.
- */
- @Override
- public String deleteContactUs(Long id) throws Exception {
- try {
- HashMap<String, Object> map = new HashMap<String, Object>();
- AppContactUs contactUs = (AppContactUs) getDataAccessService().getDomainObject(AppContactUs.class, id, map);
- if (contactUs.getApp() == null)
- throw new Exception("Delete unsuccessful for Id " + id);
- getDataAccessService().deleteDomainObject(contactUs, map);
- return "success";
- } catch (Exception e) {
-
- logger.info(EELFLoggerDelegate.errorLogger, "", e);
- throw e;
- }
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalapp.portal.domain.AppContactUs; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.ecomp.model.AppCategoryFunctionsItem; +import org.openecomp.portalapp.portal.ecomp.model.AppContactUsItem; + +/** + * Provides database access for the contact-us page controllers. + */ +@Transactional +@org.springframework.context.annotation.Configuration +public class AppContactUsServiceImpl implements AppContactUsService { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppContactUsServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.AppContactUsService# + * getAppContactUs() + */ + @SuppressWarnings("unchecked") + @Override + public List<AppContactUsItem> getAppContactUs() throws Exception { + List<AppContactUsItem> contactUsItemList = (List<AppContactUsItem>) getDataAccessService() + .executeNamedQuery("getAppContactUsItems", null, null); + Collections.sort(contactUsItemList, new AppContactUsItemCompare()); + return contactUsItemList; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.AppContactUsService# + * getAllAppsAndContacts() + */ + @SuppressWarnings("unchecked") + @Override + public List<AppContactUsItem> getAppsAndContacts() throws Exception { + List<AppContactUsItem> contactUsItemList = (List<AppContactUsItem>) getDataAccessService() + .executeNamedQuery("getAppsAndContacts", null, null); + Collections.sort(contactUsItemList, new AppContactUsItemCompare()); + return contactUsItemList; + } + + /** + * Assists in sorting app-contact-us items by application name. + */ + class AppContactUsItemCompare implements Comparator<AppContactUsItem> { + @Override + public int compare(AppContactUsItem o1, AppContactUsItem o2) { + return o1.getAppName().compareTo(o2.getAppName()); + } + } + + /** + * Gets a table of category and function details for apps that participate + * in the functional menu. + */ + @Override + public List<AppCategoryFunctionsItem> getAppCategoryFunctions() throws Exception { + @SuppressWarnings("unchecked") + // This named query requires no parameters. + List<AppCategoryFunctionsItem> list = (List<AppCategoryFunctionsItem>) dataAccessService + .executeNamedQuery("getAppCategoryFunctions", null, null); + logger.debug(EELFLoggerDelegate.debugLogger, "getAppCategoryFunctions: result list size is " + list.size()); + return list; + } + + /** + * Saves the list of contact-us objects to the database. + */ + @Override + @Transactional(rollbackFor = Exception.class) + public String saveAppContactUs(List<AppContactUsItem> contactUsModelList) throws Exception { + try { + for (AppContactUsItem contactUs : contactUsModelList) { + String status = saveAppContactUs(contactUs); + if (!status.equals("success")) + throw new Exception("saveAppContaatUsFailed: service returned " + status); + } + return "success"; + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "", e); + throw new Exception(e); + } + + } + + /** + * Saves a single contact-us object to the database, either creating a new + * row or updating if the argument has the ID of an existing row. + */ + @Override + @Transactional(rollbackFor = Exception.class) + public String saveAppContactUs(AppContactUsItem contactUsModel) throws Exception { + try { + HashMap<String, Object> map = new HashMap<String, Object>(); + AppContactUs contactUs = null; + try { + contactUs = (AppContactUs) getDataAccessService().getDomainObject(AppContactUs.class, + contactUsModel.getAppId(), map); + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "saveAppContactUs: not found for App {}, adding new entry", + contactUsModel.getAppName()); + contactUs = new AppContactUs(); + } + + // Populate the AppContactUs model for the database. + EPApp app = (EPApp) getDataAccessService().getDomainObject(EPApp.class, contactUsModel.getAppId(), map); + if (app == null || app.getId() == null) + throw new Exception("saveAppContactus: App not found for Id " + contactUsModel.getAppId()); + contactUs.setApp(app); + contactUs.setDescription(contactUsModel.getDescription()); + contactUs.setContactName(contactUsModel.getContactName()); + contactUs.setContactEmail(contactUsModel.getContactEmail()); + contactUs.setActiveYN(contactUsModel.getActiveYN()); + contactUs.setUrl(contactUsModel.getUrl()); + getDataAccessService().saveDomainObject(contactUs, map); + return "success"; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveAppContactUs failed", e); + throw e; + // return "failure"; + } + } + + /** + * Deletes the row from the app contact us table with the specified ID. + */ + @Override + public String deleteContactUs(Long id) throws Exception { + try { + HashMap<String, Object> map = new HashMap<String, Object>(); + AppContactUs contactUs = (AppContactUs) getDataAccessService().getDomainObject(AppContactUs.class, id, map); + if (contactUs.getApp() == null) + throw new Exception("Delete unsuccessful for Id " + id); + getDataAccessService().deleteDomainObject(contactUs, map); + return "success"; + } catch (Exception e) { + + logger.info(EELFLoggerDelegate.errorLogger, "", e); + throw e; + } + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java index aefbbbd5..2ee98644 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java @@ -1,42 +1,42 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-
-package org.openecomp.portalapp.portal.service;
-
-import org.openecomp.portalapp.portal.domain.EPApp;
-
-public interface AppsCacheService {
-
- /**
- * returns an app by id from the cache
- * @param appId
- * @return corresponding App
- */
- EPApp getApp(Long appId);
-
- /**
- * returns the corresponding application endpoint
- * @param appId
- * @return if appId exists in cache, then return corresponding application endpoint, null otherwise.
- */
- String getAppEndpoint(Long appId);
-
- EPApp getAppForAnalytics(String appKey);
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ + +package org.openecomp.portalapp.portal.service; + +import org.openecomp.portalapp.portal.domain.EPApp; + +public interface AppsCacheService { + + /** + * returns an app by id from the cache + * @param appId + * @return corresponding App + */ + EPApp getApp(Long appId); + + /** + * returns the corresponding application endpoint + * @param appId + * @return if appId exists in cache, then return corresponding application endpoint, null otherwise. + */ + String getAppEndpoint(Long appId); + + EPApp getAppForAnalytics(String appKey); +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java index 80aa00d4..c5856c62 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java @@ -1,136 +1,136 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.annotation.PostConstruct;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.stereotype.Service;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-
-@Service("appsCacheService")
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class AppsCacheServiceImple implements AppsCacheService {
- @Autowired
- EPAppService appsService;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsCacheServiceImple.class);
-
- final class CacheConfiguration {
-
- private long updateTime = 0;
- private int updateInterval = 10;
-
- public CacheConfiguration (long _updateTime, int _updateInterval) {
- updateTime = _updateTime;
- updateInterval = _updateInterval;
- }
- }
-
- CacheConfiguration appConf = null;
- CacheConfiguration analyticsAppConf = null;
-
-
- private static volatile Map<Long, EPApp> appsMap;
- private static volatile Map<String, EPApp> anlyticsAppsMap;
-
- @PostConstruct
- public void init() {
- appConf = new CacheConfiguration(0, 10);
- analyticsAppConf = new CacheConfiguration(0, 3600);
-
- this.refreshAppsMap(appConf);
- }
-
- private Map<Long, EPApp> refreshAppsMap(CacheConfiguration conf) {
- long now = System.currentTimeMillis();
-
- if(noNeedToUpdate(now, conf))
- return null;
-
- synchronized (this) {
- if(noNeedToUpdate(now, conf))
- return null;
- List<EPApp> allApps = appsService.getAppsFullList();
- Map<Long, EPApp> newAppsMap = new HashMap<Long, EPApp>();
- for (EPApp app : allApps) {
- newAppsMap.put(app.getId(), app);
- }
-
- Map<String, EPApp> newAnalyticsAppsMap = new HashMap<String, EPApp>();
- for (EPApp app : allApps) {
- newAnalyticsAppsMap.put(app.getUebKey(), app);
- }
- // Switch cache with the new one.
- appsMap = newAppsMap;
- anlyticsAppsMap = newAnalyticsAppsMap;
- conf.updateTime = now;
- }
-
- return appsMap;
- }
-
- private boolean noNeedToUpdate(long now, CacheConfiguration conf) {
- long secondsPassed = (now - conf.updateTime)/1000;
- if(secondsPassed < conf.updateInterval){
- logger.debug(EELFLoggerDelegate.debugLogger, "no need to refresh yet, seconds since last refresh: " + secondsPassed + ", refresh interval (sec) = " + conf.updateInterval);
- return true; // no need to update cache
- }
- return false; // its time to update
- }
-
- @Override
- public String getAppEndpoint(Long appId) {
- refreshAppsMap(appConf);
- EPApp app = appsMap.get(appId);
- if(app != null)
- return app.getAppRestEndpoint();
- return null;
- }
-
- @Override
- public EPApp getApp(Long appId) {
- refreshAppsMap(appConf);
- EPApp app = appsMap.get(appId);
- if(app != null)
- return app;
- return null;
- }
-
- @Override
- public EPApp getAppForAnalytics(String appKey) {
- refreshAppsMap(analyticsAppConf);
- EPApp app = anlyticsAppsMap.get(appKey);
- if(app != null)
- return app;
- return null;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; + +@Service("appsCacheService") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class AppsCacheServiceImple implements AppsCacheService { + @Autowired + EPAppService appsService; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsCacheServiceImple.class); + + final class CacheConfiguration { + + private long updateTime = 0; + private int updateInterval = 10; + + public CacheConfiguration (long _updateTime, int _updateInterval) { + updateTime = _updateTime; + updateInterval = _updateInterval; + } + } + + CacheConfiguration appConf = null; + CacheConfiguration analyticsAppConf = null; + + + private static volatile Map<Long, EPApp> appsMap; + private static volatile Map<String, EPApp> anlyticsAppsMap; + + @PostConstruct + public void init() { + appConf = new CacheConfiguration(0, 10); + analyticsAppConf = new CacheConfiguration(0, 3600); + + this.refreshAppsMap(appConf); + } + + private Map<Long, EPApp> refreshAppsMap(CacheConfiguration conf) { + long now = System.currentTimeMillis(); + + if(noNeedToUpdate(now, conf)) + return null; + + synchronized (this) { + if(noNeedToUpdate(now, conf)) + return null; + List<EPApp> allApps = appsService.getAppsFullList(); + Map<Long, EPApp> newAppsMap = new HashMap<Long, EPApp>(); + for (EPApp app : allApps) { + newAppsMap.put(app.getId(), app); + } + + Map<String, EPApp> newAnalyticsAppsMap = new HashMap<String, EPApp>(); + for (EPApp app : allApps) { + newAnalyticsAppsMap.put(app.getUebKey(), app); + } + // Switch cache with the new one. + appsMap = newAppsMap; + anlyticsAppsMap = newAnalyticsAppsMap; + conf.updateTime = now; + } + + return appsMap; + } + + private boolean noNeedToUpdate(long now, CacheConfiguration conf) { + long secondsPassed = (now - conf.updateTime)/1000; + if(secondsPassed < conf.updateInterval){ + logger.debug(EELFLoggerDelegate.debugLogger, "no need to refresh yet, seconds since last refresh: " + secondsPassed + ", refresh interval (sec) = " + conf.updateInterval); + return true; // no need to update cache + } + return false; // its time to update + } + + @Override + public String getAppEndpoint(Long appId) { + refreshAppsMap(appConf); + EPApp app = appsMap.get(appId); + if(app != null) + return app.getAppRestEndpoint(); + return null; + } + + @Override + public EPApp getApp(Long appId) { + refreshAppsMap(appConf); + EPApp app = appsMap.get(appId); + if(app != null) + return app; + return null; + } + + @Override + public EPApp getAppForAnalytics(String appKey) { + refreshAppsMap(analyticsAppConf); + EPApp app = anlyticsAppsMap.get(appKey); + if(app != null) + return app; + return null; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthAccountService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthAccountService.java index 011a6485..4b4342d4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthAccountService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthAccountService.java @@ -6,42 +6,59 @@ import org.openecomp.portalapp.portal.domain.BasicAuthCredentials; import org.openecomp.portalapp.portal.domain.EPEndpoint; public interface BasicAuthAccountService { - + /** - * Saves Basic Authentication account for external systems - * @param BasicAuthCredentials + * Saves Basic Authentication account for external systems + * + * @param newCredential + * BasicAuthCredentials * @return Id of the newly created account + * @throws Exception */ Long saveBasicAuthAccount(BasicAuthCredentials newCredential) throws Exception; - + /** - * Saves Endpoint associated with a Basic Auth account - * @param EPEndpoint + * Saves Endpoint associated with a Basic Auth account + * + * @param endpoint + * EPEndpoint * @return Id of the newly created endpoint + * @throws Exception */ Long saveEndpoints(EPEndpoint endpoint) throws Exception; - + /** - * Saves Endpoint associated with a Basic Auth account - * @param accountId, endpointId + * Saves Endpoint associated with a Basic Auth account + * + * @param accountId + * @param endpointId + * @throws Exception */ void saveEndpointAccount(Long accountId, Long endpointId) throws Exception; - + /** - * Returns list of all BasicAuthCredentials in the sytem + * Returns list of all BasicAuthCredentials in the sytem + * * @return List<BasicAuthCredentials> + * @throws Exception */ List<BasicAuthCredentials> getAccountData() throws Exception; - + /** * Deletes BasicAuthenticationAccount + * * @param accountId + * @throws Exception */ void deleteEndpointAccout(Long accountId) throws Exception; - + /** * Updates BasicAuthenticationAccount - * @param accountId, BasicAuthCredentials + * + * @param accountId + * @param newCredential + * BasicAuthCredentials + * @throws Exception */ void updateBasicAuthAccount(Long accountId, BasicAuthCredentials newCredential) throws Exception; } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthAccountServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthAccountServiceImpl.java index fd0fb597..753a501e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthAccountServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthAccountServiceImpl.java @@ -5,14 +5,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.hibernate.Session; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import org.openecomp.portalapp.portal.domain.BasicAuthCredentials; import org.openecomp.portalapp.portal.domain.EPEndpoint; import org.openecomp.portalapp.portal.domain.EPEndpointAccount; -import org.openecomp.portalapp.portal.domain.MicroserviceData; -import org.openecomp.portalapp.portal.domain.MicroserviceParameter; import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; @@ -136,6 +133,7 @@ public class BasicAuthAccountServiceImpl implements BasicAuthAccountService{ @Override public List<BasicAuthCredentials> getAccountData() throws Exception { + @SuppressWarnings("unchecked") List<BasicAuthCredentials> list = (List<BasicAuthCredentials>) dataAccessService.getList(BasicAuthCredentials.class, null); for (int i = 0; i < list.size(); i++) { if (list.get(i).getPassword() != null) diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthenticationCredentialService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthenticationCredentialService.java index 459a6504..e5966603 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthenticationCredentialService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthenticationCredentialService.java @@ -1,35 +1,35 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import org.openecomp.portalapp.portal.domain.BasicAuthCredentials;
-
-public interface BasicAuthenticationCredentialService {
- /**
- * Gets the basic authentication credential for the specified appName from
- * table ep_basic_auth_account
- *
- * @param appName
- * External application name
- * @return BasicAuthCredentials for the specified app; null if the app is
- * not known.
- */
- public BasicAuthCredentials getBasicAuthCredentialByAppName(String appName);
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import org.openecomp.portalapp.portal.domain.BasicAuthCredentials; + +public interface BasicAuthenticationCredentialService { + /** + * Gets the basic authentication credential for the specified appName from + * table ep_basic_auth_account + * + * @param username + * External user name + * @return BasicAuthCredentials for the specified app; null if the username + * is not known. + */ + public BasicAuthCredentials getBasicAuthCredentialByUsernameAndPassword(String username, String password); +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthenticationCredentialServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthenticationCredentialServiceImpl.java index 54a9d2af..8a7dd19a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthenticationCredentialServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/BasicAuthenticationCredentialServiceImpl.java @@ -27,7 +27,6 @@ import org.hibernate.criterion.Restrictions; import org.openecomp.portalapp.portal.domain.BasicAuthCredentials; import org.openecomp.portalapp.portal.domain.EPEndpoint; import org.openecomp.portalapp.portal.domain.EPEndpointAccount; -import org.openecomp.portalapp.portal.domain.SharedContext; import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.openecomp.portalsdk.core.service.DataAccessService; @@ -46,16 +45,20 @@ public class BasicAuthenticationCredentialServiceImpl implements BasicAuthentica private DataAccessService dataAccessService; @Override - public BasicAuthCredentials getBasicAuthCredentialByAppName(String appName) { - + public BasicAuthCredentials getBasicAuthCredentialByUsernameAndPassword(String username, String password) { + List<Criterion> restrictionsList = new ArrayList<Criterion>(); - Criterion contextIdCrit = Restrictions.eq("applicationName", appName); - restrictionsList.add(contextIdCrit); + Criterion contextUserNameCrit = Restrictions.eq("username", username); + restrictionsList.add(contextUserNameCrit); + Criterion contextPasswordCrit = Restrictions.eq("password", password); + restrictionsList.add(contextPasswordCrit); + @SuppressWarnings("unchecked") - List<BasicAuthCredentials> credList = (List<BasicAuthCredentials>) dataAccessService.getList(BasicAuthCredentials.class, null, restrictionsList, null); + List<BasicAuthCredentials> credList = (List<BasicAuthCredentials>) dataAccessService + .getList(BasicAuthCredentials.class, null, restrictionsList, null); if (credList == null || credList.size() == 0) { logger.error(EELFLoggerDelegate.errorLogger, - "getBasicAuthCredentialByAppName: no credential(s) for " + appName); + "getBasicAuthCredentialByAppName: no credential(s) for " + username); return null; } logger.debug(EELFLoggerDelegate.debugLogger, @@ -64,15 +67,16 @@ public class BasicAuthenticationCredentialServiceImpl implements BasicAuthentica cred.setEndpoints(getEndpointsByAccountId(cred.getId())); return cred; } - - private List<EPEndpoint> getEndpointsByAccountId(long id){ - + + private List<EPEndpoint> getEndpointsByAccountId(long id) { List<EPEndpoint> list = new ArrayList<>(); List<Criterion> restrictionsList = new ArrayList<Criterion>(); Criterion contextIdCrit = Restrictions.eq("account_id", id); restrictionsList.add(contextIdCrit); - List<EPEndpointAccount> epList = (List<EPEndpointAccount>) dataAccessService.getList(EPEndpointAccount.class, null, restrictionsList, null); - for(EPEndpointAccount ep: epList){ + @SuppressWarnings("unchecked") + List<EPEndpointAccount> epList = (List<EPEndpointAccount>) dataAccessService.getList(EPEndpointAccount.class, + null, restrictionsList, null); + for (EPEndpointAccount ep : epList) { list.add((EPEndpoint) dataAccessService.getDomainObject(EPEndpoint.class, ep.getEp_id(), null)); } return list; diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ConsulHealthService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ConsulHealthService.java index 6ceb2cac..24367e6e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ConsulHealthService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ConsulHealthService.java @@ -1,32 +1,43 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalapp.portal.exceptions.NoHealthyServiceException;
-import com.ecwid.consul.ConsulException;
-import com.orbitz.consul.model.health.ServiceHealth;
-
-public interface ConsulHealthService {
- public String getServiceLocation(String service) throws NoHealthyServiceException;
- public List<ServiceHealth> getAllHealthyNodes(String service) throws ConsulException;
- public List<ServiceHealth> getAllNodes(String service) throws ConsulException;
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.exceptions.NoHealthyServiceException; +import com.ecwid.consul.ConsulException; +import com.orbitz.consul.model.health.ServiceHealth; + +public interface ConsulHealthService { + /** + * This method returns the location of one healthy node if found in Consul - + * If not found in / by Consul, it falls back to 'localhost' + * + * @param service + * @param fallbackPortOnLocalhost + * value provided by the calling service + * @return Service location + */ + public String getServiceLocation(String service, String fallbackPortOnLocalhost) throws NoHealthyServiceException; + + public List<ServiceHealth> getAllHealthyNodes(String service) throws ConsulException; + + public List<ServiceHealth> getAllNodes(String service) throws ConsulException; +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ConsulHealthServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ConsulHealthServiceImpl.java index 1d741dca..175a1c71 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ConsulHealthServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ConsulHealthServiceImpl.java @@ -1,91 +1,95 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.springframework.stereotype.Component;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import com.ecwid.consul.ConsulException;
-import com.orbitz.consul.Consul;
-import com.orbitz.consul.HealthClient;
-import com.orbitz.consul.model.health.ServiceHealth;
-
-@Component
-public class ConsulHealthServiceImpl implements ConsulHealthService {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulHealthServiceImpl.class);
-
- @Override
- public String getServiceLocation(String service){
-
- List<ServiceHealth> nodes = null;
-
- try{
- Consul consul = Consul.builder().build();
- HealthClient healthClient = consul.healthClient();
- nodes = healthClient.getHealthyServiceInstances(service).getResponse();
- }
- catch(Exception e){
- //using both loggers.
- logger.debug(logger.debugLogger, " problem getting nodes for service - " + service + e.getMessage() + " - Defaulting to localhost", e);
- logger.error(logger.errorLogger, " problem getting nodes for service - " + service + e.getMessage() + " - Defaulting to localhost", e);
-
- return "localhost:" + SystemProperties.getProperty("microservices.widget.local.port");
- }
-
- if(nodes == null || nodes.size() == 0){
- logger.debug(logger.debugLogger, "No healthy node found in the consul cluster running service " + service + ". Defaulting to localhost");
- return "localhost:" + SystemProperties.getProperty("microservices.widget.local.port");
- }
- else{
- String locationFromConsul;
- ServiceHealth node = nodes.get(0);
- locationFromConsul = node.getNode().getNode() + ":" + node.getService().getPort();
- logger.debug(logger.debugLogger, "Found healthy service location using consul - returning location " + locationFromConsul);
-
- //if locationFromConsul is null for some reason (very unlikely at this point), default to localhost
- if(null == locationFromConsul || "".equals(locationFromConsul)){
- logger.debug(logger.debugLogger, "Couldn't get location from consul for service " + service + ". Defaulting to localhost");
- return "localhost:" + SystemProperties.getProperty("microservices.widget.local.port");
- }
- else{
- logger.debug(logger.debugLogger, "Found service location from consul for service " + service + ". Location is " + locationFromConsul);
- return locationFromConsul;
- }
- }
- }
-
- @Override
- public List<ServiceHealth> getAllHealthyNodes(String service) throws ConsulException{
- Consul consul = Consul.builder().build();
- HealthClient healthClient = consul.healthClient();
- return healthClient.getHealthyServiceInstances(service).getResponse();
- }
-
- @Override
- public List<ServiceHealth> getAllNodes(String service){
- Consul consul = Consul.builder().build();
- HealthClient healthClient = consul.healthClient();
- return healthClient.getAllServiceInstances(service).getResponse();
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.stereotype.Component; + +import com.ecwid.consul.ConsulException; +import com.orbitz.consul.Consul; +import com.orbitz.consul.HealthClient; +import com.orbitz.consul.model.health.ServiceHealth; + +@Component +public class ConsulHealthServiceImpl implements ConsulHealthService { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ConsulHealthServiceImpl.class); + + @Override + public String getServiceLocation(String service, String fallbackPortOnLocalHost) { + + List<ServiceHealth> nodes = null; + + try { + Consul consul = Consul.builder().build(); + HealthClient healthClient = consul.healthClient(); + nodes = healthClient.getHealthyServiceInstances(service).getResponse(); + } catch (Exception e) { + String localFallbackServiceLocation = "localhost:" + fallbackPortOnLocalHost; + logger.debug(EELFLoggerDelegate.debugLogger, + " problem getting nodes for service {1}. Defaulting to {2}. Exception: {3}", service, + localFallbackServiceLocation, e.getMessage()); + logger.error(EELFLoggerDelegate.errorLogger, + " problem getting nodes for service {1}. Defaulting to {2}. Exception: {3}", service, + localFallbackServiceLocation, e); + return localFallbackServiceLocation; + } + + if (nodes == null || nodes.size() == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, "No healthy node found in the consul cluster running service " + service + + ". Defaulting to localhost"); + return "localhost:" + fallbackPortOnLocalHost; + } else { + String locationFromConsul; + ServiceHealth node = nodes.get(0); + locationFromConsul = node.getNode().getNode() + ":" + node.getService().getPort(); + logger.debug(EELFLoggerDelegate.debugLogger, + "Found healthy service location using consul - returning location " + locationFromConsul); + + // if locationFromConsul is null for some reason (very unlikely at + // this point), default to localhost + if (null == locationFromConsul || "".equals(locationFromConsul)) { + logger.debug(EELFLoggerDelegate.debugLogger, + "Couldn't get location from consul for service " + service + ". Defaulting to localhost"); + return "localhost:" + fallbackPortOnLocalHost; + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "Found service location from consul for service " + service + + ". Location is " + locationFromConsul); + return locationFromConsul; + } + } + } + + @Override + public List<ServiceHealth> getAllHealthyNodes(String service) throws ConsulException { + Consul consul = Consul.builder().build(); + HealthClient healthClient = consul.healthClient(); + return healthClient.getHealthyServiceInstances(service).getResponse(); + } + + @Override + public List<ServiceHealth> getAllNodes(String service) { + Consul consul = Consul.builder().build(); + HealthClient healthClient = consul.healthClient(); + return healthClient.getAllServiceInstances(service).getResponse(); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchService.java index 177f0e6a..538678b0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchService.java @@ -1,37 +1,37 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-import java.util.Map;
-
-import org.openecomp.portalapp.portal.transport.CommonWidget;
-import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
-import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem;
-
-public interface DashboardSearchService {
- public Map<String, List<SearchResultItem>> searchResults(String userId, String searchString);
- public List<String> getRelatedUsers(String userId);
-
- public CommonWidgetMeta getWidgetData(String resourceType);
- public String saveWidgetDataBulk(CommonWidgetMeta commonWidgetMetaData);
- public String saveWidgetData(CommonWidget commonWidgetData);
- public String deleteWidgetData(CommonWidget eventWidget);
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; +import java.util.Map; + +import org.openecomp.portalapp.portal.transport.CommonWidget; +import org.openecomp.portalapp.portal.transport.CommonWidgetMeta; +import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem; + +public interface DashboardSearchService { + public Map<String, List<SearchResultItem>> searchResults(String userId, String searchString); + public List<String> getRelatedUsers(String userId); + + public CommonWidgetMeta getWidgetData(String resourceType); + public String saveWidgetDataBulk(CommonWidgetMeta commonWidgetMetaData); + public String saveWidgetData(CommonWidget commonWidgetData); + public String deleteWidgetData(CommonWidget eventWidget); +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchServiceImpl.java index 412d833d..336a7522 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchServiceImpl.java @@ -1,100 +1,100 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalapp.portal.transport.CommonWidget;
-import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
-import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem;
-
-@Component
-public class DashboardSearchServiceImpl implements DashboardSearchService {
-
- @Autowired
- private DataAccessService dataAccessService;
-
- public Map<String, List<SearchResultItem>> searchResults(String userId, String searchString) {
- Map<String, String> params = new HashMap<>();
- params.put("userId", userId);
- params.put("searchQuery", searchString);
- // Named query is stored in a *.hbm.xml file, mapped to SearchResultItem
- @SuppressWarnings("unchecked")
- List<SearchResultItem> list = dataAccessService.executeNamedQuery("searchPortal", params, null);
- Map<String, List<SearchResultItem>> finalJson = null;
- if (list.size() > 0) {
- finalJson = new HashMap<String, List<SearchResultItem>>();
- for (SearchResultItem thisResult : list) {
- List<SearchResultItem> thisList = finalJson.get(thisResult.getCategory().toLowerCase());
- if (thisList == null)
- thisList = new ArrayList<SearchResultItem>();
- thisList.add(thisResult);
- finalJson.put(thisResult.getCategory().toLowerCase(), thisList);
- }
- }
- return finalJson;
- }
-
- @Override
- public List<String> getRelatedUsers(String userId) {
- Map<String, String> params = new HashMap<>();
- params.put("userId", userId);
- @SuppressWarnings("unchecked")
- List<String> activeUsers = dataAccessService.executeNamedQuery("relatedUsers", params, null);
- return activeUsers;
- }
-
- @Override
- public CommonWidgetMeta getWidgetData(String resourceType) {
- Map<String, String> params = new HashMap<>();
- params.put("cat", resourceType);
- @SuppressWarnings("unchecked")
- List<CommonWidget> widgetItems = (List<CommonWidget>) dataAccessService.executeNamedQuery("getCommonWidgetItem", params, null);
- return new CommonWidgetMeta(resourceType, widgetItems);
- }
-
- @Override
- public String saveWidgetDataBulk(CommonWidgetMeta commonMetaWidgetData) {
- for (CommonWidget widgetData : commonMetaWidgetData.getItems()) {
- widgetData.setCategory(commonMetaWidgetData.getCategory());
- dataAccessService.saveDomainObject(widgetData, null);
- }
- return "success";
- }
-
- @Override
- public String saveWidgetData(CommonWidget commonWidgetData) {
- dataAccessService.saveDomainObject(commonWidgetData, null);
- return "success";
- }
-
- @Override
- public String deleteWidgetData(CommonWidget eventWidget) {
- dataAccessService.deleteDomainObject(eventWidget, null);
- return "success";
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalapp.portal.transport.CommonWidget; +import org.openecomp.portalapp.portal.transport.CommonWidgetMeta; +import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem; + +@Component +public class DashboardSearchServiceImpl implements DashboardSearchService { + + @Autowired + private DataAccessService dataAccessService; + + public Map<String, List<SearchResultItem>> searchResults(String userId, String searchString) { + Map<String, String> params = new HashMap<>(); + params.put("userId", userId); + params.put("searchQuery", searchString); + // Named query is stored in a *.hbm.xml file, mapped to SearchResultItem + @SuppressWarnings("unchecked") + List<SearchResultItem> list = dataAccessService.executeNamedQuery("searchPortal", params, null); + Map<String, List<SearchResultItem>> finalJson = null; + if (list.size() > 0) { + finalJson = new HashMap<String, List<SearchResultItem>>(); + for (SearchResultItem thisResult : list) { + List<SearchResultItem> thisList = finalJson.get(thisResult.getCategory().toLowerCase()); + if (thisList == null) + thisList = new ArrayList<SearchResultItem>(); + thisList.add(thisResult); + finalJson.put(thisResult.getCategory().toLowerCase(), thisList); + } + } + return finalJson; + } + + @Override + public List<String> getRelatedUsers(String userId) { + Map<String, String> params = new HashMap<>(); + params.put("userId", userId); + @SuppressWarnings("unchecked") + List<String> activeUsers = dataAccessService.executeNamedQuery("relatedUsers", params, null); + return activeUsers; + } + + @Override + public CommonWidgetMeta getWidgetData(String resourceType) { + Map<String, String> params = new HashMap<>(); + params.put("cat", resourceType); + @SuppressWarnings("unchecked") + List<CommonWidget> widgetItems = (List<CommonWidget>) dataAccessService.executeNamedQuery("getCommonWidgetItem", params, null); + return new CommonWidgetMeta(resourceType, widgetItems); + } + + @Override + public String saveWidgetDataBulk(CommonWidgetMeta commonMetaWidgetData) { + for (CommonWidget widgetData : commonMetaWidgetData.getItems()) { + widgetData.setCategory(commonMetaWidgetData.getCategory()); + dataAccessService.saveDomainObject(widgetData, null); + } + return "success"; + } + + @Override + public String saveWidgetData(CommonWidget commonWidgetData) { + dataAccessService.saveDomainObject(commonWidgetData, null); + return "success"; + } + + @Override + public String deleteWidgetData(CommonWidget eventWidget) { + dataAccessService.deleteDomainObject(eventWidget, null); + return "success"; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppCommonServiceImpl.java index a5b15e24..4ef6e891 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppCommonServiceImpl.java @@ -1,1368 +1,1421 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Base64;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.annotation.PostConstruct;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.lang.StringUtils;
-import org.hibernate.Query;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.Transaction;
-import org.openecomp.portalapp.portal.domain.AdminUserApp;
-import org.openecomp.portalapp.portal.domain.AdminUserApplications;
-import org.openecomp.portalapp.portal.domain.AppIdAndNameTransportModel;
-import org.openecomp.portalapp.portal.domain.AppsResponse;
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EPUserAppsManualSortPreference;
-import org.openecomp.portalapp.portal.domain.EPUserAppsSortPreference;
-import org.openecomp.portalapp.portal.domain.EPWidgetsManualSortPreference;
-import org.openecomp.portalapp.portal.domain.EcompApp;
-import org.openecomp.portalapp.portal.domain.UserRole;
-import org.openecomp.portalapp.portal.domain.UserRoles;
-import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem;
-import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.transport.EPAppsManualPreference;
-import org.openecomp.portalapp.portal.transport.EPAppsSortPreference;
-import org.openecomp.portalapp.portal.transport.EPDeleteAppsManualSortPref;
-import org.openecomp.portalapp.portal.transport.EPWidgetsSortPreference;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
-import org.openecomp.portalapp.portal.transport.LocalRole;
-import org.openecomp.portalapp.portal.transport.OnboardingApp;
-import org.openecomp.portalapp.portal.ueb.EPUebHelper;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.ueb.Helper;
-import org.openecomp.portalsdk.core.onboarding.ueb.TopicManager;
-import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import com.att.nsa.apiClient.http.HttpException;
-import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
-import com.att.nsa.cambria.client.CambriaClientBuilders;
-import com.att.nsa.cambria.client.CambriaIdentityManager;
-import com.google.common.primitives.Ints;
-
-public class EPAppCommonServiceImpl implements EPAppService {
-
- protected String ECOMP_APP_ID = "1";
- protected String SUPER_ADMIN_ROLE_ID = "1";
- protected String ACCOUNT_ADMIN_ROLE_ID = "999";
- protected String RESTRICTED_APP_ROLE_ID = "900";
-
- private static final String urlField = "url";
- private static final String nameField = "name";
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppCommonServiceImpl.class);
-
- @Autowired
- AdminRolesService adminRolesService;
- @Autowired
- private SessionFactory sessionFactory;
- @Autowired
- private DataAccessService dataAccessService;
- @Autowired
- EPUebHelper epUebHelper;
-
- @PostConstruct
- private void init() {
- SUPER_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID);
- ACCOUNT_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID);
- ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
- RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID);
- }
-
- @Override
- public List<EPApp> getUserAsAdminApps(EPUser user) {
- if (adminRolesService.isAccountAdmin(user)) {
- String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where "
- + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
- + " AND FN_APP.ENABLED = 'Y'";
- logQuery(sql);
- try {
- @SuppressWarnings("unchecked")
- List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
- return adminApps;
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- return null;
- }
- } else {
- logger.error(EELFLoggerDelegate.errorLogger,
- "getUserAsAdminApps: only Account Admin may invoke this function!");
- return new ArrayList<EPApp>();
- }
- }
-
- @Override
- public List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId) {
- String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
- + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID "
- + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
- + " AND FN_APP.ENABLED = 'Y'";
-
- String sql = String.format(format, orgUserId);
- logQuery(sql);
-
- try {
- @SuppressWarnings("unchecked")
- List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
- return adminApps;
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- return null;
- }
- }
-
- @Override
- public List<EPApp> getAppsFullList() {
- @SuppressWarnings("unchecked")
- List<EPApp> apps = dataAccessService.getList(EPApp.class, null);
- return apps;
- }
-
- @Override
- public List<EcompApp> getEcompAppAppsFullList() {
- return transformAppsToEcompApps(getAppsFullList());
- }
-
- @Override
- public List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList) {
- List<EcompApp> ecompAppList = new ArrayList<EcompApp>();
- for (EPApp app : appsList) {
- EcompApp ecompApp = new EcompApp();
- ecompApp.setId(app.getId());
- ecompApp.setName(app.getName());
- ecompApp.setImageUrl(app.getImageUrl());
- ecompApp.setDescription(app.getDescription());
- ecompApp.setNotes(app.getNotes());
- ecompApp.setUrl(app.getUrl());
- ecompApp.setAlternateUrl(app.getAlternateUrl());
- ecompApp.setUebTopicName(app.getUebTopicName());
- ecompApp.setUebKey(app.getUebKey());
- ecompApp.setUebSecret(app.getUebSecret());
- ecompApp.setEnabled(app.getEnabled());
- ecompApp.setRestrictedApp(app.isRestrictedApp());
- ecompAppList.add(ecompApp);
- }
- return ecompAppList;
- }
-
- @Override
- public EPApp getApp(Long appId) {
- try {
- @SuppressWarnings("unchecked")
- List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id = " + appId, null, null);
- return (apps.size() > 0) ? apps.get(0) : null;
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- return null;
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<AppIdAndNameTransportModel> getAdminApps(EPUser user) {
- if (adminRolesService.isAccountAdmin(user)) {
- String format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app inner join FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
- + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
- + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)";
- String sql = String.format(format, user.getId());
- // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
- // app.APP_REST_ENDPOINT <> ''";
- logQuery(sql);
- try {
- return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
- }
- }
- return new ArrayList<AppIdAndNameTransportModel>();
- }
-
- @Override
- public EPApp getAppDetail(String appName) {
- final Map<String, String> params = new HashMap<String, String>();
- try {
- params.put("appName", appName);
- @SuppressWarnings("unchecked")
- List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getAppDetails", params, null);
- return (apps.size() > 0) ? apps.get(0) : null;
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- return null;
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user) {
- if (adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user)) {
- String format = "";
- String sql = "";
- if (adminRolesService.isSuperAdmin(user)) {
- format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app "
- + "where app.ENABLED = 'Y' AND app.app_type = 1";
- } else {
- format = "SELECT app.APP_ID, app.APP_NAME, APP_TYPE FROM FN_APP app inner join FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
- + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
- + " AND app.ENABLED = 'Y' AND app.app_type = 1";
- }
- sql = String.format(format, user.getId());
- // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
- // app.APP_REST_ENDPOINT <> ''";
- logQuery(sql);
- try {
- return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null);
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e);
- }
- }
- return new ArrayList<AppIdAndNameTransportModel>();
- }
-
- protected void logQuery(String sql) {
- logger.debug(EELFLoggerDelegate.debugLogger, "logQuery: " + sql);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- @Override
- public List<AdminUserApplications> getAppsAdmins() {
- String sql = "SELECT apps.APP_NAME, apps.APP_ID, user.USER_ID, user.FIRST_NAME, user.LAST_NAME, user.org_user_id FROM fn_user_role userrole "
- + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID "
- + "INNER JOIN fn_app apps ON apps.APP_ID = userrole.APP_ID " + "WHERE userrole.ROLE_ID = "
- + ACCOUNT_ADMIN_ROLE_ID + " AND (apps.ENABLED = 'Y' OR apps.APP_ID=1)";
- logQuery(sql);
- try {
- @SuppressWarnings("unchecked")
- List<AdminUserApp> adminApps = dataAccessService.executeSQLQuery(sql, AdminUserApp.class, null);
- // DataAccessService does not use generic types.
- return aggregateRowsResultsByUserId(adminApps);
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- return null;
- }
- }
-
- private List<AdminUserApplications> aggregateRowsResultsByUserId(List<AdminUserApp> adminApps) {
- HashMap<Long, AdminUserApplications> adminUserApplications = new HashMap<Long, AdminUserApplications>();
- for (AdminUserApp app : adminApps) {
- Long userId = app.getUser_Id();
- if (adminUserApplications.get(userId) == null)
- adminUserApplications.put(userId, new AdminUserApplications(app));
- else
- adminUserApplications.get(userId).addApp(app.getAppId(), app.getAppName());
- }
- return new ArrayList<AdminUserApplications>(adminUserApplications.values());
- }
-
- @Override
- public List<AppsResponse> getAllApps(Boolean all) {
- // If all is true, return both active and inactive apps. Otherwise, just
- // active apps.
- @SuppressWarnings("unchecked")
- // Sort the list by application name so the drop-down looks pretty.
- List<EPApp> apps = all
- ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
- : (List<EPApp>) dataAccessService.getList(EPApp.class,
- " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null);
-
- List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
- for (EPApp app : apps) {
- appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
- }
- return appsModified;
- }
-
- @Override
- public UserRoles getUserProfile(String loginId) {
- String format = "SELECT DISTINCT user.USER_ID, role.ROLE_ID, user.org_user_id, user.FIRST_NAME, user.LAST_NAME, role.ROLE_NAME FROM fn_user_role userrole "
- + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID "
- + "INNER JOIN fn_role role ON role.ROLE_ID = userrole.ROLE_ID "
- + "WHERE user.org_user_id = \"%s\" and (userrole.app_id = 1 or role.role_id = " + ACCOUNT_ADMIN_ROLE_ID
- + ") ";
- String sql = String.format(format, loginId);
- logQuery(sql);
- @SuppressWarnings("unchecked")
- List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserRole.class, null);
- ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
- if (usersRolesList == null || usersRolesList.size() < 1)
- return null;
-
- return usersRolesList.get(0);
- }
-
- @Override
- public UserRoles getUserProfileNormalized(EPUser user) {
- // Check database.
- UserRoles userAndRoles = getUserProfile(user.getLoginId());
- // If no roles are defined, treat this user as a guest.
- if (user.isGuest() || userAndRoles == null) {
- logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfile: treating user {} as guest",
- user.getLoginId());
- UserRole userRole = new UserRole();
- userRole.setUser_Id(user.getId());
- userRole.setOrgUserId(user.getLoginId());
- userRole.setFirstName(user.getFirstName());
- userRole.setLastName(user.getLastName());
- userRole.setRoleId(-1L);
- userRole.setRoleName("Guest");
- userRole.setUser_Id(-1L);
- userAndRoles = new UserRoles(userRole);
- }
-
- return userAndRoles;
- }
-
- protected ArrayList<UserRoles> aggregateUserProfileRowsResultsByRole(List<UserRole> userRoleList) {
- HashMap<String, UserRoles> userRoles = new HashMap<String, UserRoles>();
- for (UserRole user : userRoleList) {
- String orgUserId = user.getOrgUserId();
- if (userRoles.get(orgUserId) == null)
- userRoles.put(orgUserId, new UserRoles(user));
- else
- userRoles.get(orgUserId).addRole(user.getRoleName());
- }
- return new ArrayList<UserRoles>(userRoles.values());
- }
-
- private boolean isRestrictedApp(Long appId) {
- EPApp app = getApp(appId);
- return app.isRestrictedApp();
- }
-
- // For the functional menu edit
- @Override
- public List<LocalRole> getAppRoles(Long appId) {
- String sql = "";
- if (isRestrictedApp(appId)) {
- sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'";
- } else {
- sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where APP_ID = '" + appId + "'";
- }
- logQuery(sql);
- @SuppressWarnings("unchecked")
- List<LocalRole> appRoles = dataAccessService.executeSQLQuery(sql, LocalRole.class, null);
- return appRoles;
- }
-
- protected String userAppsQuery(EPUser user) {
- StringBuilder query = new StringBuilder();
- if (adminRolesService.isSuperAdmin(user)) {
- query.append("SELECT * FROM FN_APP where FN_APP.ENABLED = 'Y' ORDER BY APP_NAME");
- } else {
- query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where ");
- query.append(
- "FN_USER_ROLE.USER_ID = " + user.getId() + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID);
- query.append(" AND FN_APP.ENABLED = 'Y'");
- }
- return query.toString();
- }
-
- protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
- || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null
- || onboardingApp.isOpen == null || onboardingApp.isEnabled == null
- || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID))
- // For a normal app (appType==1), these fields must be filled
- // in.
- // For a restricted app (appType==2), they will be empty.
- || ((!onboardingApp.restrictedApp)
- && (onboardingApp.username == null || onboardingApp.username.length() == 0
- || onboardingApp.appPassword == null || onboardingApp.appPassword.length() == 0))) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
- }
- return fieldsValidator;
- }
-
- @Override
- public List<EPApp> getUserApps(EPUser user) {
- List<EPApp> openApps = getOpenApps();
-
- if (user.isGuest()) {
- return openApps;
- } else {
- String sql = userAppsQuery(user);
- logQuery(sql);
-
- // TreeSet<EPApp> distinctApps = new TreeSet<EPApp>();
- List<EPApp> appsList = new ArrayList<>();
- @SuppressWarnings("unchecked")
- List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
- HashSet<EPApp> appSet = new HashSet<>();
- for (EPApp app : adminApps) {
- appSet.add(app);
- appsList.add(app);
- }
-
- for (EPApp app : openApps) {
- if (!appSet.contains(app))
- appsList.add(app);
- }
-
- return appsList;
- }
- }
-
- @Override
- public List<EPApp> getPersAdminApps(EPUser user) {
- final Map<String, Long> params = new HashMap<>();
- params.put("userId", user.getId());
- // Named query is stored in EP.hbm.xml, mapped to EPApp
- @SuppressWarnings("unchecked")
- List<EPApp> list = dataAccessService.executeNamedQuery("getPersAdminApps", params, null);
- return list;
- }
-
- @Override
- public List<EPApp> getPersUserApps(EPUser user) {
- final Map<String, Long> params = new HashMap<>();
- params.put("userId", user.getId());
- // Named query is stored in EP.hbm.xml, mapped to EPApp
- @SuppressWarnings("unchecked")
- List<EPApp> list = dataAccessService.executeNamedQuery("getPersUserApps", params, null);
- return list;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalapp.portal.service.EPAppService#getAppCatalog(com.att
- * .fusionapp.ecomp.portal.domain.EPUser)
- */
- @Override
- public List<AppCatalogItem> getUserAppCatalog(EPUser user) {
- final Map<String, Long> params = new HashMap<>();
- params.put("userId", user.getId());
- // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
- @SuppressWarnings("unchecked")
- List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getUserAppCatalog", params, null);
- return list;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalapp.portal.service.EPAppService#getAdminAppCatalog(
- * org.openecomp.portalapp.portal.domain.EPUser)
- */
- @Override
- public List<AppCatalogItem> getAdminAppCatalog(EPUser user) {
- final Map<String, Long> params = new HashMap<>();
- params.put("userId", user.getId());
- // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
- @SuppressWarnings("unchecked")
- List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getAdminAppCatalog", params, null);
- return list;
- }
-
- private List<EPApp> getOpenApps() {
- @SuppressWarnings("unchecked")
- List<EPApp> openApps = dataAccessService.getList(EPApp.class, " where open='Y' and enabled='Y'", null, null);
- return openApps;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<EPApp> getAppsOrderByName(EPUser user) {
- final Map<String, Long> params = new HashMap<>();
- List<EPApp> sortedAppsByName = null;
- try {
- if (adminRolesService.isSuperAdmin(user)) {
- params.put("userId", user.getId());
- sortedAppsByName = dataAccessService.executeNamedQuery("getPersAdminAppsOrderByName", params, null);
- } else {
- params.put("userId", user.getId());
- sortedAppsByName = dataAccessService.executeNamedQuery("getPersUserAppsOrderByName", params, null);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByName failed", e);
- }
- return sortedAppsByName;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<EPApp> getAppsOrderByLastUsed(EPUser user) {
-
- final Map<String, Long> params = new HashMap<>();
- List<EPApp> sortedAppsByLastUsed = new ArrayList<EPApp>();
- List<EPApp> finalsortedAppsByLastUsed = new ArrayList<EPApp>();
- try {
- if (adminRolesService.isSuperAdmin(user)) {
- params.put("userId", user.getId());
- sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByLastUsed", params, null);
- } else {
- params.put("userId", user.getId());
- sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByLastUsed", params, null);
- }
- Set<String> epAppSet = new HashSet<String>();
- for (EPApp eapp : sortedAppsByLastUsed)
- if (!epAppSet.contains(eapp.getName())) {
- finalsortedAppsByLastUsed.add(eapp);
- epAppSet.add(eapp.getName());
- }
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByLastUsed failed", e);
- }
- return finalsortedAppsByLastUsed;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<EPApp> getAppsOrderByMostUsed(EPUser user) {
- final Map<String, Long> params = new HashMap<>();
- List<EPApp> sortedAppsByMostUsed = new ArrayList<EPApp>();
- List<EPApp> finalsortedAppsByMostUsed = new ArrayList<EPApp>();
- try {
- if (adminRolesService.isSuperAdmin(user)) {
- params.put("userId", user.getId());
- sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByMostUsed", params, null);
- } else {
- params.put("userId", user.getId());
- sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByMostUsed", params, null);
- }
- Set<String> epAppSet = new HashSet<String>();
-
- for (EPApp eapp : sortedAppsByMostUsed) {
- if (!epAppSet.contains(eapp.getName())) {
- finalsortedAppsByMostUsed.add(eapp);
- epAppSet.add(eapp.getName());
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByMostUsed failed", e);
- }
-
- return finalsortedAppsByMostUsed;
- }
-
- /*
- * This Method retrieves the User Apps by Sort Manual Preference
- *
- * @param: user--contains LoggedIn User Data
- */
- @SuppressWarnings("unchecked")
- @Override
- public List<EPApp> getAppsOrderByManual(EPUser user) {
- final Map<String, Long> params = new HashMap<>();
- List<EPApp> sortedAppsByManual = new ArrayList<EPApp>();
- List<EPApp> finalsortedAppsByManual = new ArrayList<EPApp>();
- try {
- if (adminRolesService.isSuperAdmin(user)) {
- params.put("userId", user.getId());
- sortedAppsByManual = dataAccessService.executeNamedQuery("getAdminAppsOrderByManual", params, null);
- } else {
- params.put("userId", user.getId());
- sortedAppsByManual = dataAccessService.executeNamedQuery("getUserAppsOrderByManual", params, null);
- }
- Set<String> epAppSet = new HashSet<String>();
-
- for (EPApp eapp : sortedAppsByManual) {
- if (!epAppSet.contains(eapp.getName())) {
- finalsortedAppsByManual.add(eapp);
- epAppSet.add(eapp.getName());
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByManual failed", e);
- }
- return finalsortedAppsByManual;
- }
-
- @Override
- public List<OnboardingApp> getOnboardingApps() {
- @SuppressWarnings("unchecked")
- List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id!=" + ECOMP_APP_ID, null, null);
- List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
- for (EPApp app : apps) {
- OnboardingApp onboardingApp = new OnboardingApp();
- createOnboardingFromApp(app, onboardingApp);
- onboardingAppsList.add(onboardingApp);
- }
- return onboardingAppsList;
- }
-
- @Override
- public List<OnboardingApp> getEnabledNonOpenOnboardingApps() {
- @SuppressWarnings("unchecked")
- List<EPApp> apps = dataAccessService.getList(EPApp.class,
- " where enabled = true and open = false and id!=" + ECOMP_APP_ID, null, null);
- List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
- for (EPApp app : apps) {
- OnboardingApp onboardingApp = new OnboardingApp();
- createOnboardingFromApp(app, onboardingApp);
- onboardingAppsList.add(onboardingApp);
- }
- return onboardingAppsList;
- }
-
- @SuppressWarnings("unchecked")
- private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) {
- boolean duplicatedUrl = false;
- boolean duplicatedName = false;
- List<EPApp> apps;
- if (onboardingApp.id == null) {
- apps = dataAccessService.getList(EPApp.class,
- " where url = '" + onboardingApp.url + "' or name = '" + onboardingApp.name + "'", null, null);
- } else {
- apps = dataAccessService.getList(EPApp.class, " where id = " + onboardingApp.id + " or url = '"
- + onboardingApp.url + "' or name = '" + onboardingApp.name + "'", null, null);
- }
- for (EPApp app : apps) {
- if (onboardingApp.id != null && onboardingApp.id.equals(app.getId())) {
- continue;
- }
- if (!duplicatedUrl && app.getUrl().equalsIgnoreCase(onboardingApp.url)) {
- duplicatedUrl = true;
- if (duplicatedName) {
- break;
- }
- }
- if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.name)) {
- duplicatedName = true;
- if (duplicatedUrl) {
- break;
- }
- }
- }
- if (duplicatedUrl || duplicatedName) {
- if (duplicatedUrl) {
- fieldsValidator.addProblematicFieldName(urlField);
- }
- if (duplicatedName) {
- fieldsValidator.addProblematicFieldName(nameField);
- }
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
- fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
- }
- }
-
- @Override
- public FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user) {
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering modifyOnboardingApp");
- FieldsValidator fieldsValidator = onboardingAppFieldsChecker(modifiedOnboardingApp);
- if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- validateOnboardingApp(modifiedOnboardingApp, fieldsValidator);
- }
- if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- if (modifiedOnboardingApp.id != null) {
- updateApp(modifiedOnboardingApp.id, modifiedOnboardingApp, fieldsValidator, user);
- } else {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
- }
- }
- return fieldsValidator;
- }
-
- @Override
- public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
- FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
- if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- validateOnboardingApp(newOnboardingApp, fieldsValidator);
- }
- if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- if (newOnboardingApp.id == null) {
- updateApp(null, newOnboardingApp, fieldsValidator, user);
- } else {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
- }
- }
- return fieldsValidator;
- }
-
- @Override
- public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- if (!adminRolesService.isSuperAdmin(user)) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
- return fieldsValidator;
- }
- Boolean result = false;
- Session localSession = null;
- Transaction transaction = null;
- try {
- localSession = sessionFactory.openSession();
- transaction = localSession.beginTransaction();
-
- // 1) Remove the URL for any functional menu item associated with
- // this app
- String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
- + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
- logQuery(sql);
- Query query = localSession.createSQLQuery(sql);
- query.executeUpdate();
-
- // Remove any favorites associated with a menu item that is
- // associated with this app
- sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
- + " where fn_menu_functional_roles.app_id='" + appid + "' "
- + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
-
- // Remove all role, appid records from fn_menu_functional_role
- // that are associated with this app
- sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
-
- // Remove all records from fn_user_role associated with this app
- sql = "delete from fn_user_role where app_id='" + appid + "'";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
-
- // Remove any widgets associated with this app
- sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
-
- // Remove any roles associated with this app
- sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role "
- + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
-
- // Remove all records from fn_role associated with this app
- sql = "delete from fn_role where app_id='" + appid + "'";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
-
- // Remove app contact us entries
- sql = "delete from fn_app_contact_us where app_id='" + appid + "'";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
-
- // Remove any widgets associated with this app
- sql = "delete from fn_widget where app_id='" + appid + "'";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
-
- // Remove rows in the app personalization selection table
- sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
-
- // Remove rows in the app personalization sort table
- sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
-
- // Delete the app
- sql = "delete from fn_app where app_id='" + appid + "'";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
-
- transaction.commit();
- result = true;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e);
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError);
- EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
- }
- if (!result) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- return fieldsValidator;
- }
-
- private static Object syncRests = new Object();
-
- // An app has been enabled/disabled. Must enable/disable all associated
- // functional menu items.
- private void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
- String active_yn = enabled ? "Y" : "N";
- String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
- + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
- + " AND r.app_id = '" + appId + "' ";
- logQuery(sql);
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
- for (FunctionalMenuItem menuItem : menuItems) {
- FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
- menuItem.menuId);
- myMenuItem.active_yn = active_yn;
- localSession.save(myMenuItem);
- }
- }
-
- // Attention! If (appId == null) we use this function to create application
- // otherwise we use it to modify existing application
- private void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
- // Separate out the code for a restricted app, since it doesn't need any
- // of the UEB code.
- if (onboardingApp.restrictedApp) {
- boolean result = false;
- Session localSession = null;
- Transaction transaction = null;
- try {
- localSession = sessionFactory.openSession();
- transaction = localSession.beginTransaction();
- EPApp app;
- if (appId == null) {
- app = new EPApp();
- } else {
- app = (EPApp) localSession.get(EPApp.class, appId);
- if (app == null || app.getId() == null) { // App is already
- // deleted!
- transaction.commit();
- localSession.close();
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
- return;
- }
- }
- createAppFromOnboarding(app, onboardingApp, localSession);
- localSession.saveOrUpdate(app);
- // Enable or disable all menu items associated with this app
- setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
- transaction.commit();
- result = true;
- } catch (Exception e) {
- EcompPortalUtils.rollbackTransaction(transaction,
- "updateApp rollback, exception = " + EcompPortalUtils.getStackTrace(e));
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "updateApp");
- }
- if (!result) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
-
- } else {
- synchronized (syncRests) {
- boolean result = false;
- Session localSession = null;
- Transaction transaction = null;
- try {
- localSession = sessionFactory.openSession();
- transaction = localSession.beginTransaction();
- EPApp app;
- if (appId == null) {
- app = new EPApp();
- // -------------------------------------------------------------------------------------------
- // Register this App with the UEB communication server.
- // Save
- // the App's unique mailbox/topic
- // name and keys to the FN_APP table. The App's mailbox
- // and
- // keys will be visible to the
- // admin on the ECOMP portal.
- // -------------------------------------------------------------------------------------------
- TopicManager topicManager = new TopicManager();
- final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
- .usingHosts(Helper.uebUrlList()).build();
- com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
- "ECOMP Portal Owner");
- String appKey = credential.getApiKey();
- String appSecret = credential.getApiSecret();
- String appMailboxName = null;
-
- int maxNumAttemptsToCreateATopic = 3;
- boolean successfullyCreatedMailbox = false;
- for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
- appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
-
- try {
- topicManager.createTopic(
- PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
- PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
- appMailboxName, "ECOMP outbox for app" + onboardingApp.name);
- successfullyCreatedMailbox = true;
- logger.debug(EELFLoggerDelegate.debugLogger,
- "Successfully created " + appMailboxName + " for App " + onboardingApp.name);
- logger.debug(EELFLoggerDelegate.debugLogger, " Key = " + appKey + " Secret = "
- + appSecret + " generated using = " + user.getEmail());
- break;
- } catch (HttpException e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
- if (e.getStatusCode() == 409) {
- logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName
- + " already exists. Will try using a different name", e);
- } else {
- logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ",
- e);
- }
- }
- }
-
- if (successfullyCreatedMailbox) {
- onboardingApp.setUebTopicName(appMailboxName);
- onboardingApp.setUebKey(appKey);
- onboardingApp.setUebSecret(appSecret);
-
- try {
- /*
- * EP is a publisher to this App's new mailbox
- */
- topicManager.addPublisher(
- PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
- PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
- PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
- appMailboxName);
-
- /*
- * This App is a subscriber of its own mailbox
- */
- topicManager.addSubscriber(
- PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
- PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
- appMailboxName);
-
- /*
- * This App is a publisher to EP
- */
- topicManager.addPublisher(
- PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
- PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
- PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
- } catch (HttpException | CambriaApiException | IOException e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
- logger.error(EELFLoggerDelegate.errorLogger,
- "Error when configuring Publisher/Subscriber for App's new mailbox", e);
- transaction.commit();
- localSession.close();
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
- return;
- }
- } else {
- transaction.commit();
- localSession.close();
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
- return;
- }
- } else {
- app = (EPApp) localSession.get(EPApp.class, appId);
- if (app == null || app.getId() == null) {
- // App is already deleted!
- transaction.commit();
- localSession.close();
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
- return;
- }
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding");
- createAppFromOnboarding(app, onboardingApp, localSession);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "LR: updateApp: finished calling createAppFromOnboarding");
- localSession.saveOrUpdate(app);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "LR: updateApp: finished calling localSession.saveOrUpdate");
- // Enable or disable all menu items associated with this app
- setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "LR: updateApp: finished calling setFunctionalMenuItemsEnabled");
- transaction.commit();
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit");
- epUebHelper.addPublisher(app);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "LR: updateApp: finished calling epUebHelper.addPublisher");
- result = true;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e);
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e);
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- EcompPortalUtils.rollbackTransaction(transaction,
- "updateApp rollback, exception = " + EcompPortalUtils.getStackTrace(e));
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "updateApp");
- }
- if (!result) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- }
- }
- }
-
- /**
- * Populates a transport model of the application from a database row model.
- * Leaves out the thumbnail because the FE fetches images via a different
- * API.
- *
- * @param app
- * Model of database row
- * @param onboardingApp
- * Model for transport as JSON
- */
- @Override
- public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
- onboardingApp.id = app.getId();
- onboardingApp.name = app.getName();
- onboardingApp.imageUrl = app.getImageUrl();
- onboardingApp.description = app.getDescription();
- onboardingApp.notes = app.getNotes();
- onboardingApp.url = app.getUrl();
- onboardingApp.alternateUrl = app.getAlternateUrl();
- onboardingApp.restUrl = app.getAppRestEndpoint();
- onboardingApp.isOpen = app.getOpen();
- onboardingApp.isEnabled = app.getEnabled();
- onboardingApp.username = app.getUsername();
- onboardingApp.appPassword = decryptedPassword(app.getAppPassword(), app);
- onboardingApp.uebTopicName = app.getUebTopicName();
- onboardingApp.uebKey = app.getUebKey();
- onboardingApp.uebSecret = app.getUebSecret();
- onboardingApp.setRestrictedApp(app.isRestrictedApp());
- // if (app.getThumbnail() != null)
- // onboardingApp.thumbnail = new
- // String(Base64.getEncoder().encode(app.getThumbnail()));
- }
-
- /**
- * Creates a database object for an application from an uploaded transport
- * model. Must decode the thumbnail, if any.
- *
- * @param app
- * @param onboardingApp
- * @param localSession
- * @return The first argument.
- */
- protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
- app.setName(onboardingApp.name);
- app.setDescription(onboardingApp.description);
- app.setNotes(onboardingApp.notes);
- app.setUrl(onboardingApp.url);
- app.setAlternateUrl(onboardingApp.alternateUrl);
- app.setAppRestEndpoint(onboardingApp.restUrl);
- app.setOpen(onboardingApp.isOpen);
- app.setEnabled(onboardingApp.isEnabled);
- app.setUsername(onboardingApp.username);
- app.setAppPassword(this.encryptedPassword(onboardingApp.appPassword, app));
- app.setUebTopicName(onboardingApp.uebTopicName);
- app.setUebKey(onboardingApp.uebKey);
- app.setUebSecret(onboardingApp.uebSecret);
- app.setRestrictedApp(onboardingApp.restrictedApp);
- if (!StringUtils.isEmpty(onboardingApp.thumbnail)) {
- logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty");
- String[] splitBase64Thumbnail = onboardingApp.thumbnail.split("base64,");
- logger.debug(EELFLoggerDelegate.debugLogger,
- "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
- if (splitBase64Thumbnail.length > 1) {
- // This occurs when we have a new image, not an existing image
- byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
- logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode");
- // This is basically a boolean indicator that an image is
- // present.
- app.setImageUrl(constructImageName(onboardingApp));
- app.setThumbnail(decodedImage);
- }
- } else if (app.getThumbnail() != null) {
- // The thumbnail that came in from the json is empty; the previous
- // thumbnail is NOT empty. Must delete it.
- logger.debug(EELFLoggerDelegate.debugLogger,
- "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null");
- app.setImageUrl(null);
- app.setThumbnail(null);
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger,
- "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is null");
- }
- return app;
- }
-
- protected String constructImageName(OnboardingApp onboardingApp) {
- return "portal_" + String.valueOf(onboardingApp.url.hashCode() + "_" + (int) (Math.random() * 100000.0))
- + ".png";
- }
-
- // Don't encrypt or decrypt the password if it is null or the empty string
- private String decryptedPassword(String encryptedAppPwd, EPApp app) {
- String result = "";
- if (encryptedAppPwd != null & encryptedAppPwd.length() > 0) {
- try {
- result = CipherUtil.decrypt(encryptedAppPwd,
- SystemProperties.getProperty(SystemProperties.Decryption_Key));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e);
- }
- }
- return result;
- }
-
- protected String encryptedPassword(String decryptedAppPwd, EPApp app) {
- String result = "";
- if (decryptedAppPwd != null & decryptedAppPwd.length() > 0) {
- try {
- result = CipherUtil.encrypt(decryptedAppPwd,
- SystemProperties.getProperty(SystemProperties.Decryption_Key));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e);
- }
- }
- return result;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- final Map<String, Long> params = new HashMap<>();
- List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>();
-
- try {
- params.put("userId", user.getId());
- epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
- Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>();
- for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) {
- existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref);
- }
- for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) {
- if (epWidgetsManPref.getWidgetid() != null) {
- Long widgetid = epWidgetsManPref.getWidgetid();
- if (existingWidgetsIds.containsKey(widgetid)) {
- EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid);
- epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
- epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
- epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
- epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
- HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
- additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId());
- dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam);
- } else {
- EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference();
- epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid());
- epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow());
- epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol());
- epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX());
- epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY());
- epWidgetsManualSort.setUserId(Ints.checkedCast(user.getId()));
- dataAccessService.saveDomainObject(epWidgetsManualSort, null);
- }
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- return fieldsValidator;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- final Map<String, Long> params = new HashMap<>();
- List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>();
- try {
- params.put("userId", user.getId());
- epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null);
- Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>();
- for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) {
- existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref);
- }
- for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) {
- if (delEpWidgetsManPref.getWidgetid() != null) {
- Long widgetId = delEpWidgetsManPref.getWidgetid();
- if (existingWidgetIds.containsKey(widgetId)) {
- dataAccessService.deleteDomainObjects(EPWidgetsManualSortPreference.class,
- "widget_id=" + widgetId + " AND user_id=" + user.getId(), null);
- }
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- return fieldsValidator;
- }
-
- /*
- * This Method Stores the Sort Order of User Apps by Sort Manual Preference
- *
- * @param: appsSortManual--contains User Apps Data
- *
- * @param: user--contains LoggedIn User Data
- */
- @SuppressWarnings("unchecked")
- @Override
- public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- final Map<String, Long> params = new HashMap<>();
- List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
-
- try {
- params.put("userId", user.getId());
- epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
- Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
- for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) {
- existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref);
- }
- for (EPAppsManualPreference epAppsManPref : appsSortManual) {
- if (epAppsManPref.getAppid() != null) {
- Long appid = epAppsManPref.getAppid();
- if (existingAppIds.containsKey(appid)) {
- EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid);
- epAppsManualSort
- .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
- HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
- additionalUpdateParam.put("userId", epAppsManualSort.getUserId());
- dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam);
- } else {
- EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference();
- epAppsManualSort.setAppId(epAppsManPref.getAppid());
- epAppsManualSort
- .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1);
- epAppsManualSort.setUserId(Ints.checkedCast(user.getId()));
- dataAccessService.saveDomainObject(epAppsManualSort, null);
- }
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- return fieldsValidator;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalapp.portal.service.EPAppService#
- * deleteUserAppSortManual(java.lang.String,
- * org.openecomp.portalapp.portal.domain.EPUser)
- */
- @SuppressWarnings("unchecked")
- @Override
- public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- final Map<String, Long> params = new HashMap<>();
- List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>();
- try {
- params.put("userId", user.getId());
- epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null);
- Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>();
- for (EPUserAppsManualSortPreference userAppPref : epManualApps) {
- existingAppIds.put(userAppPref.getAppId(), userAppPref);
- }
- if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) {
- dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class,
- "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- return fieldsValidator;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- final Map<String, Long> params = new HashMap<>();
- List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>();
- EPUserAppsSortPreference usrSortPr = null;
- try {
- params.put("userId", user.getId());
- epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
- if (epSortTypes.size() == 0) {
- usrSortPr = new EPUserAppsSortPreference();
- usrSortPr.setUserId(Ints.checkedCast(user.getId()));
- usrSortPr.setSortPref(appsSortPreference.getValue());
- dataAccessService.saveDomainObject(usrSortPr, null);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
- } else {
- usrSortPr = epSortTypes.get(0);
- usrSortPr.setSortPref(appsSortPreference.getValue());
- HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>();
- additionalUpdateParam.put("userId", usrSortPr.getUserId());
- dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- return fieldsValidator;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public String getUserAppsSortTypePreference(EPUser user) {
- final Map<String, Long> params = new HashMap<>();
- List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>();
- try {
- params.put("userId", user.getId());
- userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null);
- if (userSortPrefs.size() > 0)
- return userSortPrefs.get(0).getSortPref();
- else
- return null;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e);
- }
- return null;
-
- }
-
- @Override
- public List<EPApp> getUserRemoteApps(String id) {
- throw new RuntimeException(" Cannot be called from parent class");
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.portalapp.portal.domain.AdminUserApp; +import org.openecomp.portalapp.portal.domain.AdminUserApplications; +import org.openecomp.portalapp.portal.domain.AppIdAndNameTransportModel; +import org.openecomp.portalapp.portal.domain.AppsResponse; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserAppsManualSortPreference; +import org.openecomp.portalapp.portal.domain.EPUserAppsSortPreference; +import org.openecomp.portalapp.portal.domain.EPWidgetsManualSortPreference; +import org.openecomp.portalapp.portal.domain.EcompApp; +import org.openecomp.portalapp.portal.domain.UserRole; +import org.openecomp.portalapp.portal.domain.UserRoles; +import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.transport.EPAppsManualPreference; +import org.openecomp.portalapp.portal.transport.EPAppsSortPreference; +import org.openecomp.portalapp.portal.transport.EPDeleteAppsManualSortPref; +import org.openecomp.portalapp.portal.transport.EPWidgetsSortPreference; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.LocalRole; +import org.openecomp.portalapp.portal.transport.OnboardingApp; +import org.openecomp.portalapp.portal.ueb.EPUebHelper; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.ueb.Helper; +import org.openecomp.portalsdk.core.onboarding.ueb.TopicManager; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; + +import com.att.nsa.apiClient.http.HttpException; +import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; +import com.att.nsa.cambria.client.CambriaClientBuilders; +import com.att.nsa.cambria.client.CambriaIdentityManager; +import com.att.nsa.cambria.client.CambriaTopicManager; +import com.google.common.primitives.Ints; + +public class EPAppCommonServiceImpl implements EPAppService { + + protected String ECOMP_APP_ID = "1"; + protected String SUPER_ADMIN_ROLE_ID = "1"; + protected String ACCOUNT_ADMIN_ROLE_ID = "999"; + protected String RESTRICTED_APP_ROLE_ID = "900"; + + private static final String urlField = "url"; + private static final String nameField = "name"; + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppCommonServiceImpl.class); + + @Autowired + private AdminRolesService adminRolesService; + @Autowired + private SessionFactory sessionFactory; + @Autowired + private DataAccessService dataAccessService; + @Autowired + private EPUebHelper epUebHelper; + + @PostConstruct + private void init() { + SUPER_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID); + ACCOUNT_ADMIN_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID); + ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID); + RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID); + } + + @Override + public List<EPApp> getUserAsAdminApps(EPUser user) { + if (adminRolesService.isAccountAdmin(user)) { + String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where " + + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND FN_APP.ENABLED = 'Y'"; + logQuery(sql); + try { + @SuppressWarnings("unchecked") + List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null); + return adminApps; + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + return null; + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "getUserAsAdminApps: only Account Admin may invoke this function!"); + return new ArrayList<EPApp>(); + } + } + + @Override + public List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId) { + String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID " + + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID " + + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND FN_APP.ENABLED = 'Y'"; + + String sql = String.format(format, orgUserId); + logQuery(sql); + + try { + @SuppressWarnings("unchecked") + List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null); + return adminApps; + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + return null; + } + } + + @Override + public List<EPApp> getAppsFullList() { + @SuppressWarnings("unchecked") + List<EPApp> apps = dataAccessService.getList(EPApp.class, null); + return apps; + } + + @Override + public List<EcompApp> getEcompAppAppsFullList() { + return transformAppsToEcompApps(getAppsFullList()); + } + + @Override + public List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList) { + List<EcompApp> ecompAppList = new ArrayList<EcompApp>(); + for (EPApp app : appsList) { + EcompApp ecompApp = new EcompApp(); + ecompApp.setId(app.getId()); + ecompApp.setName(app.getName()); + ecompApp.setImageUrl(app.getImageUrl()); + ecompApp.setDescription(app.getDescription()); + ecompApp.setNotes(app.getNotes()); + ecompApp.setUrl(app.getUrl()); + ecompApp.setAlternateUrl(app.getAlternateUrl()); + ecompApp.setUebTopicName(app.getUebTopicName()); + ecompApp.setUebKey(app.getUebKey()); + ecompApp.setUebSecret(app.getUebSecret()); + ecompApp.setEnabled(app.getEnabled()); + ecompApp.setRestrictedApp(app.isRestrictedApp()); + ecompAppList.add(ecompApp); + } + return ecompAppList; + } + + @Override + public EPApp getApp(Long appId) { + try { + @SuppressWarnings("unchecked") + List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id = " + appId, null, null); + return (apps.size() > 0) ? apps.get(0) : null; + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + return null; + } + } + + @SuppressWarnings("unchecked") + @Override + public List<AppIdAndNameTransportModel> getAdminApps(EPUser user) { + if (adminRolesService.isAccountAdmin(user)) { + String format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app inner join FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID " + + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)"; + String sql = String.format(format, user.getId()); + // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND + // app.APP_REST_ENDPOINT <> ''"; + logQuery(sql); + try { + return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e); + } + } + return new ArrayList<AppIdAndNameTransportModel>(); + } + + @Override + public EPApp getAppDetail(String appName) { + final Map<String, String> params = new HashMap<String, String>(); + try { + params.put("appName", appName); + @SuppressWarnings("unchecked") + List<EPApp> apps = (List<EPApp>) dataAccessService.executeNamedQuery("getMyloginAppDetails", params, null); + return (apps.size() > 0) ? apps.get(0) : null; + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + return null; + } + } + + @SuppressWarnings("unchecked") + @Override + public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user) { + if (adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user)) { + String format = ""; + String sql = ""; + if (adminRolesService.isSuperAdmin(user)) { + format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app " + + "where app.ENABLED = 'Y' AND app.app_type = 1"; + } else { + format = "SELECT app.APP_ID, app.APP_NAME, APP_TYPE FROM FN_APP app inner join FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID " + + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND app.ENABLED = 'Y' AND app.app_type = 1"; + } + sql = String.format(format, user.getId()); + // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND + // app.APP_REST_ENDPOINT <> ''"; + logQuery(sql); + try { + return dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while fetching the adminApps for user " + user.getLoginId(), e); + } + } + return new ArrayList<AppIdAndNameTransportModel>(); + } + + protected void logQuery(String sql) { + logger.debug(EELFLoggerDelegate.debugLogger, "logQuery: " + sql); + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + @SuppressWarnings("unchecked") + @Override + public List<AdminUserApplications> getAppsAdmins() { + try { + Map<String, String> params = new HashMap<>(); + params.put("accountAdminRoleId", ACCOUNT_ADMIN_ROLE_ID); + List<AdminUserApp> adminApps = (List<AdminUserApp>) dataAccessService.executeNamedQuery("getAppsAdmins", + params, null); + return aggregateRowsResultsByUserId(adminApps); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + return null; + } + } + + private List<AdminUserApplications> aggregateRowsResultsByUserId(List<AdminUserApp> adminApps) { + HashMap<Long, AdminUserApplications> adminUserApplications = new HashMap<Long, AdminUserApplications>(); + for (AdminUserApp app : adminApps) { + Long userId = app.getUser_Id(); + if (adminUserApplications.get(userId) == null) + adminUserApplications.put(userId, new AdminUserApplications(app)); + else + adminUserApplications.get(userId).addApp(app.getAppId(), app.getAppName()); + } + return new ArrayList<AdminUserApplications>(adminUserApplications.values()); + } + + @Override + public List<AppsResponse> getAllApps(Boolean all) { + // If all is true, return both active and inactive apps. Otherwise, just + // active apps. + @SuppressWarnings("unchecked") + // Sort the list by application name so the drop-down looks pretty. + List<EPApp> apps = all + ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null) + : (List<EPApp>) dataAccessService.getList(EPApp.class, + " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null); + + List<AppsResponse> appsModified = new ArrayList<AppsResponse>(); + for (EPApp app : apps) { + appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled())); + } + return appsModified; + } + + @Override + public UserRoles getUserProfile(String loginId) { + String format = "SELECT DISTINCT user.USER_ID, role.ROLE_ID, user.org_user_id, user.FIRST_NAME, user.LAST_NAME, role.ROLE_NAME FROM fn_user_role userrole " + + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + + "INNER JOIN fn_role role ON role.ROLE_ID = userrole.ROLE_ID " + + "WHERE user.org_user_id = \"%s\" and (userrole.app_id = 1 or role.role_id = " + ACCOUNT_ADMIN_ROLE_ID + + ") "; + String sql = String.format(format, loginId); + logQuery(sql); + @SuppressWarnings("unchecked") + List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserRole.class, null); + ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList); + if (usersRolesList == null || usersRolesList.size() < 1) + return null; + + return usersRolesList.get(0); + } + + @Override + public UserRoles getUserProfileNormalized(EPUser user) { + // Check database. + UserRoles userAndRoles = getUserProfile(user.getLoginId()); + // If no roles are defined, treat this user as a guest. + if (user.isGuest() || userAndRoles == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfile: treating user {} as guest", + user.getLoginId()); + UserRole userRole = new UserRole(); + userRole.setUser_Id(user.getId()); + userRole.setOrgUserId(user.getLoginId()); + userRole.setFirstName(user.getFirstName()); + userRole.setLastName(user.getLastName()); + userRole.setRoleId(-1L); + userRole.setRoleName("Guest"); + userRole.setUser_Id(-1L); + userAndRoles = new UserRoles(userRole); + } + + return userAndRoles; + } + + protected ArrayList<UserRoles> aggregateUserProfileRowsResultsByRole(List<UserRole> userRoleList) { + HashMap<String, UserRoles> userRoles = new HashMap<String, UserRoles>(); + for (UserRole user : userRoleList) { + String orgUserId = user.getOrgUserId(); + if (userRoles.get(orgUserId) == null) + userRoles.put(orgUserId, new UserRoles(user)); + else + userRoles.get(orgUserId).addRole(user.getRoleName()); + } + return new ArrayList<UserRoles>(userRoles.values()); + } + + private boolean isRestrictedApp(Long appId) { + EPApp app = getApp(appId); + return app.isRestrictedApp(); + } + + // For the functional menu edit + @Override + public List<LocalRole> getAppRoles(Long appId) { + String sql = ""; + if (isRestrictedApp(appId)) { + sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'"; + } else { + sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where APP_ID = '" + appId + "'"; + } + logQuery(sql); + @SuppressWarnings("unchecked") + List<LocalRole> appRoles = dataAccessService.executeSQLQuery(sql, LocalRole.class, null); + return appRoles; + } + + protected String userAppsQuery(EPUser user) { + StringBuilder query = new StringBuilder(); + if (adminRolesService.isSuperAdmin(user)) { + query.append("SELECT * FROM FN_APP where FN_APP.ENABLED = 'Y' ORDER BY APP_NAME"); + } else { + query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where "); + query.append( + "FN_USER_ROLE.USER_ID = " + user.getId() + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID); + query.append(" AND FN_APP.ENABLED = 'Y'"); + } + return query.toString(); + } + + protected FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) { + FieldsValidator fieldsValidator = new FieldsValidator(); + if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null + || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null + || onboardingApp.isOpen == null || onboardingApp.isEnabled == null + || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID)) + // For a normal app (appType==1), these fields must be filled + // in. + // For a restricted app (appType==2), they will be empty. + || ((!onboardingApp.restrictedApp) + && (onboardingApp.username == null || onboardingApp.username.length() == 0 + || onboardingApp.appPassword == null || onboardingApp.appPassword.length() == 0))) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + } + return fieldsValidator; + } + + @Override + public List<EPApp> getUserApps(EPUser user) { + List<EPApp> openApps = getOpenApps(); + + if (user.isGuest()) { + return openApps; + } else { + String sql = userAppsQuery(user); + logQuery(sql); + + // TreeSet<EPApp> distinctApps = new TreeSet<EPApp>(); + List<EPApp> appsList = new ArrayList<>(); + @SuppressWarnings("unchecked") + List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null); + HashSet<EPApp> appSet = new HashSet<>(); + for (EPApp app : adminApps) { + appSet.add(app); + appsList.add(app); + } + + for (EPApp app : openApps) { + if (!appSet.contains(app)) + appsList.add(app); + } + + return appsList; + } + } + + @Override + public List<EPApp> getPersAdminApps(EPUser user) { + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + // Named query is stored in EP.hbm.xml, mapped to EPApp + @SuppressWarnings("unchecked") + List<EPApp> list = dataAccessService.executeNamedQuery("getPersAdminApps", params, null); + return list; + } + + @Override + public List<EPApp> getPersUserApps(EPUser user) { + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + // Named query is stored in EP.hbm.xml, mapped to EPApp + @SuppressWarnings("unchecked") + List<EPApp> list = dataAccessService.executeNamedQuery("getPersUserApps", params, null); + return list; + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalapp.portal.service.EPAppService#getAppCatalog(com.att + * .fusionapp.ecomp.portal.domain.EPUser) + */ + @Override + public List<AppCatalogItem> getUserAppCatalog(EPUser user) { + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem + @SuppressWarnings("unchecked") + List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getUserAppCatalog", params, null); + return list; + } + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalapp.portal.service.EPAppService#getAdminAppCatalog( + * org.openecomp.portalapp.portal.domain.EPUser) + */ + @Override + public List<AppCatalogItem> getAdminAppCatalog(EPUser user) { + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem + @SuppressWarnings("unchecked") + List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getAdminAppCatalog", params, null); + return list; + } + + private List<EPApp> getOpenApps() { + @SuppressWarnings("unchecked") + List<EPApp> openApps = dataAccessService.getList(EPApp.class, " where open='Y' and enabled='Y'", null, null); + return openApps; + } + + @SuppressWarnings("unchecked") + @Override + public List<EPApp> getAppsOrderByName(EPUser user) { + final Map<String, Long> params = new HashMap<>(); + List<EPApp> sortedAppsByName = null; + try { + if (adminRolesService.isSuperAdmin(user)) { + params.put("userId", user.getId()); + sortedAppsByName = dataAccessService.executeNamedQuery("getPersAdminAppsOrderByName", params, null); + } else { + params.put("userId", user.getId()); + sortedAppsByName = dataAccessService.executeNamedQuery("getPersUserAppsOrderByName", params, null); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByName failed", e); + } + return sortedAppsByName; + } + + @SuppressWarnings("unchecked") + @Override + public List<EPApp> getAppsOrderByLastUsed(EPUser user) { + + final Map<String, Long> params = new HashMap<>(); + List<EPApp> sortedAppsByLastUsed = new ArrayList<EPApp>(); + List<EPApp> finalsortedAppsByLastUsed = new ArrayList<EPApp>(); + try { + if (adminRolesService.isSuperAdmin(user)) { + params.put("userId", user.getId()); + sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByLastUsed", params, null); + } else { + params.put("userId", user.getId()); + sortedAppsByLastUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByLastUsed", params, null); + } + Set<String> epAppSet = new HashSet<String>(); + for (EPApp eapp : sortedAppsByLastUsed) + if (!epAppSet.contains(eapp.getName())) { + finalsortedAppsByLastUsed.add(eapp); + epAppSet.add(eapp.getName()); + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByLastUsed failed", e); + } + return finalsortedAppsByLastUsed; + } + + @SuppressWarnings("unchecked") + @Override + public List<EPApp> getAppsOrderByMostUsed(EPUser user) { + final Map<String, Long> params = new HashMap<>(); + List<EPApp> sortedAppsByMostUsed = new ArrayList<EPApp>(); + List<EPApp> finalsortedAppsByMostUsed = new ArrayList<EPApp>(); + try { + if (adminRolesService.isSuperAdmin(user)) { + params.put("userId", user.getId()); + sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getAdminAppsOrderByMostUsed", params, null); + } else { + params.put("userId", user.getId()); + sortedAppsByMostUsed = dataAccessService.executeNamedQuery("getUserAppsOrderByMostUsed", params, null); + } + Set<String> epAppSet = new HashSet<String>(); + + for (EPApp eapp : sortedAppsByMostUsed) { + if (!epAppSet.contains(eapp.getName())) { + finalsortedAppsByMostUsed.add(eapp); + epAppSet.add(eapp.getName()); + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByMostUsed failed", e); + } + + return finalsortedAppsByMostUsed; + } + + /* + * This Method retrieves the User Apps by Sort Manual Preference + * + * @param: user--contains LoggedIn User Data + */ + @SuppressWarnings("unchecked") + @Override + public List<EPApp> getAppsOrderByManual(EPUser user) { + final Map<String, Long> params = new HashMap<>(); + List<EPApp> sortedAppsByManual = new ArrayList<EPApp>(); + List<EPApp> finalsortedAppsByManual = new ArrayList<EPApp>(); + try { + if (adminRolesService.isSuperAdmin(user)) { + params.put("userId", user.getId()); + sortedAppsByManual = dataAccessService.executeNamedQuery("getAdminAppsOrderByManual", params, null); + } else { + params.put("userId", user.getId()); + sortedAppsByManual = dataAccessService.executeNamedQuery("getUserAppsOrderByManual", params, null); + } + Set<String> epAppSet = new HashSet<String>(); + + for (EPApp eapp : sortedAppsByManual) { + if (!epAppSet.contains(eapp.getName())) { + finalsortedAppsByManual.add(eapp); + epAppSet.add(eapp.getName()); + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAppsOrderByManual failed", e); + } + return finalsortedAppsByManual; + } + + @Override + public List<OnboardingApp> getOnboardingApps() { + @SuppressWarnings("unchecked") + List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id!=" + ECOMP_APP_ID, null, null); + List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>(); + for (EPApp app : apps) { + OnboardingApp onboardingApp = new OnboardingApp(); + createOnboardingFromApp(app, onboardingApp); + onboardingAppsList.add(onboardingApp); + } + return onboardingAppsList; + } + + @Override + public List<OnboardingApp> getEnabledNonOpenOnboardingApps() { + @SuppressWarnings("unchecked") + List<EPApp> apps = dataAccessService.getList(EPApp.class, + " where enabled = true and open = false and id!=" + ECOMP_APP_ID, null, null); + List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>(); + for (EPApp app : apps) { + OnboardingApp onboardingApp = new OnboardingApp(); + createOnboardingFromApp(app, onboardingApp); + onboardingAppsList.add(onboardingApp); + } + return onboardingAppsList; + } + + @SuppressWarnings("unchecked") + private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) { + boolean duplicatedUrl = false; + boolean duplicatedName = false; + List<EPApp> apps; + if (onboardingApp.id == null) { + apps = dataAccessService.getList(EPApp.class, + " where url = '" + onboardingApp.url + "' or name = '" + onboardingApp.name + "'", null, null); + } else { + apps = dataAccessService.getList(EPApp.class, " where id = " + onboardingApp.id + " or url = '" + + onboardingApp.url + "' or name = '" + onboardingApp.name + "'", null, null); + } + for (EPApp app : apps) { + if (onboardingApp.id != null && onboardingApp.id.equals(app.getId())) { + continue; + } + if (!duplicatedUrl && app.getUrl().equalsIgnoreCase(onboardingApp.url)) { + duplicatedUrl = true; + if (duplicatedName) { + break; + } + } + if (!duplicatedName && app.getName().equalsIgnoreCase(onboardingApp.name)) { + duplicatedName = true; + if (duplicatedUrl) { + break; + } + } + } + if (duplicatedUrl || duplicatedName) { + if (duplicatedUrl) { + fieldsValidator.addProblematicFieldName(urlField); + } + if (duplicatedName) { + fieldsValidator.addProblematicFieldName(nameField); + } + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT); + fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR); + } + } + + @Override + public FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user) { + logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering modifyOnboardingApp"); + FieldsValidator fieldsValidator = onboardingAppFieldsChecker(modifiedOnboardingApp); + if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { + validateOnboardingApp(modifiedOnboardingApp, fieldsValidator); + } + if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { + if (modifiedOnboardingApp.id != null) { + updateApp(modifiedOnboardingApp.id, modifiedOnboardingApp, fieldsValidator, user); + } else { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + } + } + return fieldsValidator; + } + + @Override + public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) { + FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp); + if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { + validateOnboardingApp(newOnboardingApp, fieldsValidator); + } + if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { + if (newOnboardingApp.id == null) { + updateApp(null, newOnboardingApp, fieldsValidator, user); + } else { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + } + } + return fieldsValidator; + } + + @Override + public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) { + FieldsValidator fieldsValidator = new FieldsValidator(); + if (!adminRolesService.isSuperAdmin(user)) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN); + return fieldsValidator; + } + Boolean result = false; + Session localSession = null; + Transaction transaction = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + + // 1) Remove the URL for any functional menu item associated with + // this app + String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' " + + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'"; + logQuery(sql); + Query query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Remove any favorites associated with a menu item that is + // associated with this app + sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles " + + " where fn_menu_functional_roles.app_id='" + appid + "' " + + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Remove all role, appid records from fn_menu_functional_role + // that are associated with this app + sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Remove all records from fn_user_role associated with this app + sql = "delete from fn_user_role where app_id='" + appid + "'"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Remove any widgets associated with this app + sql = "delete from ep_widget_catalog_role where app_id='" + appid + "'"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Remove any roles associated with this app + sql = "delete from ep_role_notification " + " using ep_role_notification inner join fn_role " + + " where fn_role.app_id='" + appid + "' " + " and ep_role_notification.role_id= fn_role.role_id"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Remove all records from fn_role associated with this app + sql = "delete from fn_role where app_id='" + appid + "'"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Remove app contact us entries + sql = "delete from fn_app_contact_us where app_id='" + appid + "'"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Remove rows in the app personalization selection table + sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Remove rows in the app personalization sort table + sql = "delete from ep_pers_user_app_man_sort where app_id='" + appid + "'"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Remove rows in the app personalization sort table + sql = "delete from ep_user_roles_request where app_id='" + appid + "'"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Remove rows in the app personalization sort table + sql = "delete from ep_web_analytics_source where app_id='" + appid + "'"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete the app + sql = "delete from fn_app where app_id='" + appid + "'"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + transaction.commit(); + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteOnboardingApp failed", e); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError); + EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp"); + } + if (!result) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return fieldsValidator; + } + + private static Object syncRests = new Object(); + + // An app has been enabled/disabled. Must enable/disable all associated + // functional menu items. + private void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) { + String active_yn = enabled ? "Y" : "N"; + String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn " + + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id " + + " AND r.app_id = '" + appId + "' "; + logQuery(sql); + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null); + for (FunctionalMenuItem menuItem : menuItems) { + FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class, + menuItem.menuId); + myMenuItem.active_yn = active_yn; + localSession.save(myMenuItem); + } + } + + // Attention! If (appId == null) we use this function to create application + // otherwise we use it to modify existing application + private void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) { + logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp"); + // Separate out the code for a restricted app, since it doesn't need any + // of the UEB code. + if (onboardingApp.restrictedApp) { + boolean result = false; + Session localSession = null; + Transaction transaction = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + EPApp app; + if (appId == null) { + app = new EPApp(); + } else { + app = (EPApp) localSession.get(EPApp.class, appId); + if (app == null || app.getId() == null) { // App is already + // deleted! + transaction.commit(); + localSession.close(); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND); + return; + } + } + createAppFromOnboarding(app, onboardingApp, localSession); + localSession.saveOrUpdate(app); + // Enable or disable all menu items associated with this app + setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId); + transaction.commit(); + result = true; + } catch (Exception e) { + EcompPortalUtils.rollbackTransaction(transaction, + "updateApp rollback, exception = " + EcompPortalUtils.getStackTrace(e)); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "updateApp"); + } + if (!result) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + + } else { + synchronized (syncRests) { + boolean result = false; + Session localSession = null; + Transaction transaction = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + EPApp app; + if (appId == null) { + app = new EPApp(); + // ------------------------------------------------------------------------------------------- + // Register this App with the UEB communication server. + // Save + // the App's unique mailbox/topic + // name and keys to the FN_APP table. The App's mailbox + // and + // keys will be visible to the + // admin on the ECOMP portal. + // ------------------------------------------------------------------------------------------- + TopicManager topicManager = new TopicManager() { + + EPAppCommonServiceImpl service; + + public void init(EPAppCommonServiceImpl _service) { + service = _service; + } + + public void createTopic(String key, String secret, String topicName, + String topicDescription) throws HttpException, CambriaApiException, IOException { + + init(EPAppCommonServiceImpl.this); + final LinkedList<String> urlList = Helper.uebUrlList(); + if (logger.isInfoEnabled()) { + logger.info("==> createTopic"); + logger.info("topicName: " + topicName); + logger.info("topicDescription: " + topicDescription); + } + CambriaTopicManager tm = null; + try { + tm = service.getTopicManager(urlList, key, secret); + } catch (Exception e) { + logger.error("pub.build Exception ", e); + throw new CambriaApiException(topicName); + } + tm.createTopic(topicName, topicDescription, 1, 1); + } + + public void addPublisher(String topicOwnerKey, String topicOwnerSecret, String publisherKey, + String topicName) throws HttpException, CambriaApiException, IOException { + logger.info("==> addPublisher to topic " + topicName); + final LinkedList<String> urlList = Helper.uebUrlList(); + CambriaTopicManager tm = null; + try { + tm = service.getTopicManager(urlList, topicOwnerKey, topicOwnerSecret); + } catch (Exception e) { + logger.error("pub.build Exception ", e); + throw new CambriaApiException(topicName); + } + tm.allowProducer(topicName, publisherKey); + } + + }; + final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder() + .usingHosts(Helper.uebUrlList()).build(); + com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(), + "ECOMP Portal Owner"); + String appKey = credential.getApiKey(); + String appSecret = credential.getApiSecret(); + String appMailboxName = null; + + int maxNumAttemptsToCreateATopic = 3; + boolean successfullyCreatedMailbox = false; + for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) { + appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0); + + try { + topicManager.createTopic( + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), + appMailboxName, "ECOMP outbox for app" + onboardingApp.name); + successfullyCreatedMailbox = true; + logger.debug(EELFLoggerDelegate.debugLogger, + "Successfully created " + appMailboxName + " for App " + onboardingApp.name); + logger.debug(EELFLoggerDelegate.debugLogger, " Key = " + appKey + " Secret = " + + appSecret + " generated using = " + user.getEmail()); + break; + } catch (HttpException e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e); + if (e.getStatusCode() == 409) { + logger.error(EELFLoggerDelegate.errorLogger, "Topic/mailbox " + appMailboxName + + " already exists. Will try using a different name", e); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "HttpException when onboarding App: ", + e); + } + } + } + + if (successfullyCreatedMailbox) { + onboardingApp.setUebTopicName(appMailboxName); + onboardingApp.setUebKey(appKey); + onboardingApp.setUebSecret(appSecret); + + try { + /* + * EP is a publisher to this App's new mailbox + */ + topicManager.addPublisher( + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), + appMailboxName); + + /* + * This App is a subscriber of its own mailbox + */ + topicManager.addSubscriber( + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey, + appMailboxName); + + /* + * This App is a publisher to EP + */ + topicManager.addPublisher( + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey, + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME)); + } catch (HttpException | CambriaApiException | IOException e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e); + logger.error(EELFLoggerDelegate.errorLogger, + "Error when configuring Publisher/Subscriber for App's new mailbox", e); + transaction.commit(); + localSession.close(); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT); + return; + } + } else { + transaction.commit(); + localSession.close(); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT); + return; + } + } else { + app = (EPApp) localSession.get(EPApp.class, appId); + if (app == null || app.getId() == null) { + // App is already deleted! + transaction.commit(); + localSession.close(); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND); + return; + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "LR: about to call createAppFromOnboarding"); + createAppFromOnboarding(app, onboardingApp, localSession); + logger.debug(EELFLoggerDelegate.debugLogger, + "LR: updateApp: finished calling createAppFromOnboarding"); + localSession.saveOrUpdate(app); + logger.debug(EELFLoggerDelegate.debugLogger, + "LR: updateApp: finished calling localSession.saveOrUpdate"); + // Enable or disable all menu items associated with this app + setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId); + logger.debug(EELFLoggerDelegate.debugLogger, + "LR: updateApp: finished calling setFunctionalMenuItemsEnabled"); + transaction.commit(); + logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit"); + epUebHelper.addPublisher(app); + logger.debug(EELFLoggerDelegate.debugLogger, + "LR: updateApp: finished calling epUebHelper.addPublisher"); + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "updateApp failed", e); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + EcompPortalUtils.rollbackTransaction(transaction, + "updateApp rollback, exception = " + EcompPortalUtils.getStackTrace(e)); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "updateApp"); + } + if (!result) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + } + } + + public CambriaTopicManager getTopicManager(LinkedList<String> urlList, String key, String secret) + throws GeneralSecurityException, Exception { + throw new Exception("This method can only be invoked from child class"); + } + + /** + * Populates a transport model of the application from a database row model. + * Leaves out the thumbnail because the FE fetches images via a different + * API. + * + * @param app + * Model of database row + * @param onboardingApp + * Model for transport as JSON + */ + @Override + public void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) { + onboardingApp.id = app.getId(); + onboardingApp.name = app.getName(); + onboardingApp.imageUrl = app.getImageUrl(); + onboardingApp.description = app.getDescription(); + onboardingApp.notes = app.getNotes(); + onboardingApp.url = app.getUrl(); + onboardingApp.alternateUrl = app.getAlternateUrl(); + onboardingApp.restUrl = app.getAppRestEndpoint(); + onboardingApp.isOpen = app.getOpen(); + onboardingApp.isEnabled = app.getEnabled(); + onboardingApp.username = app.getUsername(); + onboardingApp.appPassword = decryptedPassword(app.getAppPassword(), app); + onboardingApp.uebTopicName = app.getUebTopicName(); + onboardingApp.uebKey = app.getUebKey(); + onboardingApp.uebSecret = app.getUebSecret(); + onboardingApp.setRestrictedApp(app.isRestrictedApp()); + // if (app.getThumbnail() != null) + // onboardingApp.thumbnail = new + // String(Base64.getEncoder().encode(app.getThumbnail())); + } + + /** + * Creates a database object for an application from an uploaded transport + * model. Must decode the thumbnail, if any. + * + * @param app + * @param onboardingApp + * @param localSession + * @return The first argument. + */ + protected EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) { + app.setName(onboardingApp.name); + app.setDescription(onboardingApp.description); + app.setNotes(onboardingApp.notes); + app.setUrl(onboardingApp.url); + app.setAlternateUrl(onboardingApp.alternateUrl); + app.setAppRestEndpoint(onboardingApp.restUrl); + app.setOpen(onboardingApp.isOpen); + app.setEnabled(onboardingApp.isEnabled); + app.setUsername(onboardingApp.username); + app.setAppPassword(this.encryptedPassword(onboardingApp.appPassword, app)); + app.setUebTopicName(onboardingApp.uebTopicName); + app.setUebKey(onboardingApp.uebKey); + app.setUebSecret(onboardingApp.uebSecret); + app.setRestrictedApp(onboardingApp.restrictedApp); + if (!StringUtils.isEmpty(onboardingApp.thumbnail)) { + logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: onboarding thumbnail is NOT empty"); + String[] splitBase64Thumbnail = onboardingApp.thumbnail.split("base64,"); + logger.debug(EELFLoggerDelegate.debugLogger, + "createAppFromOnboarding: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length); + if (splitBase64Thumbnail.length > 1) { + // This occurs when we have a new image, not an existing image + byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes()); + logger.debug(EELFLoggerDelegate.debugLogger, "createAppFromOnboarding: finished calling decode"); + // This is basically a boolean indicator that an image is + // present. + app.setImageUrl(constructImageName(onboardingApp)); + app.setThumbnail(decodedImage); + } + } else if (app.getThumbnail() != null && onboardingApp.imageLink == null) { + // The thumbnail that came in from the json is empty; the previous + // thumbnail is NOT empty. Must delete it. + logger.debug(EELFLoggerDelegate.debugLogger, + "createAppFromOnboarding: onboarding thumbnail is empty; db thumbnail is NOT null"); + app.setImageUrl(null); + app.setThumbnail(null); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, + "createAppFromOnboarding: making no changes to thumbnail as imageLink is not null"); + } + return app; + } + + protected String constructImageName(OnboardingApp onboardingApp) { + return "portal_" + String.valueOf(onboardingApp.url.hashCode() + "_" + (int) (Math.random() * 100000.0)) + + ".png"; + } + + // Don't encrypt or decrypt the password if it is null or the empty string + private String decryptedPassword(String encryptedAppPwd, EPApp app) { + String result = ""; + if (encryptedAppPwd != null & encryptedAppPwd.length() > 0) { + try { + result = CipherUtil.decrypt(encryptedAppPwd, + SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed for app " + app.getName(), e); + } + } + return result; + } + + protected String encryptedPassword(String decryptedAppPwd, EPApp app) { + String result = ""; + if (decryptedAppPwd != null & decryptedAppPwd.length() > 0) { + try { + result = CipherUtil.encrypt(decryptedAppPwd, + SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed for app " + app.getName(), e); + } + } + return result; + } + + @SuppressWarnings("unchecked") + @Override + public FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user) { + FieldsValidator fieldsValidator = new FieldsValidator(); + final Map<String, Long> params = new HashMap<>(); + List<EPWidgetsManualSortPreference> epManualWidgets = new ArrayList<EPWidgetsManualSortPreference>(); + + try { + params.put("userId", user.getId()); + epManualWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null); + Map<Long, EPWidgetsManualSortPreference> existingWidgetsIds = new HashMap<Long, EPWidgetsManualSortPreference>(); + for (EPWidgetsManualSortPreference userWidgetManualPref : epManualWidgets) { + existingWidgetsIds.put(userWidgetManualPref.getWidgetId(), userWidgetManualPref); + } + for (EPWidgetsSortPreference epWidgetsManPref : widgetsSortManual) { + if (epWidgetsManPref.getWidgetid() != null) { + Long widgetid = epWidgetsManPref.getWidgetid(); + if (existingWidgetsIds.containsKey(widgetid)) { + EPWidgetsManualSortPreference epWidgetsManualSort = existingWidgetsIds.get(widgetid); + epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow()); + epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol()); + epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX()); + epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY()); + HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>(); + additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId()); + dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam); + } else { + EPWidgetsManualSortPreference epWidgetsManualSort = new EPWidgetsManualSortPreference(); + epWidgetsManualSort.setWidgetId(epWidgetsManPref.getWidgetid()); + epWidgetsManualSort.setWidgetRow(epWidgetsManPref.getRow()); + epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol()); + epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX()); + epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY()); + epWidgetsManualSort.setUserId(Ints.checkedCast(user.getId())); + dataAccessService.saveDomainObject(epWidgetsManualSort, null); + } + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK); + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetsSortManual failed", e); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return fieldsValidator; + } + + @SuppressWarnings("unchecked") + @Override + public FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user) { + FieldsValidator fieldsValidator = new FieldsValidator(); + final Map<String, Long> params = new HashMap<>(); + List<EPWidgetsManualSortPreference> epWidgets = new ArrayList<EPWidgetsManualSortPreference>(); + try { + params.put("userId", user.getId()); + epWidgets = dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null); + Map<Long, EPWidgetsManualSortPreference> existingWidgetIds = new HashMap<Long, EPWidgetsManualSortPreference>(); + for (EPWidgetsManualSortPreference userWidgetSortPref : epWidgets) { + existingWidgetIds.put(userWidgetSortPref.getWidgetId(), userWidgetSortPref); + } + for (EPWidgetsSortPreference delEpWidgetsManPref : delWidgetSortPref) { + if (delEpWidgetsManPref.getWidgetid() != null) { + Long widgetId = delEpWidgetsManPref.getWidgetid(); + if (existingWidgetIds.containsKey(widgetId)) { + dataAccessService.deleteDomainObjects(EPWidgetsManualSortPreference.class, + "widget_id=" + widgetId + " AND user_id=" + user.getId(), null); + } + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK); + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteUserWidgetSortPref failed", e); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return fieldsValidator; + } + + /* + * This Method Stores the Sort Order of User Apps by Sort Manual Preference + * + * @param: appsSortManual--contains User Apps Data + * + * @param: user--contains LoggedIn User Data + */ + @SuppressWarnings("unchecked") + @Override + public FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user) { + FieldsValidator fieldsValidator = new FieldsValidator(); + final Map<String, Long> params = new HashMap<>(); + List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>(); + + try { + params.put("userId", user.getId()); + epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null); + Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>(); + for (EPUserAppsManualSortPreference userAppManualPref : epManualApps) { + existingAppIds.put(userAppManualPref.getAppId(), userAppManualPref); + } + for (EPAppsManualPreference epAppsManPref : appsSortManual) { + if (epAppsManPref.getAppid() != null) { + Long appid = epAppsManPref.getAppid(); + if (existingAppIds.containsKey(appid)) { + EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid); + epAppsManualSort + .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1); + HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>(); + additionalUpdateParam.put("userId", epAppsManualSort.getUserId()); + dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam); + } else { + EPUserAppsManualSortPreference epAppsManualSort = new EPUserAppsManualSortPreference(); + epAppsManualSort.setAppId(epAppsManPref.getAppid()); + epAppsManualSort + .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1); + epAppsManualSort.setUserId(Ints.checkedCast(user.getId())); + dataAccessService.saveDomainObject(epAppsManualSort, null); + } + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK); + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortManual failed", e); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return fieldsValidator; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.EPAppService# + * deleteUserAppSortManual(java.lang.String, + * org.openecomp.portalapp.portal.domain.EPUser) + */ + @SuppressWarnings("unchecked") + @Override + public FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user) { + FieldsValidator fieldsValidator = new FieldsValidator(); + final Map<String, Long> params = new HashMap<>(); + List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>(); + try { + params.put("userId", user.getId()); + epManualApps = dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null); + Map<Long, EPUserAppsManualSortPreference> existingAppIds = new HashMap<Long, EPUserAppsManualSortPreference>(); + for (EPUserAppsManualSortPreference userAppPref : epManualApps) { + existingAppIds.put(userAppPref.getAppId(), userAppPref); + } + if (existingAppIds.containsKey(delAppSortManual.getAppId()) && !delAppSortManual.isSelect()) { + dataAccessService.deleteDomainObjects(EPUserAppsManualSortPreference.class, + "app_id=" + delAppSortManual.getAppId() + " AND user_id=" + user.getId(), null); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteUserAppSortManual failed", e); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return fieldsValidator; + } + + @SuppressWarnings("unchecked") + @Override + public FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user) { + FieldsValidator fieldsValidator = new FieldsValidator(); + final Map<String, Long> params = new HashMap<>(); + List<EPUserAppsSortPreference> epSortTypes = new ArrayList<EPUserAppsSortPreference>(); + EPUserAppsSortPreference usrSortPr = null; + try { + params.put("userId", user.getId()); + epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null); + if (epSortTypes.size() == 0) { + usrSortPr = new EPUserAppsSortPreference(); + usrSortPr.setUserId(Ints.checkedCast(user.getId())); + usrSortPr.setSortPref(appsSortPreference.getValue()); + dataAccessService.saveDomainObject(usrSortPr, null); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK); + } else { + usrSortPr = epSortTypes.get(0); + usrSortPr.setSortPref(appsSortPreference.getValue()); + HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>(); + additionalUpdateParam.put("userId", usrSortPr.getUserId()); + dataAccessService.saveDomainObject(usrSortPr, additionalUpdateParam); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveAppsSortPreference failed", e); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return fieldsValidator; + } + + @SuppressWarnings("unchecked") + @Override + public String getUserAppsSortTypePreference(EPUser user) { + final Map<String, Long> params = new HashMap<>(); + List<EPUserAppsSortPreference> userSortPrefs = new ArrayList<EPUserAppsSortPreference>(); + try { + params.put("userId", user.getId()); + userSortPrefs = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null); + if (userSortPrefs.size() > 0) + return userSortPrefs.get(0).getSortPref(); + else + return null; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getUserAppsSortTypePreference failed", e); + } + return null; + + } + + @Override + public List<EPApp> getUserRemoteApps(String id) { + throw new RuntimeException(" Cannot be called from parent class"); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java index c7bf680d..1e12dd52 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java @@ -1,213 +1,213 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalapp.portal.domain.AdminUserApplications;
-import org.openecomp.portalapp.portal.domain.AppIdAndNameTransportModel;
-import org.openecomp.portalapp.portal.domain.AppsResponse;
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EcompApp;
-import org.openecomp.portalapp.portal.domain.UserRoles;
-import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem;
-import org.openecomp.portalapp.portal.transport.EPAppsManualPreference;
-import org.openecomp.portalapp.portal.transport.EPAppsSortPreference;
-import org.openecomp.portalapp.portal.transport.EPDeleteAppsManualSortPref;
-import org.openecomp.portalapp.portal.transport.EPWidgetsSortPreference;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.LocalRole;
-import org.openecomp.portalapp.portal.transport.OnboardingApp;
-
-public interface EPAppService {
-
- /**
- * Get all applications adminId is an admin
- *
- * @param adminId
- * - the admin
- * @return the admin's applications
- */
- List<EPApp> getUserAsAdminApps(EPUser user);
-
- List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId);
-
- /**
- * Gets all rows and all fields from the fn_app table.
- *
- * @return list of EPApp objects
- */
- List<EPApp> getAppsFullList();
-
- /**
- * Gets all rows and most fields from the fn_app table.
- *
- * @return list of EcompApp objects.
- */
- List<EcompApp> getEcompAppAppsFullList();
-
- /**
- * Get apps with app app admins
- *
- * @return List of AdminUserApplications
- */
- List<AdminUserApplications> getAppsAdmins();
-
- /**
- * Get all apps from fn_app table (index, name, title only).
- *
- * @param all
- * If all is true, returns active and inactive apps; otherwise,
- * just active apps.
- * @return List of AppsResponse objects.
- */
- List<AppsResponse> getAllApps(Boolean all);
-
- UserRoles getUserProfile(String loginId);
-
- UserRoles getUserProfileNormalized(EPUser user);
-
- List<LocalRole> getAppRoles(Long appId);
-
- List<AppIdAndNameTransportModel> getAdminApps(EPUser user);
-
- List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user);
-
- /**
- * Gets the applications accessible to the specified user, which includes
- * all enabled open applications, plus all enabled applications for which
- * the user has a defined role for that app.
- *
- * @param user
- * EPUser object with the user's ATT UID
- * @return the user's list of applications, which may be empty.
- */
- List<EPApp> getUserApps(EPUser user);
-
- /**
- * Gets the user-personalized list of applications for the Portal (super)
- * admin, which includes enabled open applications, enabled applications for
- * which the user has a defined role for that app, and/or enabled
- * applications which the user has chosen to show.
- *
- * @param user
- * EPUser object with the user's ATT UID
- * @return the user's personalized list of applications, which may be empty.
- */
- List<EPApp> getPersAdminApps(EPUser user);
-
- /**
- * Gets the user-personalized list of accessible applications, which
- * includes enabled open applications and/or enabled applications for which
- * the user has a defined role for that app. Personalization means the user
- * can indicate an accessible application should be excluded from this
- * result.
- *
- * @param user
- * EPUser object with the user's ATT UID
- * @return the user's personalized list of applications, which may be empty.
- */
- List<EPApp> getPersUserApps(EPUser user);
-
- /**
- * Gets the application catalog for the specified user who is a super admin.
- * This includes all enabled applications. Each item indicates whether the
- * user has access (open or via a role), and whether the application is
- * selected for showing in the user's home (applications) page. Admin sees
- * slightly different behavior - can force an app onto the home page using
- * the personalization feature (user-app-selection table).
- *
- * @param user
- * @return list of all enabled applications, which may be empty
- */
- List<AppCatalogItem> getAdminAppCatalog(EPUser user);
-
- /**
- * Gets the application catalog for the specified user, who is a regular
- * user. This includes all enabled applications. Each item indicates whether
- * the user has access (open or via a role), and whether the application is
- * selected for showing in the user's home (applications) page.
- *
- * @param user
- * @return list of all enabled applications, which may be empty
- */
- List<AppCatalogItem> getUserAppCatalog(EPUser user);
-
- List<OnboardingApp> getOnboardingApps();
-
- List<OnboardingApp> getEnabledNonOpenOnboardingApps();
-
- FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user);
-
- FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user);
-
- /**
- * Deletes the specified application from all tables where the app_id is
- * used, and ultimately from the fn_app table.
- *
- * @param user
- * Must be Portal (super) administrator
- * @param onboardingAppId
- * ID of application to be deleted
- * @return Status code
- */
- FieldsValidator deleteOnboardingApp(EPUser user, Long onboardingAppId);
-
- List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList);
-
- EPApp getApp(Long appId);
-
- EPApp getAppDetail(String appName);
-
- List<EPApp> getAppsOrderByName(EPUser user);
-
- FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user);
-
- FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user);
-
- FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user);
-
- /**
- * Deletes the sort order of user apps by sort manual preference
- *
- * @param delAppSortManual
- * User Apps Data
- * @param user
- * LoggedIn User Data
- * @return FieldsValidator
- */
- FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user);
-
- FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user);
-
- String getUserAppsSortTypePreference(EPUser user);
-
- List<EPApp> getAppsOrderByLastUsed(EPUser user);
-
- List<EPApp> getAppsOrderByMostUsed(EPUser user);
-
- List<EPApp> getAppsOrderByManual(EPUser user);
-
- List<EPApp> getUserRemoteApps(String id);
-
- void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp);
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.AdminUserApplications; +import org.openecomp.portalapp.portal.domain.AppIdAndNameTransportModel; +import org.openecomp.portalapp.portal.domain.AppsResponse; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EcompApp; +import org.openecomp.portalapp.portal.domain.UserRoles; +import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem; +import org.openecomp.portalapp.portal.transport.EPAppsManualPreference; +import org.openecomp.portalapp.portal.transport.EPAppsSortPreference; +import org.openecomp.portalapp.portal.transport.EPDeleteAppsManualSortPref; +import org.openecomp.portalapp.portal.transport.EPWidgetsSortPreference; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.LocalRole; +import org.openecomp.portalapp.portal.transport.OnboardingApp; + +public interface EPAppService { + + /** + * Get all applications adminId is an admin + * + * @param user + * the admin user + * @return the admin's applications + */ + List<EPApp> getUserAsAdminApps(EPUser user); + + List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId); + + /** + * Gets all rows and all fields from the fn_app table. + * + * @return list of EPApp objects + */ + List<EPApp> getAppsFullList(); + + /** + * Gets all rows and most fields from the fn_app table. + * + * @return list of EcompApp objects. + */ + List<EcompApp> getEcompAppAppsFullList(); + + /** + * Get apps with app app admins + * + * @return List of AdminUserApplications + */ + List<AdminUserApplications> getAppsAdmins(); + + /** + * Get all apps from fn_app table (index, name, title only). + * + * @param all + * If all is true, returns active and inactive apps; otherwise, + * just active apps. + * @return List of AppsResponse objects. + */ + List<AppsResponse> getAllApps(Boolean all); + + UserRoles getUserProfile(String loginId); + + UserRoles getUserProfileNormalized(EPUser user); + + List<LocalRole> getAppRoles(Long appId); + + List<AppIdAndNameTransportModel> getAdminApps(EPUser user); + + List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user); + + /** + * Gets the applications accessible to the specified user, which includes + * all enabled open applications, plus all enabled applications for which + * the user has a defined role for that app. + * + * @param user + * EPUser object with the user's ATT UID + * @return the user's list of applications, which may be empty. + */ + List<EPApp> getUserApps(EPUser user); + + /** + * Gets the user-personalized list of applications for the Portal (super) + * admin, which includes enabled open applications, enabled applications for + * which the user has a defined role for that app, and/or enabled + * applications which the user has chosen to show. + * + * @param user + * EPUser object with the user's ATT UID + * @return the user's personalized list of applications, which may be empty. + */ + List<EPApp> getPersAdminApps(EPUser user); + + /** + * Gets the user-personalized list of accessible applications, which + * includes enabled open applications and/or enabled applications for which + * the user has a defined role for that app. Personalization means the user + * can indicate an accessible application should be excluded from this + * result. + * + * @param user + * EPUser object with the user's ATT UID + * @return the user's personalized list of applications, which may be empty. + */ + List<EPApp> getPersUserApps(EPUser user); + + /** + * Gets the application catalog for the specified user who is a super admin. + * This includes all enabled applications. Each item indicates whether the + * user has access (open or via a role), and whether the application is + * selected for showing in the user's home (applications) page. Admin sees + * slightly different behavior - can force an app onto the home page using + * the personalization feature (user-app-selection table). + * + * @param user + * @return list of all enabled applications, which may be empty + */ + List<AppCatalogItem> getAdminAppCatalog(EPUser user); + + /** + * Gets the application catalog for the specified user, who is a regular + * user. This includes all enabled applications. Each item indicates whether + * the user has access (open or via a role), and whether the application is + * selected for showing in the user's home (applications) page. + * + * @param user + * @return list of all enabled applications, which may be empty + */ + List<AppCatalogItem> getUserAppCatalog(EPUser user); + + List<OnboardingApp> getOnboardingApps(); + + List<OnboardingApp> getEnabledNonOpenOnboardingApps(); + + FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user); + + FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user); + + /** + * Deletes the specified application from all tables where the app_id is + * used, and ultimately from the fn_app table. + * + * @param user + * Must be Portal (super) administrator + * @param onboardingAppId + * ID of application to be deleted + * @return Status code + */ + FieldsValidator deleteOnboardingApp(EPUser user, Long onboardingAppId); + + List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList); + + EPApp getApp(Long appId); + + EPApp getAppDetail(String appName); + + List<EPApp> getAppsOrderByName(EPUser user); + + FieldsValidator saveAppsSortPreference(EPAppsSortPreference appsSortPreference, EPUser user); + + FieldsValidator saveAppsSortManual(List<EPAppsManualPreference> appsSortManual, EPUser user); + + FieldsValidator saveWidgetsSortManual(List<EPWidgetsSortPreference> widgetsSortManual, EPUser user); + + /** + * Deletes the sort order of user apps by sort manual preference + * + * @param delAppSortManual + * User Apps Data + * @param user + * LoggedIn User Data + * @return FieldsValidator + */ + FieldsValidator deleteUserAppSortManual(EPDeleteAppsManualSortPref delAppSortManual, EPUser user); + + FieldsValidator deleteUserWidgetSortPref(List<EPWidgetsSortPreference> delWidgetSortPref, EPUser user); + + String getUserAppsSortTypePreference(EPUser user); + + List<EPApp> getAppsOrderByLastUsed(EPUser user); + + List<EPApp> getAppsOrderByMostUsed(EPUser user); + + List<EPApp> getAppsOrderByManual(EPUser user); + + List<EPApp> getUserRemoteApps(String id); + + void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAuditService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAuditService.java index a35a8ba2..ef436475 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAuditService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAuditService.java @@ -1,27 +1,27 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.Date;
-
-public interface EPAuditService {
- public Date getGuestLastLogin(String userId);
- public void delAuditLogFromDay();
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.Date; + +public interface EPAuditService { + public Date getGuestLastLogin(String userId); + public void delAuditLogFromDay(); +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAuditServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAuditServiceImpl.java index 1a343866..a7b71612 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAuditServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAuditServiceImpl.java @@ -1,96 +1,112 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.time.LocalDate;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-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 org.openecomp.portalsdk.core.domain.AuditLog;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-
-@Service("epAuditService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class EPAuditServiceImpl implements EPAuditService {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAuditServiceImpl.class);
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @Override
- /* get the guest last login time with orgUserId as param.
- * If record not found in table, return null.
- *
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.EPUserService#getGuestLastLogin(java.lang.String)
- */
- public Date getGuestLastLogin(String userId) {
- Map<String, String> params = new HashMap<>();
- params.put("userId", userId);
- List<Date> list = getDataAccessService().executeNamedQuery("getGuestLastLogin", params, null);
- Date date=null;
- if(list!=null){
- if(list.size()==1) /* if list only contains one item, meaning this is the first time user logs in or record not found in db*/
- date = list.get(0); /*the guest's current log in time*/
- else if(list.size()==2)
- date = list.get(1); /*most recent login date from db*/
- }
- return date;
- }
-
- @Override
- /* Clean all the records in fn_audit_log table that are less than defined date in system.property
- *
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.EPAuditService#delAuditLogFromDay()
- */
- public void delAuditLogFromDay(){
- if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.AUDITLOG_DEL_DAY_FROM)) {
- String day = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.AUDITLOG_DEL_DAY_FROM);
- LocalDate removeDateFrom = LocalDate.now().minusDays(Integer.valueOf(day));
- getDataAccessService().deleteDomainObjects(AuditLog.class, "audit_date <'"+removeDateFrom+"'",null);
- }else{
- logger.error(EELFLoggerDelegate.errorLogger, "delAuditLogFromDay Exception = system.propertiy value is empty on" + EPCommonSystemProperties.AUDITLOG_DEL_DAY_FROM);
- }
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.time.LocalDate; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +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 org.openecomp.portalsdk.core.domain.AuditLog; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; + +@Service("epAuditService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class EPAuditServiceImpl implements EPAuditService { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAuditServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + @Override + /* + * get the guest last login time with orgUserId as param. If record not + * found in table, return null. + * + * (non-Javadoc) + * + * @see + * org.openecomp.portalapp.portal.service.EPUserService#getGuestLastLogin( + * java.lang.String) + */ + public Date getGuestLastLogin(String userId) { + Map<String, String> params = new HashMap<>(); + params.put("userId", userId); + @SuppressWarnings("unchecked") + List<Date> list = getDataAccessService().executeNamedQuery("getGuestLastLogin", params, null); + Date date = null; + if (list != null) { + /* + * if list only contains one item, meaning this is the first time + * user logs in or record not found in db + */ + if (list.size() == 1) + date = list.get(0); /* the guest's current log in time */ + else if (list.size() == 2) + date = list.get(1); /* most recent login date from db */ + } + return date; + } + + /* + * Cleans all the records in fn_audit_log table that are less than defined + * date in system.property + * + * (non-Javadoc) + * + * @see + * org.openecomp.portalapp.portal.service.EPAuditService#delAuditLogFromDay( + * ) + */ + @Override + public void delAuditLogFromDay() { + if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.AUDITLOG_DEL_DAY_FROM)) { + String day = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.AUDITLOG_DEL_DAY_FROM); + LocalDate removeDateFrom = LocalDate.now().minusDays(Integer.valueOf(day)); + getDataAccessService().deleteDomainObjects(AuditLog.class, "audit_date <'" + removeDateFrom + "'", null); + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "delAuditLogFromDay Exception = system.propertiy value is empty on" + + EPCommonSystemProperties.AUDITLOG_DEL_DAY_FROM); + } + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLdapService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLdapService.java index c77684fa..4bdecc92 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLdapService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLdapService.java @@ -1,31 +1,31 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import org.openecomp.portalsdk.core.command.support.SearchResult;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-
-public interface EPLdapService {
-
- // search POST for users based on the criteria selected in the Request
- SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, int pageNo, int dataSize, int userId) throws Exception;
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import org.openecomp.portalsdk.core.command.support.SearchResult; +import org.openecomp.portalsdk.core.domain.support.DomainVo; + + +public interface EPLdapService { + + // search POST for users based on the criteria selected in the Request + SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, int pageNo, int dataSize, int userId) throws Exception; + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLdapServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLdapServiceImpl.java index dfcc0c7f..664ee1ae 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLdapServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLdapServiceImpl.java @@ -1,288 +1,288 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-import javax.naming.directory.Attribute;
-import javax.naming.directory.Attributes;
-import javax.naming.directory.DirContext;
-import javax.naming.directory.SearchControls;
-
-import org.slf4j.MDC;
-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 org.openecomp.portalsdk.core.command.support.SearchResult;
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.support.FusionService;
-import org.openecomp.portalsdk.core.service.support.ServiceLocator;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-
-@Service("epLdapService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-public class EPLdapServiceImpl extends FusionService implements EPLdapService {
- @Autowired
- private ServiceLocator serviceLocator;
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPLdapServiceImpl.class);
-
- @EPAuditLog
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3,
- int pageNo, int dataSize, int userId) throws Exception {
-
- String remoteHost = "";
-
- // initialize the directory context to access POST
- DirContext dirContext = serviceLocator.getDirContext(SystemProperties.getProperty(SystemProperties.POST_INITIAL_CONTEXT_FACTORY),
- SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL),
- SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL));
-
- SearchResult searchResult = new SearchResult();
-
- try {
-
- remoteHost = String.format("%s/%s", SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL),
- SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL));
- MDC.put(EPCommonSystemProperties.FULL_URL, remoteHost);
-
- String[] postAttributes = {"nickname","givenName","initials","sn","employeeNumber","mail","telephoneNumber",
- "departmentNumber","a1","street","roomNumber","l","st","postalCode","zip4","physicalDeliveryOfficeName","bc",
- "friendlyCountryName","bd","bdname","bu","buname","jtname","mgrid","a2","compcode","compdesc",
- "costcenter","silo","b2"};
-
- SearchControls searchControls = new SearchControls();
- searchControls.setTimeLimit(5000);
- searchControls.setReturningAttributes(postAttributes);
-
- StringBuffer filterClause = new StringBuffer("(&(objectClass=*)");
-
- EPUser user = (EPUser)searchCriteria;
-
- if(Utilities.nvl(user.getFirstName()).length() > 0) {
- filterClause.append("(givenName=").append(user.getFirstName()).append("*)");
- }
- if(Utilities.nvl(user.getLastName()).length() > 0) {
- filterClause.append("(sn=").append(user.getLastName()).append("*)");
- }
- if(Utilities.nvl(user.getHrid()).length() > 0) {
- filterClause.append("(employeeNumber=").append(user.getHrid()).append("*)");
- }
- if(Utilities.nvl(user.getOrgManagerUserId()).length() > 0) {
- filterClause.append("(mgrid=").append(user.getOrgManagerUserId()).append("*)");
- }
- if(Utilities.nvl(user.getOrgCode()).length() > 0) {
- filterClause.append("(departmentNumber=").append(user.getOrgCode()).append("*)");
- }
- if(Utilities.nvl(user.getEmail()).length() > 0) {
- filterClause.append("(mail=").append(user.getEmail()).append("*)");
- }
- if(Utilities.nvl(user.getOrgUserId()).length() > 0) {
- filterClause.append("(a1=").append(user.getOrgUserId()).append("*)");
- }
- filterClause.append("(c3=N)"); // this has been added to filter CP09 entries on the LDAP server that are duplicates of existing individuals
- filterClause.append(")");
-
- List list = new ArrayList();
- if (!filterClause.toString().equals("(&(objectClass=*))")) {
- NamingEnumeration e = dirContext.search(SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL) + "/" +
- SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL),
- filterClause.toString(),
- searchControls);
- list = processResults(e);
- }
-
- Collections.sort(list);
-
- searchResult = new SearchResult(list);
- searchResult.setPageNo(pageNo);
- if(dataSize >= 0) {
- searchResult.setDataSize(dataSize);
- }
- else {
- searchResult.setDataSize(list.size());
- }
- } catch(NamingException ne) {
- String stackTrace = EcompPortalUtils.getStackTrace(ne);
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the LDAP search. Details: " + stackTrace);
- } catch(Exception e) {
- String stackTrace = EcompPortalUtils.getStackTrace(e);
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the LDAP search. Details: " + stackTrace);
- }
- finally {
- dirContext.close();
- }
-
- return searchResult;
- }
-
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @EPMetricsLog
- private ArrayList processResults(NamingEnumeration e) throws NamingException {
- ArrayList results = new ArrayList();
- int count = 0;
-
- while (e.hasMore()) {
- javax.naming.directory.SearchResult searchResult = (javax.naming.directory.SearchResult)e.next();
- results.add(processAttributes(searchResult.getAttributes()));
- count++;
-
- if(count > Integer.parseInt(SystemProperties.getProperty(SystemProperties.POST_MAX_RESULT_SIZE))) {
- break;
- }
- }
- return results;
- }
-
-
- @SuppressWarnings("rawtypes")
- @EPMetricsLog
- private DomainVo processAttributes(Attributes resultAttributes) throws NamingException {
- EPUser user = new EPUser();
-
- try {
- if (resultAttributes == null) {
- logger.debug(EELFLoggerDelegate.debugLogger, "This result has no attributes");
- } else {
- for (NamingEnumeration e = resultAttributes.getAll(); e.hasMore();) { //why the nested loop?
- Attribute attribute = (Attribute)e.next();
- for (NamingEnumeration ie = attribute.getAll(); ie.hasMore();) {
- if (attribute.getID().equalsIgnoreCase("nickname")) {
- user.setFirstName((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("initials")) {
- user.setMiddleInitial((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("sn")) {
- user.setLastName((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("employeeNumber")) {
- user.setHrid((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("mail")) {
- user.setEmail((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("telephoneNumber")) {
- user.setPhone((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("departmentNumber")) {
- user.setOrgCode((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("a1")) {
- user.setOrgUserId((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("street")) {
- user.setAddress1((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("roomNumber")) {
- user.setAddress2((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("l")) {
- user.setCity((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("st")) {
- user.setState((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("postalCode")) {
- user.setZipCode((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("zip4")) {
- user.setZipCodeSuffix((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("physicalDeliveryOfficeName")) {
- user.setLocationClli((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("bc")) {
- user.setBusinessCountryCode((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("friendlyCountryName")) {
- user.setBusinessCountryName((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("bd")) {
- user.setDepartment((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("bdname")) {
- user.setDepartmentName((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("jtname")) {
- user.setJobTitle((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("mgrid")) {
- user.setOrgManagerUserId((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("a2")) {
- user.setCommandChain((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("compcode")) {
- user.setCompanyCode((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("compdesc")) {
- user.setCompany((String) ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("bu")) {
- user.setBusinessUnit((String)ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("buname")) {
- user.setBusinessUnitName((String)ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("silo")) {
- user.setSiloStatus((String)ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("costcenter")) {
- user.setCostCenter((String)ie.next());
- }
- else if (attribute.getID().equalsIgnoreCase("b2")) {
- user.setFinancialLocCode((String)ie.next());
- }
- else { //we don't care about returned attribute, let's move on
- ie.next();
- }
-
- }
- }
- }
- } catch (NamingException e) {
- String stackTrace = EcompPortalUtils.getStackTrace(e);
- logger.error(EELFLoggerDelegate.errorLogger, "An error occurred while processing the following user from POST with an Organization User ID of " + user.getOrgUserId());
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occcurred while processing LDAP search results, Details: " + stackTrace);
- } catch(Exception e) {
- String stackTrace = EcompPortalUtils.getStackTrace(e);
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occcurred while processing LDAP search results, Details: " + stackTrace);
- }
-
- return user;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.Attribute; +import javax.naming.directory.Attributes; +import javax.naming.directory.DirContext; +import javax.naming.directory.SearchControls; + +import org.slf4j.MDC; +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 org.openecomp.portalsdk.core.command.support.SearchResult; +import org.openecomp.portalsdk.core.domain.support.DomainVo; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.support.FusionService; +import org.openecomp.portalsdk.core.service.support.ServiceLocator; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; + +@Service("epLdapService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +public class EPLdapServiceImpl extends FusionService implements EPLdapService { + @Autowired + private ServiceLocator serviceLocator; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPLdapServiceImpl.class); + + @EPAuditLog + @SuppressWarnings({ "rawtypes", "unchecked" }) + public SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, + int pageNo, int dataSize, int userId) throws Exception { + + String remoteHost = ""; + + // initialize the directory context to access POST + DirContext dirContext = serviceLocator.getDirContext(SystemProperties.getProperty(SystemProperties.POST_INITIAL_CONTEXT_FACTORY), + SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL), + SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL)); + + SearchResult searchResult = new SearchResult(); + + try { + + remoteHost = String.format("%s/%s", SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL), + SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL)); + MDC.put(EPCommonSystemProperties.FULL_URL, remoteHost); + + String[] postAttributes = {"nickname","givenName","initials","sn","employeeNumber","mail","telephoneNumber", + "departmentNumber","a1","street","roomNumber","l","st","postalCode","zip4","physicalDeliveryOfficeName","bc", + "friendlyCountryName","bd","bdname","bu","buname","jtname","mgrid","a2","compcode","compdesc", + "costcenter","silo","b2"}; + + SearchControls searchControls = new SearchControls(); + searchControls.setTimeLimit(5000); + searchControls.setReturningAttributes(postAttributes); + + StringBuffer filterClause = new StringBuffer("(&(objectClass=*)"); + + EPUser user = (EPUser)searchCriteria; + + if(Utilities.nvl(user.getFirstName()).length() > 0) { + filterClause.append("(givenName=").append(user.getFirstName()).append("*)"); + } + if(Utilities.nvl(user.getLastName()).length() > 0) { + filterClause.append("(sn=").append(user.getLastName()).append("*)"); + } + if(Utilities.nvl(user.getHrid()).length() > 0) { + filterClause.append("(employeeNumber=").append(user.getHrid()).append("*)"); + } + if(Utilities.nvl(user.getOrgManagerUserId()).length() > 0) { + filterClause.append("(mgrid=").append(user.getOrgManagerUserId()).append("*)"); + } + if(Utilities.nvl(user.getOrgCode()).length() > 0) { + filterClause.append("(departmentNumber=").append(user.getOrgCode()).append("*)"); + } + if(Utilities.nvl(user.getEmail()).length() > 0) { + filterClause.append("(mail=").append(user.getEmail()).append("*)"); + } + if(Utilities.nvl(user.getOrgUserId()).length() > 0) { + filterClause.append("(a1=").append(user.getOrgUserId()).append("*)"); + } + filterClause.append("(c3=N)"); // this has been added to filter CP09 entries on the LDAP server that are duplicates of existing individuals + filterClause.append(")"); + + List list = new ArrayList(); + if (!filterClause.toString().equals("(&(objectClass=*))")) { + NamingEnumeration e = dirContext.search(SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL) + "/" + + SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL), + filterClause.toString(), + searchControls); + list = processResults(e); + } + + Collections.sort(list); + + searchResult = new SearchResult(list); + searchResult.setPageNo(pageNo); + if(dataSize >= 0) { + searchResult.setDataSize(dataSize); + } + else { + searchResult.setDataSize(list.size()); + } + } catch(NamingException ne) { + String stackTrace = EcompPortalUtils.getStackTrace(ne); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the LDAP search. Details: " + stackTrace); + } catch(Exception e) { + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the LDAP search. Details: " + stackTrace); + } + finally { + dirContext.close(); + } + + return searchResult; + } + + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @EPMetricsLog + private ArrayList processResults(NamingEnumeration e) throws NamingException { + ArrayList results = new ArrayList(); + int count = 0; + + while (e.hasMore()) { + javax.naming.directory.SearchResult searchResult = (javax.naming.directory.SearchResult)e.next(); + results.add(processAttributes(searchResult.getAttributes())); + count++; + + if(count > Integer.parseInt(SystemProperties.getProperty(SystemProperties.POST_MAX_RESULT_SIZE))) { + break; + } + } + return results; + } + + + @SuppressWarnings("rawtypes") + @EPMetricsLog + private DomainVo processAttributes(Attributes resultAttributes) throws NamingException { + EPUser user = new EPUser(); + + try { + if (resultAttributes == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "This result has no attributes"); + } else { + for (NamingEnumeration e = resultAttributes.getAll(); e.hasMore();) { //why the nested loop? + Attribute attribute = (Attribute)e.next(); + for (NamingEnumeration ie = attribute.getAll(); ie.hasMore();) { + if (attribute.getID().equalsIgnoreCase("nickname")) { + user.setFirstName((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("initials")) { + user.setMiddleInitial((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("sn")) { + user.setLastName((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("employeeNumber")) { + user.setHrid((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("mail")) { + user.setEmail((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("telephoneNumber")) { + user.setPhone((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("departmentNumber")) { + user.setOrgCode((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("a1")) { + user.setOrgUserId((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("street")) { + user.setAddress1((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("roomNumber")) { + user.setAddress2((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("l")) { + user.setCity((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("st")) { + user.setState((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("postalCode")) { + user.setZipCode((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("zip4")) { + user.setZipCodeSuffix((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("physicalDeliveryOfficeName")) { + user.setLocationClli((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("bc")) { + user.setBusinessCountryCode((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("friendlyCountryName")) { + user.setBusinessCountryName((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("bd")) { + user.setDepartment((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("bdname")) { + user.setDepartmentName((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("jtname")) { + user.setJobTitle((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("mgrid")) { + user.setOrgManagerUserId((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("a2")) { + user.setCommandChain((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("compcode")) { + user.setCompanyCode((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("compdesc")) { + user.setCompany((String) ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("bu")) { + user.setBusinessUnit((String)ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("buname")) { + user.setBusinessUnitName((String)ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("silo")) { + user.setSiloStatus((String)ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("costcenter")) { + user.setCostCenter((String)ie.next()); + } + else if (attribute.getID().equalsIgnoreCase("b2")) { + user.setFinancialLocCode((String)ie.next()); + } + else { //we don't care about returned attribute, let's move on + ie.next(); + } + + } + } + } + } catch (NamingException e) { + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "An error occurred while processing the following user from POST with an Organization User ID of " + user.getOrgUserId()); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occcurred while processing LDAP search results, Details: " + stackTrace); + } catch(Exception e) { + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occcurred while processing LDAP search results, Details: " + stackTrace); + } + + return user; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuService.java index ed9c3c4d..9785f2b0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuService.java @@ -1,44 +1,44 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.Set;
-
-import org.openecomp.portalsdk.core.domain.MenuData;
-import org.openecomp.portalapp.portal.domain.EPUser;
-
-public interface EPLeftMenuService {
-
- /**
- * Builds a JSON suitable for populating the front-end left menu from the supplied set of menu items.
- * @param user
- *
- * @param fullMenuSet
- * @param roleFunctionSet
- * @return JSON String of this form:
- * <PRE>
- * {"navItems":[
- * {"name":"Home","imageSrc":"icon-location-pin","state":"root.applicationsHome"},
- * ...
- * ] }
- * </PRE>
- */
- String getLeftMenuItems(EPUser user, Set<MenuData> fullMenuSet, Set<String> roleFunctionSet);
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.Set; + +import org.openecomp.portalsdk.core.domain.MenuData; +import org.openecomp.portalapp.portal.domain.EPUser; + +public interface EPLeftMenuService { + + /** + * Builds a JSON suitable for populating the front-end left menu from the supplied set of menu items. + * @param user + * + * @param fullMenuSet + * @param roleFunctionSet + * @return JSON String of this form: + * <PRE> + * {"navItems":[ + * {"name":"Home","imageSrc":"icon-location-pin","state":"root.applicationsHome"}, + * ... + * ] } + * </PRE> + */ + String getLeftMenuItems(EPUser user, Set<MenuData> fullMenuSet, Set<String> roleFunctionSet); +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuServiceImpl.java index 2a1f466a..9158e990 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuServiceImpl.java @@ -1,195 +1,195 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.Collection;
-import java.util.Comparator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import org.json.JSONArray;
-import org.json.JSONObject;
-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 org.openecomp.portalsdk.core.domain.MenuData;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.UserRoles;
-//import org.openecomp.portalapp.portal.domain.Menu;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-
-@Service("leftMenuService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-
-public class EPLeftMenuServiceImpl implements EPLeftMenuService {
-
- private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPLeftMenuServiceImpl.class);
-
- @Autowired
- private EPAppService appService;
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.openecomp.portalapp.portal.service.EPLeftMenuService#getLeftMenuItems
- * (java.util.Set)
- */
- @Override
- public String getLeftMenuItems(EPUser user, Set<MenuData> fullMenuSet, Set<String> roleFunctionSet) {
- final Map<String, JSONObject> defaultNavMap = new LinkedHashMap<String, JSONObject>();
-
- resetNavMap(defaultNavMap);
-
- loadDefaultNavMap(defaultNavMap);
-
- // Handle Account Administrator in a special way; soon this will
- // be revised as Account Administrator may become obsolete
- try {
- if (user != null) {
- UserRoles uRoles = appService.getUserProfileNormalized(user);
- if (uRoles.getRoles().contains("Account Administrator"))
- loadAccAdminNavMap(defaultNavMap);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "getLeftMenuItems: failed to get roles for user " + user.getOrgUserId(), e);
- }
-
- loadNavMapByRole(defaultNavMap, fullMenuSet);
-
- return convertToSideBarModel(defaultNavMap);
- }
-
- /**
- * Clears the map
- *
- * @param defaultNavMap
- */
- private void resetNavMap(Map<String, JSONObject> defaultNavMap) {
- defaultNavMap.clear();
- }
-
- /**
- *
- * @param defaultNavMap
- * @param fullMenuSet
- */
- private void loadNavMapByRole(Map<String, JSONObject> defaultNavMap, Set<MenuData> fullMenuSet) {
-
- class SortOrderComparator implements Comparator<MenuData> {
- @Override
- public int compare(MenuData e1, MenuData e2) {
- return e1.getSortOrder().compareTo(e2.getSortOrder());
- }
- }
-
- SortedSet<MenuData> sortMenuSet = new TreeSet<MenuData>(new SortOrderComparator());
- for (MenuData mn : fullMenuSet) {
- sortMenuSet.add(mn);
- }
-
- for (MenuData mn : sortMenuSet) {
- JSONObject navItemsDetails = new JSONObject();
- navItemsDetails.put("name", mn.getLabel());
- navItemsDetails.put("state", mn.getAction());
- navItemsDetails.put("imageSrc", mn.getImageSrc());
- defaultNavMap.put(mn.getAction(), navItemsDetails);
- }
- }
-
- /**
- *
- * @param defaultNavMap
- * @return
- */
- private String convertToSideBarModel(Map<String, JSONObject> defaultNavMap) {
- JSONObject sidebarModel = new JSONObject();
- JSONArray navItems = new JSONArray();
- Collection<JSONObject> jsonObjs = defaultNavMap.values();
-
- for (JSONObject navItemsDetail : jsonObjs)
- navItems.put(navItemsDetail);
-
- sidebarModel.put("label", "ECOMP portal");
- sidebarModel.put("navItems", navItems);
- return sidebarModel.toString();
- }
-
- /**
- * Loads default entries for regular user.
- *
- * @param defaultNavMap
- */
- private void loadDefaultNavMap(Map<String, JSONObject> defaultNavMap) {
-
- JSONObject navItemsDetails1 = new JSONObject();
- navItemsDetails1.put("name", "Home");
- navItemsDetails1.put("state", "root.applicationsHome");
- navItemsDetails1.put("imageSrc", "icon-building-home");
- defaultNavMap.put("root.applicationsHome", navItemsDetails1);
-
- JSONObject navItemsDetails2 = new JSONObject();
- navItemsDetails2.put("name", "Application Catalog");
- navItemsDetails2.put("state", "root.appCatalog");
- navItemsDetails2.put("imageSrc", "icon-apps-marketplace");
- defaultNavMap.put("root.appCatalog", navItemsDetails2);
-
- JSONObject navItemsDetails3 = new JSONObject();
- navItemsDetails3.put("name", "Widget Catalog");
- navItemsDetails3.put("state", "root.widgetCatalog");
- navItemsDetails3.put("imageSrc", "icon-apps-marketplace");
- defaultNavMap.put("root.widgetCatalog", navItemsDetails3);
-
- }
-
- /**
- * Loads default entries for application administrator.
- *
- * @param defaultNavMap
- */
- private void loadAccAdminNavMap(Map<String, JSONObject> defaultNavMap) {
-
- JSONObject navItemsDetails1 = new JSONObject();
- navItemsDetails1.put("name", "Users");
- navItemsDetails1.put("state", "root.users");
- navItemsDetails1.put("imageSrc", "icon-user");
- defaultNavMap.put("root.users", navItemsDetails1);
-
- // No more widget onboarding like this:
- //
- // JSONObject navItemsDetails2 = new JSONObject();
- // navItemsDetails2.put("name", "Widget Onboarding");
- // navItemsDetails2.put("state", "root.widgetOnboarding");
- // navItemsDetails2.put("imageSrc", "icon-add-widget");
- // defaultNavMap.put("root.widgetOnboarding", navItemsDetails2);
-
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.Collection; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; + +import org.json.JSONArray; +import org.json.JSONObject; +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 org.openecomp.portalsdk.core.domain.MenuData; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.UserRoles; +//import org.openecomp.portalapp.portal.domain.Menu; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; + +@Service("leftMenuService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog + +public class EPLeftMenuServiceImpl implements EPLeftMenuService { + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPLeftMenuServiceImpl.class); + + @Autowired + private EPAppService appService; + + /* + * (non-Javadoc) + * + * @see + * org.openecomp.portalapp.portal.service.EPLeftMenuService#getLeftMenuItems + * (java.util.Set) + */ + @Override + public String getLeftMenuItems(EPUser user, Set<MenuData> fullMenuSet, Set<String> roleFunctionSet) { + final Map<String, JSONObject> defaultNavMap = new LinkedHashMap<String, JSONObject>(); + + resetNavMap(defaultNavMap); + + loadDefaultNavMap(defaultNavMap); + + // Handle Account Administrator in a special way; soon this will + // be revised as Account Administrator may become obsolete + try { + if (user != null) { + UserRoles uRoles = appService.getUserProfileNormalized(user); + if (uRoles.getRoles().contains("Account Administrator")) + loadAccAdminNavMap(defaultNavMap); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "getLeftMenuItems: failed to get roles for user " + user.getOrgUserId(), e); + } + + loadNavMapByRole(defaultNavMap, fullMenuSet); + + return convertToSideBarModel(defaultNavMap); + } + + /** + * Clears the map + * + * @param defaultNavMap + */ + private void resetNavMap(Map<String, JSONObject> defaultNavMap) { + defaultNavMap.clear(); + } + + /** + * + * @param defaultNavMap + * @param fullMenuSet + */ + private void loadNavMapByRole(Map<String, JSONObject> defaultNavMap, Set<MenuData> fullMenuSet) { + + class SortOrderComparator implements Comparator<MenuData> { + @Override + public int compare(MenuData e1, MenuData e2) { + return e1.getSortOrder().compareTo(e2.getSortOrder()); + } + } + + SortedSet<MenuData> sortMenuSet = new TreeSet<MenuData>(new SortOrderComparator()); + for (MenuData mn : fullMenuSet) { + sortMenuSet.add(mn); + } + + for (MenuData mn : sortMenuSet) { + JSONObject navItemsDetails = new JSONObject(); + navItemsDetails.put("name", mn.getLabel()); + navItemsDetails.put("state", mn.getAction()); + navItemsDetails.put("imageSrc", mn.getImageSrc()); + defaultNavMap.put(mn.getAction(), navItemsDetails); + } + } + + /** + * + * @param defaultNavMap + * @return + */ + private String convertToSideBarModel(Map<String, JSONObject> defaultNavMap) { + JSONObject sidebarModel = new JSONObject(); + JSONArray navItems = new JSONArray(); + Collection<JSONObject> jsonObjs = defaultNavMap.values(); + + for (JSONObject navItemsDetail : jsonObjs) + navItems.put(navItemsDetail); + + sidebarModel.put("label", "ECOMP portal"); + sidebarModel.put("navItems", navItems); + return sidebarModel.toString(); + } + + /** + * Loads default entries for regular user. + * + * @param defaultNavMap + */ + private void loadDefaultNavMap(Map<String, JSONObject> defaultNavMap) { + + JSONObject navItemsDetails1 = new JSONObject(); + navItemsDetails1.put("name", "Home"); + navItemsDetails1.put("state", "root.applicationsHome"); + navItemsDetails1.put("imageSrc", "icon-building-home"); + defaultNavMap.put("root.applicationsHome", navItemsDetails1); + + JSONObject navItemsDetails2 = new JSONObject(); + navItemsDetails2.put("name", "Application Catalog"); + navItemsDetails2.put("state", "root.appCatalog"); + navItemsDetails2.put("imageSrc", "icon-apps-marketplace"); + defaultNavMap.put("root.appCatalog", navItemsDetails2); + + JSONObject navItemsDetails3 = new JSONObject(); + navItemsDetails3.put("name", "Widget Catalog"); + navItemsDetails3.put("state", "root.widgetCatalog"); + navItemsDetails3.put("imageSrc", "icon-apps-marketplace"); + defaultNavMap.put("root.widgetCatalog", navItemsDetails3); + + } + + /** + * Loads default entries for application administrator. + * + * @param defaultNavMap + */ + private void loadAccAdminNavMap(Map<String, JSONObject> defaultNavMap) { + + JSONObject navItemsDetails1 = new JSONObject(); + navItemsDetails1.put("name", "Users"); + navItemsDetails1.put("state", "root.users"); + navItemsDetails1.put("imageSrc", "icon-user"); + defaultNavMap.put("root.users", navItemsDetails1); + + // No more widget onboarding like this: + // + // JSONObject navItemsDetails2 = new JSONObject(); + // navItemsDetails2.put("name", "Widget Onboarding"); + // navItemsDetails2.put("state", "root.widgetOnboarding"); + // navItemsDetails2.put("imageSrc", "icon-add-widget"); + // defaultNavMap.put("root.widgetOnboarding", navItemsDetails2); + + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLoginService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLoginService.java index 4bdb2009..d8d2a290 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLoginService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLoginService.java @@ -1,70 +1,72 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.HashMap;
-
-import org.openecomp.portalapp.command.EPLoginBean;
-import org.openecomp.portalapp.portal.domain.EPUser;
-
-public interface EPLoginService {
-
- /**
- * Calls {@link #findUser(EPLoginBean, String, HashMap, boolean)} with the
- * last parameter set to true.
- *
- * @param bean
- * @param menuPropertiesFilename
- * @param additionalParams
- * @return EPUser object; null on error or if no match.
- * @throws Exception
- */
- @SuppressWarnings("rawtypes")
- EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename, HashMap additionalParams) throws Exception;
-
- /**
- * Searches the fn_user table for a row that matches information in the
- * bean. Uses the bean's Organization User ID property if present; if not, uses the bean's
- * LoginId property and (optionally, depending on matchPassword parameter)
- * loginPwd property.
- *
- * @param bean
- * EPLoginBean
- * @param menuPropertiesFileName
- * Always ignored
- * @param additionalParams
- * Used by DataAccessService when updating a matched user object
- * @param matchPassword
- * If true, the search must match the password
- * @return EPUser object; null on error or if no match.
- */
- @SuppressWarnings("rawtypes")
- EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename, HashMap additionalParams,
- boolean matchPassword) throws Exception;
-
- /**
- * Searches the fn_user table for a row with a value in column login_id that
- * matches the specified value.
- *
- * @param loginId
- * @return EPUser object; null on error or if no match.
- */
- public EPUser findUserWithoutPwd(String loginId);
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.HashMap; + +import org.openecomp.portalapp.command.EPLoginBean; +import org.openecomp.portalapp.portal.domain.EPUser; + +public interface EPLoginService { + + /** + * Calls {@link #findUser(EPLoginBean, String, HashMap, boolean)} with the + * last parameter set to true. + * + * @param bean + * @param menuPropertiesFilename + * @param additionalParams + * @return EPUser object; null on error or if no match. + * @throws Exception + */ + @SuppressWarnings("rawtypes") + EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename, HashMap additionalParams) throws Exception; + + /** + * Searches the fn_user table for a row that matches information in the + * bean. Uses the bean's Organization User ID property if present; if not, + * uses the bean's LoginId property and (optionally, depending on + * matchPassword parameter) loginPwd property. + * + * @param bean + * EPLoginBean + * @param menuPropertiesFileName + * Always ignored + * @param additionalParams + * Used by DataAccessService when updating a matched user object + * @param matchPassword + * If true, the search must match the password + * @return EPUser object; null on error or if no match. + * @throws Exception + */ + @SuppressWarnings("rawtypes") + EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFileName, HashMap additionalParams, + boolean matchPassword) throws Exception; + + /** + * Searches the fn_user table for a row with a value in column login_id that + * matches the specified value. + * + * @param loginId + * Login name + * @return EPUser object; null on error or if no match. + */ + public EPUser findUserWithoutPwd(String loginId); +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLoginServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLoginServiceImpl.java index ba202d63..f9125064 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLoginServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLoginServiceImpl.java @@ -1,234 +1,234 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.menu.MenuBuilder;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.service.support.FusionService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.openecomp.portalapp.command.EPLoginBean;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.util.EPUserUtils;
-
-@Service("eploginService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class EPLoginServiceImpl extends FusionService implements EPLoginService {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPLoginServiceImpl.class);
-
- @Autowired
- private DataAccessService dataAccessService;
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.EPLoginService#findUser(org.openecomp.portalapp.command.EPLoginBean, java.lang.String, java.util.HashMap)
- */
- @SuppressWarnings("rawtypes")
- public EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename, HashMap additionalParams)
- throws Exception {
- return findUser(bean, menuPropertiesFilename, additionalParams, true);
- }
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.EPLoginService#findUser(org.openecomp.portalapp.command.EPLoginBean, java.lang.String, java.util.HashMap, boolean)
- */
- @SuppressWarnings("rawtypes")
- public EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename_ignored, HashMap additionalParams,
- boolean matchPassword) throws Exception {
- EPUser user = null;
- EPUser userCopy = null;
-
- if (bean.getOrgUserId() != null) {
- user = (EPUser) findUser(bean);
- } else {
- if (matchPassword)
- user = (EPUser) findUser(bean.getLoginId(), bean.getLoginPwd());
- else
- user = (EPUser) findUserWithoutPwd(bean.getLoginId());
- }
-
- // run this command to fetch more information from the lazily loaded
- // object
-
- // This is funny - commenting out the following method call
- // 1. What are we doing with the returned values of the following two
- // methods? Nothing.
- // 2. Use a guest user scenario - user object will be null - clealry,
- // NPE.
- // 3. A check of if(user !=null) is made AFTER these bogus calls :) - If
- // these calls WERE doing anything significat (which they are not),
- // shouln't they have been moved inside that if check?
-
- // user.getEPUserApps();
-
- // Comments
- // 1. This method is clearly doing more than 'getting roles' - Not a
- // good name -
- // 2. Also, there is no null check - guest user scenarios will break the
- // code with NPE - added the check - Do not want to remove the call
- // altogether - not sure how it will effect things.
-
- if (user != null) {
- user.getEPRoles();
-
- // raise an error if the portal application is locked and the user
- // does not
- // have system administrator privileges
- if (AppUtils.isApplicationLocked()
- && !EPUserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) {
- bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED);
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUserAdminPrivilegesInfo, user.getLoginId());
- }
-
- // raise an error if the user is inactive
- if (!user.getActive()) {
- bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUserInactiveWarning, user.getLoginId());
- }
-
- // only login the user if no errors have occurred
- if (bean.getLoginErrorMessage() == null) {
-
- // this will be a snapshot of the user's information as
- // retrieved from the database
- userCopy = (EPUser) user.clone();
-
- // update the last logged in date for the user
- user.setLastLoginDate(new Date());
- getDataAccessService().saveDomainObject(user, additionalParams);
-
- // create the application menu based on the user's privileges
- MenuBuilder menuBuilder = new MenuBuilder();
- Set appMenu = menuBuilder.getMenu(
- SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME), dataAccessService);
- bean.setMenu(appMenu != null ? appMenu : new HashSet());
- Set businessDirectMenu = menuBuilder.getMenu(
- SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_SET_NAME),
- dataAccessService);
- bean.setBusinessDirectMenu(businessDirectMenu != null ? businessDirectMenu : new HashSet());
-
- bean.setUser(userCopy);
- }
-
- } else {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUserMissingError, bean.getOrgUserId());
- }
-
- return bean;
- }
-
- /**
- * Searches the fn_user table for a row that matches the specified login_id
- * and login_pwd values.
- *
- * @param loginId
- * @param password
- * @return EPUser object; null on error or if no match.
- */
- private EPUser findUser(String loginId, String password) {
- List<?> list = null;
-
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where login_id = '").append(loginId).append("'").append(" and login_pwd = '").append(password)
- .append("'");
-
- try {
- list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null);
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- logger.error(EELFLoggerDelegate.errorLogger, "findUser(String) failed on " + loginId, e);
- }
-
- return (list == null || list.size() == 0) ? null : (EPUser) list.get(0);
- }
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.EPLoginService#findUserWithoutPwd(java.lang.String)
- */
- @Override
- public EPUser findUserWithoutPwd(String loginId) {
- List<?> list = null;
-
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where login_id = '").append(loginId).append("'");
-
- try {
- list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null);
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- String message = "findUserWithoutPwd failed on " + loginId;
- logger.error(EELFLoggerDelegate.errorLogger, message, e);
- }
-
- return (list == null || list.size() == 0) ? null : (EPUser) list.get(0);
- }
-
- /**
- * Searches the fn_user table for a row that matches the value of the bean's
- * Organization User ID property.
- *
- * @param bean
- * @return EPUser object; null on error or if no match.
- */
- private EPUser findUser(EPLoginBean bean) {
- List<?> list = null;
-
- StringBuffer criteria = new StringBuffer();
- criteria.append(" where orgUserId = '").append(bean.getOrgUserId()).append("'");
-
- try {
- list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null);
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- logger.error(EELFLoggerDelegate.errorLogger, "findUser(EPLoginBean) failed", e);
- }
-
- return (list == null || list.size() == 0) ? null : (EPUser) list.get(0);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.menu.MenuBuilder; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.support.FusionService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.openecomp.portalapp.command.EPLoginBean; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.util.EPUserUtils; + +@Service("eploginService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class EPLoginServiceImpl extends FusionService implements EPLoginService { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPLoginServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + /* + * (non-Javadoc) + * @see org.openecomp.portalapp.portal.service.EPLoginService#findUser(org.openecomp.portalapp.command.EPLoginBean, java.lang.String, java.util.HashMap) + */ + @SuppressWarnings("rawtypes") + public EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename, HashMap additionalParams) + throws Exception { + return findUser(bean, menuPropertiesFilename, additionalParams, true); + } + + /* + * (non-Javadoc) + * @see org.openecomp.portalapp.portal.service.EPLoginService#findUser(org.openecomp.portalapp.command.EPLoginBean, java.lang.String, java.util.HashMap, boolean) + */ + @SuppressWarnings("rawtypes") + public EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename_ignored, HashMap additionalParams, + boolean matchPassword) throws Exception { + EPUser user = null; + EPUser userCopy = null; + + if (bean.getOrgUserId() != null) { + user = (EPUser) findUser(bean); + } else { + if (matchPassword) + user = (EPUser) findUser(bean.getLoginId(), bean.getLoginPwd()); + else + user = (EPUser) findUserWithoutPwd(bean.getLoginId()); + } + + // run this command to fetch more information from the lazily loaded + // object + + // This is funny - commenting out the following method call + // 1. What are we doing with the returned values of the following two + // methods? Nothing. + // 2. Use a guest user scenario - user object will be null - clealry, + // NPE. + // 3. A check of if(user !=null) is made AFTER these bogus calls :) - If + // these calls WERE doing anything significat (which they are not), + // shouln't they have been moved inside that if check? + + // user.getEPUserApps(); + + // Comments + // 1. This method is clearly doing more than 'getting roles' - Not a + // good name - + // 2. Also, there is no null check - guest user scenarios will break the + // code with NPE - added the check - Do not want to remove the call + // altogether - not sure how it will effect things. + + if (user != null) { + user.getEPRoles(); + + // raise an error if the portal application is locked and the user + // does not + // have system administrator privileges + if (AppUtils.isApplicationLocked() + && !EPUserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) { + bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUserAdminPrivilegesInfo, user.getLoginId()); + } + + // raise an error if the user is inactive + if (!user.getActive()) { + bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUserInactiveWarning, user.getLoginId()); + } + + // only login the user if no errors have occurred + if (bean.getLoginErrorMessage() == null) { + + // this will be a snapshot of the user's information as + // retrieved from the database + userCopy = (EPUser) user.clone(); + + // update the last logged in date for the user + user.setLastLoginDate(new Date()); + getDataAccessService().saveDomainObject(user, additionalParams); + + // create the application menu based on the user's privileges + MenuBuilder menuBuilder = new MenuBuilder(); + Set appMenu = menuBuilder.getMenu( + SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME), dataAccessService); + bean.setMenu(appMenu != null ? appMenu : new HashSet()); + Set businessDirectMenu = menuBuilder.getMenu( + SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_SET_NAME), + dataAccessService); + bean.setBusinessDirectMenu(businessDirectMenu != null ? businessDirectMenu : new HashSet()); + + bean.setUser(userCopy); + } + + } else { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUserMissingError, bean.getOrgUserId()); + } + + return bean; + } + + /** + * Searches the fn_user table for a row that matches the specified login_id + * and login_pwd values. + * + * @param loginId + * @param password + * @return EPUser object; null on error or if no match. + */ + private EPUser findUser(String loginId, String password) { + List<?> list = null; + + StringBuffer criteria = new StringBuffer(); + criteria.append(" where login_id = '").append(loginId).append("'").append(" and login_pwd = '").append(password) + .append("'"); + + try { + list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, "findUser(String) failed on " + loginId, e); + } + + return (list == null || list.size() == 0) ? null : (EPUser) list.get(0); + } + + /* + * (non-Javadoc) + * @see org.openecomp.portalapp.portal.service.EPLoginService#findUserWithoutPwd(java.lang.String) + */ + @Override + public EPUser findUserWithoutPwd(String loginId) { + List<?> list = null; + + StringBuffer criteria = new StringBuffer(); + criteria.append(" where login_id = '").append(loginId).append("'"); + + try { + list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + String message = "findUserWithoutPwd failed on " + loginId; + logger.error(EELFLoggerDelegate.errorLogger, message, e); + } + + return (list == null || list.size() == 0) ? null : (EPUser) list.get(0); + } + + /** + * Searches the fn_user table for a row that matches the value of the bean's + * Organization User ID property. + * + * @param bean + * @return EPUser object; null on error or if no match. + */ + private EPUser findUser(EPLoginBean bean) { + List<?> list = null; + + StringBuffer criteria = new StringBuffer(); + criteria.append(" where orgUserId = '").append(bean.getOrgUserId()).append("'"); + + try { + list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + logger.error(EELFLoggerDelegate.errorLogger, "findUser(EPLoginBean) failed", e); + } + + return (list == null || list.size() == 0) ? null : (EPUser) list.get(0); + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleService.java index 32dccbe0..cec7dd64 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleService.java @@ -1,37 +1,37 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalapp.portal.domain.EPRole;
-
-
-public interface EPRoleService {
-
- // Used by ECOMP. Get cached role by two columns used by ECOMP only. app id, and external app role id.
- EPRole getRole(Long appId, Long appRoleid);
- public void saveRole(EPRole domainRole);
- EPRole getAppRole(String roleName, Long appId);
- public List<RoleFunction> getRoleFunctions();
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalapp.portal.domain.EPRole; + + +public interface EPRoleService { + + // Used by ECOMP. Get cached role by two columns used by ECOMP only. app id, and external app role id. + EPRole getRole(Long appId, Long appRoleid); + public void saveRole(EPRole domainRole); + EPRole getAppRole(String roleName, Long appId); + public List<RoleFunction> getRoleFunctions(); + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleServiceImpl.java index d7661e9a..e509fcf5 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleServiceImpl.java @@ -1,171 +1,179 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-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 org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalapp.portal.domain.EPRole;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-
-@Service("epRoleService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class EPRoleServiceImpl implements EPRoleService{
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPRoleServiceImpl.class);
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @SuppressWarnings("unchecked")
- public List<RoleFunction> getRoleFunctions() {
- //List msgDB = getDataAccessService().getList(Profile.class, null);
- return getDataAccessService().getList(RoleFunction.class, null);
- }
-
- @SuppressWarnings("unchecked")
- public List<EPRole> getAvailableChildRoles(Long roleId) {
- List<EPRole> availableChildRoles = (List<EPRole>)getDataAccessService().getList(EPRole.class,null);
- if(roleId==null || roleId==0){
- return availableChildRoles;
- }
-
- EPRole currentRole = (EPRole)getDataAccessService().getDomainObject(EPRole.class,roleId,null);
- Set<EPRole> allParentRoles = new TreeSet<EPRole>();
- allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
-
-
- Iterator<EPRole> availableChildRolesIterator = availableChildRoles.iterator();
- while (availableChildRolesIterator.hasNext()) {
- EPRole role = availableChildRolesIterator.next();
- if(!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)){
- availableChildRolesIterator.remove();
- }
- }
- return availableChildRoles;
- }
-
- private Set<EPRole> getAllParentRolesAsList(EPRole role, Set<EPRole> allParentRoles) {
- Set<EPRole> parentRoles = role.getParentRoles();
- allParentRoles.addAll(parentRoles);
- Iterator<EPRole> parentRolesIterator = parentRoles.iterator();
- while (parentRolesIterator.hasNext()) {
- getAllParentRolesAsList(parentRolesIterator.next(),allParentRoles);
- }
- return allParentRoles;
- }
-
- public RoleFunction getRoleFunction(String code) {
- return (RoleFunction)getDataAccessService().getDomainObject(RoleFunction.class, code, null);
- }
-
- public void saveRoleFunction(RoleFunction domainRoleFunction) {
- getDataAccessService().saveDomainObject(domainRoleFunction, null);
- }
-
- public void deleteRoleFunction(RoleFunction domainRoleFunction) {
- getDataAccessService().deleteDomainObject(domainRoleFunction, null);
- }
-
- public EPRole getRole(Long id) {
- return (EPRole)getDataAccessService().getDomainObject(EPRole.class, id, null);
- }
-
- // TODO: refactor
- private static final String getAppRoleSqlFormat ="SELECT * FROM fn_role where APP_ID = %s AND APP_ROLE_ID = %s";
-
- @SuppressWarnings("unchecked")
- public EPRole getRole(Long appId, Long appRoleid) {
- if(appId == null || appRoleid == null){
- logger.error(EELFLoggerDelegate.errorLogger, String.format("getRole does not support null appId or roleId. appRoleid=%s, appRoleid=%s", appId, appRoleid));
- return null;
- }
-
- String sql = String.format(getAppRoleSqlFormat, appId, appRoleid);
-
- List<EPRole> roles = (List<EPRole>)dataAccessService.executeSQLQuery(sql, EPRole.class, null);
- int resultsCount = roles.size();
- if(resultsCount > 1){
- logger.error(EELFLoggerDelegate.errorLogger, String.format("search by appId=%s, appRoleid=%s should have returned 0 or 1 results. Got %d. This is an internal server error.", appId, appRoleid, resultsCount));
- logger.error(EELFLoggerDelegate.errorLogger, "Trying to recover from duplicates by returning the first search result. This issue should be treated, it is probably not critical because duplicate roles should be similar.");
- return roles.get(0);
- } else if(resultsCount == 1){
- return roles.get(0);
- }
- return null;
- }
-
- @SuppressWarnings("unchecked")
- public EPRole getAppRole(String roleName, Long appId) {
-
- final Map<String, String> params = new HashMap<String, String>();
- params.put("appId", appId.toString());
- params.put("roleName", roleName);
-
- List<EPRole> roles = (List<EPRole>)dataAccessService.executeNamedQuery("getAppRoles", params, null);
- int resultsCount = roles.size();
- if(resultsCount > 1){
- logger.error(EELFLoggerDelegate.errorLogger, "Trying to recover from duplicates by returning the first search result. This issue should be treated, it is probably not critical because duplicate roles should be similar.");
- return roles.get(0);
- } else if(resultsCount == 1){
- return roles.get(0);
- }
- return null;
- }
-
-
- public void saveRole(EPRole domainRole) {
- getDataAccessService().saveDomainObject(domainRole, null);
- }
-
- public void deleteRole(EPRole domainRole) {
- getDataAccessService().deleteDomainObject(domainRole, null);
- }
-
- @SuppressWarnings("unchecked")
- public List<EPRole> getAvailableRoles() {
- return getDataAccessService().getList(EPRole.class, null);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-}
-
-
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +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 org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.utils.PortalConstants; + +@Service("epRoleService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class EPRoleServiceImpl implements EPRoleService { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPRoleServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + @SuppressWarnings("unchecked") + public List<RoleFunction> getRoleFunctions() { + // List msgDB = getDataAccessService().getList(Profile.class, null); + return getDataAccessService().getList(RoleFunction.class, null); + } + + @SuppressWarnings("unchecked") + public List<EPRole> getAvailableChildRoles(Long roleId) { + List<EPRole> availableChildRoles = (List<EPRole>) getDataAccessService().getList(EPRole.class, null); + if (roleId == null || roleId == 0) { + return availableChildRoles; + } + + EPRole currentRole = (EPRole) getDataAccessService().getDomainObject(EPRole.class, roleId, null); + Set<EPRole> allParentRoles = new TreeSet<EPRole>(); + allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles); + + Iterator<EPRole> availableChildRolesIterator = availableChildRoles.iterator(); + while (availableChildRolesIterator.hasNext()) { + EPRole role = availableChildRolesIterator.next(); + if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) { + availableChildRolesIterator.remove(); + } + } + return availableChildRoles; + } + + private Set<EPRole> getAllParentRolesAsList(EPRole role, Set<EPRole> allParentRoles) { + Set<EPRole> parentRoles = role.getParentRoles(); + allParentRoles.addAll(parentRoles); + Iterator<EPRole> parentRolesIterator = parentRoles.iterator(); + while (parentRolesIterator.hasNext()) { + getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles); + } + return allParentRoles; + } + + public RoleFunction getRoleFunction(String code) { + return (RoleFunction) getDataAccessService().getDomainObject(RoleFunction.class, code, null); + } + + public void saveRoleFunction(RoleFunction domainRoleFunction) { + getDataAccessService().saveDomainObject(domainRoleFunction, null); + } + + public void deleteRoleFunction(RoleFunction domainRoleFunction) { + getDataAccessService().deleteDomainObject(domainRoleFunction, null); + } + + public EPRole getRole(Long id) { + return (EPRole) getDataAccessService().getDomainObject(EPRole.class, id, null); + } + + // TODO: refactor + private static final String getAppRoleSqlFormat = "SELECT * FROM fn_role where APP_ID = %s AND APP_ROLE_ID = %s"; + + @SuppressWarnings("unchecked") + public EPRole getRole(Long appId, Long appRoleid) { + if (appId == null || appRoleid == null) { + logger.error(EELFLoggerDelegate.errorLogger, String.format( + "getRole does not support null appId or roleId. appRoleid=%s, appRoleid=%s", appId, appRoleid)); + return null; + } + + String sql = String.format(getAppRoleSqlFormat, appId, appRoleid); + + List<EPRole> roles = (List<EPRole>) dataAccessService.executeSQLQuery(sql, EPRole.class, null); + int resultsCount = roles.size(); + if (resultsCount > 1) { + logger.error(EELFLoggerDelegate.errorLogger, + String.format( + "search by appId=%s, appRoleid=%s should have returned 0 or 1 results. Got %d. This is an internal server error.", + appId, appRoleid, resultsCount)); + logger.error(EELFLoggerDelegate.errorLogger, + "Trying to recover from duplicates by returning the first search result. This issue should be treated, it is probably not critical because duplicate roles should be similar."); + return roles.get(0); + } else if (resultsCount == 1) { + return roles.get(0); + } + return null; + } + + @SuppressWarnings("unchecked") + public EPRole getAppRole(String roleName, Long appId) { + + final Map<String, String> params = new HashMap<String, String>(); + final Map<String, String> portalParams = new HashMap<String, String>(); + List<EPRole> roles = null; + params.put("appId", appId.toString()); + params.put("roleName", roleName); + portalParams.put("appRoleName", roleName); + if (appId == 1 || roleName.equals(PortalConstants.ADMIN_ROLE)) { + roles = (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", portalParams, null); + } else if (appId != 1 && !roleName.equals(PortalConstants.ADMIN_ROLE)) { + roles = (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", params, null); + } + int resultsCount = roles.size(); + if (resultsCount > 1) { + logger.error(EELFLoggerDelegate.errorLogger, + "Trying to recover from duplicates by returning the first search result. This issue should be treated, it is probably not critical because duplicate roles should be similar."); + return roles.get(0); + } else if (resultsCount == 1) { + return roles.get(0); + } + return null; + } + + public void saveRole(EPRole domainRole) { + getDataAccessService().saveDomainObject(domainRole, null); + } + + public void deleteRole(EPRole domainRole) { + getDataAccessService().deleteDomainObject(domainRole, null); + } + + @SuppressWarnings("unchecked") + public List<EPRole> getAvailableRoles() { + return getDataAccessService().getList(EPRole.class, null); + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuService.java index 0fa790c5..c9aac85e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuService.java @@ -1,58 +1,58 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.FunctionalMenuItemWithAppID;
-import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRole;
-import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItem;
-import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuItemWithRoles;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuRole;
-
-public interface FunctionalMenuService {
- List<FunctionalMenuItem> getFunctionalMenuItems (EPUser user);
- // return all active menu items
- List<FunctionalMenuItem> getFunctionalMenuItems ();
- // return all active menu items. If all is true, return all active and inactive menu items.
- List<FunctionalMenuItem> getFunctionalMenuItems(Boolean all);
- // return all active Functional menu items for Notification Tree in User Notification . If all is true, return all active menu items.
- List<FunctionalMenuItem> getFunctionalMenuItemsForNotificationTree(Boolean all);
- List<FunctionalMenuItem> getFunctionalMenuItemsForApp (Integer appId);
- List<FunctionalMenuItem> getFunctionalMenuItemsForUser (String orgUserId);
- FunctionalMenuItem getFunctionalMenuItemDetails (Integer menuid);
- FieldsValidator createFunctionalMenuItem (FunctionalMenuItemWithRoles menuItemJson);
- FieldsValidator editFunctionalMenuItem (FunctionalMenuItemWithRoles menuItemJson);
- FieldsValidator deleteFunctionalMenuItem (Long menuId);
- FieldsValidator regenerateAncestorTable ();
- //Methods relevant to favorites
- FieldsValidator setFavoriteItem(FavoritesFunctionalMenuItem menuItemJson);
- List<FavoritesFunctionalMenuItemJson> getFavoriteItems(Long userId);
- FieldsValidator removeFavoriteItem (Long userId, Long menuId);
- List<FunctionalMenuItem> transformFunctionalMenuItemWithAppIDToFunctionalMenuItem(List<FunctionalMenuItemWithAppID> functionalMenuItemWithAppIDList);
- List<FunctionalMenuRole> getFunctionalMenuRole();
- //Assign URLs under Help Menu
- void assignHelpURLs(List<FunctionalMenuItem> menuItems);
- List<BusinessCardApplicationRole> getUserAppRolesList(String userId);
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.FunctionalMenuItemWithAppID; +import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRole; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItemWithRoles; +import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; + +public interface FunctionalMenuService { + List<FunctionalMenuItem> getFunctionalMenuItems (EPUser user); + // return all active menu items + List<FunctionalMenuItem> getFunctionalMenuItems (); + // return all active menu items. If all is true, return all active and inactive menu items. + List<FunctionalMenuItem> getFunctionalMenuItems(Boolean all); + // return all active Functional menu items for Notification Tree in User Notification . If all is true, return all active menu items. + List<FunctionalMenuItem> getFunctionalMenuItemsForNotificationTree(Boolean all); + List<FunctionalMenuItem> getFunctionalMenuItemsForApp (Integer appId); + List<FunctionalMenuItem> getFunctionalMenuItemsForUser (String orgUserId); + FunctionalMenuItem getFunctionalMenuItemDetails (Integer menuid); + FieldsValidator createFunctionalMenuItem (FunctionalMenuItemWithRoles menuItemJson); + FieldsValidator editFunctionalMenuItem (FunctionalMenuItemWithRoles menuItemJson); + FieldsValidator deleteFunctionalMenuItem (Long menuId); + FieldsValidator regenerateAncestorTable (); + //Methods relevant to favorites + FieldsValidator setFavoriteItem(FavoritesFunctionalMenuItem menuItemJson); + List<FavoritesFunctionalMenuItemJson> getFavoriteItems(Long userId); + FieldsValidator removeFavoriteItem (Long userId, Long menuId); + List<FunctionalMenuItem> transformFunctionalMenuItemWithAppIDToFunctionalMenuItem(List<FunctionalMenuItemWithAppID> functionalMenuItemWithAppIDList); + List<FunctionalMenuRole> getFunctionalMenuRole(); + //Assign URLs under Help Menu + void assignHelpURLs(List<FunctionalMenuItem> menuItems); + List<BusinessCardApplicationRole> getUserAppRolesList(String userId); +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImpl.java index a6a11209..6a71bc71 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImpl.java @@ -1,963 +1,963 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.annotation.PostConstruct;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.lang3.StringUtils;
-import org.hibernate.Criteria;
-import org.hibernate.Query;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.Transaction;
-import org.hibernate.criterion.Projections;
-import org.hibernate.criterion.Restrictions;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.stereotype.Service;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.FunctionalMenuItemWithAppID;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRole;
-import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItem;
-import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuItemWithRoles;
-import org.openecomp.portalapp.portal.transport.FunctionalMenuRole;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-
-@Service("functionalMenuService")
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class FunctionalMenuServiceImpl implements FunctionalMenuService {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuServiceImpl.class);
-
- private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
- private String RESTRICTED_APP_ROLE_ID = "900";
-
- @Autowired
- private DataAccessService dataAccessService;
- @Autowired
- private SessionFactory sessionFactory;
-
- @PostConstruct
- private void init() {
- try {
- ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
- RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID);
- } catch(Exception e) {
- }
- }
-
- public List<FunctionalMenuItem> getFunctionalMenuItems(EPUser user) {
- List<FunctionalMenuItem> menuItems = new ArrayList<FunctionalMenuItem>();
- return menuItems;
- }
-
- public List<FunctionalMenuItem> getFunctionalMenuItems() {
- return getFunctionalMenuItems(false);
- }
-
- public List<FunctionalMenuItem> getFunctionalMenuItems(Boolean all) {
- // Divide this into 2 queries: one which returns the bottom-level menu items associated with Restricted apps,
- // and one that returns all the other menu items. Then we can easily add the boolean flag
- // restrictedApp to each FunctionalMenuItem, to be used by the front end.
- String activeWhereClause = "";
- if (! all) {
- activeWhereClause = " AND UPPER(m.active_yn) = 'Y' ";
- }
- String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn, r.app_id "
- + "FROM fn_menu_functional m, fn_menu_functional_roles r "
- + "WHERE m.menu_id = r.menu_id "
- + activeWhereClause //" AND UPPER(m.active_yn) = 'Y' "
- + " AND r.role_id != '" + RESTRICTED_APP_ROLE_ID + "' "
- + " UNION "
- + " SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn,-1 app_id "
- + " FROM fn_menu_functional m "
- + " WHERE m.url='' "
- + activeWhereClause; //" AND UPPER(m.active_yn) = 'Y' ";
- logQuery(sql);
-
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItemWithAppID> menuItemsWithAppIdList = dataAccessService.executeSQLQuery(sql,FunctionalMenuItemWithAppID.class, null);
- List<FunctionalMenuItem> menuItems = new ArrayList<>();
- menuItems = transformFunctionalMenuItemWithAppIDToFunctionalMenuItem(menuItemsWithAppIdList);
- for (FunctionalMenuItem menuItem : menuItems) {
- menuItem.restrictedApp = false;
- }
-
- sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn, r.app_id "
- + "FROM fn_menu_functional m, fn_menu_functional_roles r "
- + "WHERE m.menu_id = r.menu_id "
- + activeWhereClause //" AND UPPER(m.active_yn) = 'Y' "
- + " AND r.role_id = '" + RESTRICTED_APP_ROLE_ID + "' ";
- logQuery(sql);
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItem> menuItems2 = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
- for (FunctionalMenuItem menuItem : menuItems2) {
- menuItem.restrictedApp = true;
- menuItems.add(menuItem);
- }
-
- return menuItems;
- }
-
-
- public List<FunctionalMenuItem> getFunctionalMenuItemsForNotificationTree(Boolean all) {
- // Divide this into 2 queries: one which returns the bottom-level menu items associated with Restricted apps,
- // and one that returns all the other menu items which are active. Then we can easily add the boolean flag
- // restrictedApp to each FunctionalMenuItem, to be used by the front end.
- String activeWhereClause = "";
- if (! all) {
- activeWhereClause = " AND UPPER(m.active_yn) = 'Y' ";
- }
- String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn, r.app_id "
- + "FROM fn_menu_functional m, fn_menu_functional_roles r "
- + "WHERE m.menu_id = r.menu_id "
- + activeWhereClause + " AND UPPER(m.active_yn) = 'Y' "
- + " AND r.role_id != '" + RESTRICTED_APP_ROLE_ID + "' "
- + " UNION "
- + " SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn,-1 app_id "
- + " FROM fn_menu_functional m "
- + " WHERE m.url='' "
- + activeWhereClause + " AND UPPER(m.active_yn) = 'Y' ";
- logQuery(sql);
-
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItemWithAppID> menuItemsWithAppIdList = dataAccessService.executeSQLQuery(sql,FunctionalMenuItemWithAppID.class, null);
- List<FunctionalMenuItem> menuItems = new ArrayList<>();
- menuItems = transformFunctionalMenuItemWithAppIDToFunctionalMenuItem(menuItemsWithAppIdList);
- for (FunctionalMenuItem menuItem : menuItems) {
- menuItem.restrictedApp = false;
- }
-
- sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn, r.app_id "
- + "FROM fn_menu_functional m, fn_menu_functional_roles r "
- + "WHERE m.menu_id = r.menu_id "
- + activeWhereClause + " AND UPPER(m.active_yn) = 'Y' "
- + " AND r.role_id = '" + RESTRICTED_APP_ROLE_ID + "' ";
- logQuery(sql);
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItem> menuItems2 = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
- for (FunctionalMenuItem menuItem : menuItems2) {
- menuItem.restrictedApp = true;
- menuItems.add(menuItem);
- }
-
- return menuItems;
- }
-
- public List<FunctionalMenuItem> getFunctionalMenuItemsForApp(Integer appId) {
- String sql = "SELECT DISTINCT m1.menu_id, m1.column_num, m1.text, m1.parent_menu_id, m1.url, m.active_yn "
- + " FROM fn_menu_functional m, fn_menu_functional m1, fn_menu_functional_ancestors a, fn_menu_functional_roles mr "
- + " WHERE " + " mr.app_id='" + appId + "' " + " AND mr.menu_id = m.menu_id " + " AND UPPER(m.active_yn) = 'Y'"
- + " AND UPPER(m1.active_yn) ='Y'" + " AND a.menu_id = m.menu_id " + " AND a.ancestor_menu_id = m1.menu_id";
- logQuery(sql);
- logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuItemsForApp: logged the query");
-
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
-
- return menuItems;
- }
- /**
- * convert List of FunctionalMenuItemWithAppID into List of FunctionalMenuItem
- *
- */
- public List<FunctionalMenuItem> transformFunctionalMenuItemWithAppIDToFunctionalMenuItem(List<FunctionalMenuItemWithAppID> functionalMenuItemWithAppIDList) {
- List<FunctionalMenuItem> functionalMenuItemList = new ArrayList<FunctionalMenuItem>();
- for (FunctionalMenuItemWithAppID functionalMenuItemWithAppID : functionalMenuItemWithAppIDList) {
- FunctionalMenuItem menuItem = new FunctionalMenuItem();
- menuItem.menuId=functionalMenuItemWithAppID.menuId;
- menuItem.column=functionalMenuItemWithAppID.column;
- menuItem.text=functionalMenuItemWithAppID.text;
- menuItem.parentMenuId=functionalMenuItemWithAppID.parentMenuId;
- menuItem.url=functionalMenuItemWithAppID.url;
- menuItem.active_yn=functionalMenuItemWithAppID.active_yn;
- menuItem.appid=functionalMenuItemWithAppID.appid;
- menuItem.setRoles(functionalMenuItemWithAppID.roles);
- menuItem.restrictedApp=functionalMenuItemWithAppID.restrictedApp;
- functionalMenuItemList.add(menuItem);
- }
- return functionalMenuItemList;
- }
-
- public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(String orgUserId) {
- // m represents the functional menu items that are the leaf nodes
- // m1 represents the functional menu items for all the nodes
-
- // Divide this into 2 queries: one which returns the bottom-level menu items associated with Restricted apps,
- // and one that returns all the other menu items. Then we can easily add the boolean flag
- // restrictedApp to each FunctionalMenuItem, to be used by the front end.
- String sql = "SELECT DISTINCT m1.menu_id, m1.column_num, m1.text, m1.parent_menu_id, m1.url, m.active_yn "
- + " FROM fn_menu_functional m, fn_menu_functional m1, fn_menu_functional_ancestors a, "
- + " fn_menu_functional_roles mr, fn_user u , fn_user_role ur " + " WHERE " + " u.org_user_id='" + orgUserId
- + "' " + " AND u.user_id = ur.user_id " + " AND ur.app_id = mr.app_id " +
- // " AND ur.role_id = mr.role_id " +
- " AND (ur.role_id = mr.role_id " + " OR ur.role_id = '" + ACCOUNT_ADMIN_ROLE_ID + "') "
- + " AND m.menu_id = mr.menu_id " + " AND UPPER(m.active_yn) = 'Y'" + " AND UPPER(m1.active_yn) ='Y' "
- + " AND a.menu_id = m.menu_id " + " AND a.ancestor_menu_id = m1.menu_id "
- + " UNION "
- // the ancestors of the restricted app menu items
- + " select m1.menu_id, m1.column_num, m1.text, m1.parent_menu_id, m1.url, m1.active_yn "
- + " FROM fn_menu_functional m, fn_menu_functional_roles mr, fn_menu_functional m1, "
- + " fn_menu_functional_ancestors a "
- + " where a.menu_id = m.menu_id "
- + " AND a.ancestor_menu_id = m1.menu_id "
- + " AND m.menu_id != m1.menu_id "
- + " AND m.menu_id = mr.menu_id "
- + " AND mr.role_id = '" + RESTRICTED_APP_ROLE_ID + "' "
- + " AND UPPER(m.active_yn) = 'Y'" + " AND UPPER(m1.active_yn) ='Y' "
- // Add the Favorites menu item
- + " UNION "
- + " SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
- + " FROM fn_menu_functional m "
- + " WHERE m.text in ('Favorites','Get Access','Contact Us','Support','User Guide','Help')";
-
- logQuery(sql);
- logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuItemsForUser: logged the query");
-
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
- for (FunctionalMenuItem menuItem : menuItems) {
- menuItem.restrictedApp = false;
- }
-
- sql = " SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
- + " FROM fn_menu_functional m, fn_menu_functional_roles r "
- + " WHERE m.menu_id = r.menu_id "
- + " AND UPPER(m.active_yn) = 'Y' "
- + " AND r.role_id = '" + RESTRICTED_APP_ROLE_ID + "' ";
- logQuery(sql);
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItem> menuItems2 = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
- for (FunctionalMenuItem menuItem : menuItems2) {
- menuItem.restrictedApp = true;
- menuItems.add(menuItem);
- }
-
- return menuItems;
- }
-
- public FunctionalMenuItem getFunctionalMenuItemDetails(Integer menuid) {
- // First, fill in the fields that apply to all menu items
-
- String sql = "SELECT * FROM fn_menu_functional WHERE menu_id = '" + menuid + "'";
- logQuery(sql);
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
- FunctionalMenuItem menuItem = (menuItems == null || menuItems.isEmpty() ? null : menuItems.get(0));
- // If it is a bottom-level menu item, must fill in the appid and the
- // roles
- sql = "SELECT * FROM fn_menu_functional_roles WHERE menu_id = '" + menuid + "'";
- logQuery(sql);
- @SuppressWarnings("unchecked")
- List<FunctionalMenuRole> roleItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuRole.class, null);
- if (roleItems.size() > 0) {
- Integer appid = roleItems.get(0).appId;
- menuItem.appid = appid;
- List<Integer> roles = new ArrayList<Integer>();
- for (FunctionalMenuRole roleItem : roleItems) {
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: app_id: " + roleItem.appId + "; role_id: " + roleItem.roleId + "\n");
- roles.add(roleItem.roleId);
- }
- menuItem.setRoles(roles);
- }
-
- return menuItem;
- }
-
- private FieldsValidator menuItemFieldsChecker(FunctionalMenuItemWithRoles menuItemJson) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- try {
- // TODO: validate all the fields
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItem> functionalMenuItems = dataAccessService.getList(FunctionalMenuItem.class,
- " where text = '" + menuItemJson.text + "'", null, null);
-
- boolean dublicatedName = false;
- for (FunctionalMenuItem fnMenuItem : functionalMenuItems) {
- if (menuItemJson.menuId != null && menuItemJson.menuId.equals(fnMenuItem.menuId)) {
- // FunctionalMenuItem should not be compared with itself
- continue;
- }
-
- if (!dublicatedName && fnMenuItem.text.equalsIgnoreCase(menuItemJson.text)) {
- dublicatedName = true;
- break;
- }
- }
- if (dublicatedName) {
- fieldsValidator.addProblematicFieldName("text");
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
- fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
- logger.debug(EELFLoggerDelegate.debugLogger, "In menuItemFieldsChecker, Error: we have an duplicate text field");
- } else if (StringUtils.isEmpty(menuItemJson.text) && menuItemJson.menuId == null) {
- // text must be non empty for a create. For an edit, can be empty, which means it is a move request.
- // a null menuId indicates a create.
- fieldsValidator.addProblematicFieldName("text");
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
- logger.debug(EELFLoggerDelegate.debugLogger, "In menuItemFieldsChecker, Error: we have an empty text field");
- } else {
- // The url, appid, and roles must either be all filled or all empty.
- Boolean urlIsEmpty = StringUtils.isEmpty(menuItemJson.url);
- Boolean rolesIsEmpty = menuItemJson.getRoles() == null || menuItemJson.getRoles().isEmpty();
- Boolean appidIsEmpty = menuItemJson.appid == null || menuItemJson.appid == 0;
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: menuItemfieldsChecker: urlIsEmpty: " + urlIsEmpty + "; rolesIsEmpty: " + rolesIsEmpty + "; appidIsEmpty: " + appidIsEmpty +"\n");
- if (!((urlIsEmpty && rolesIsEmpty && appidIsEmpty) || (!urlIsEmpty && !rolesIsEmpty && !appidIsEmpty)))
- {
- fieldsValidator.addProblematicFieldName("url,roles,appid");
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
- logger.debug(EELFLoggerDelegate.debugLogger, "In menuItemFieldsChecker, Error: we don't have: either all 3 fields empty or all 3 fields nonempty");
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "In menuItemFieldsChecker, Success: either all 3 fields empty or all 3 fields nonempty");
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while validating the FunctionalMenuItems. Details: " + EcompPortalUtils.getStackTrace(e));
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
-
- return fieldsValidator;
- }
-
- // Turn foreign key checks on or off
- protected void setForeignKeys(Session localSession, Boolean on) {
- String keyCheck = "0";
- if (on) {
- keyCheck = "1";
- }
- String sql = "set FOREIGN_KEY_CHECKS="+keyCheck;
- logQuery(sql);
- Query query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- }
-
- public FieldsValidator createFunctionalMenuItem(FunctionalMenuItemWithRoles menuItemJson) {
- FieldsValidator fieldsValidator = menuItemFieldsChecker(menuItemJson);
- if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: createFunctionalMenuItem: test 1");
- boolean result = false;
- Session localSession = null;
- Transaction transaction = null;
- try {
- FunctionalMenuItem menuItem = new FunctionalMenuItem();
- menuItem.appid = menuItemJson.appid;
- menuItem.setRoles(menuItemJson.getRoles());
- menuItem.url = menuItemJson.url;
- menuItem.text = menuItemJson.text;
- menuItem.parentMenuId = menuItemJson.parentMenuId;
- menuItem.active_yn = "Y";
- localSession = sessionFactory.openSession();
-
- // If the app is disabled, deactivate the menu item.
- if (menuItemJson.appid != null) {
- Long appidLong = Long.valueOf(menuItemJson.appid);
- EPApp app = (EPApp) localSession.get(EPApp.class, appidLong);
- if (app != null && ! app.getEnabled()) {
- menuItem.active_yn = "N";
- }
- }
-
- // Set the column number to 1 higher than the highest column
- // number under this parent.
- Criteria criteria = localSession.createCriteria(FunctionalMenuItem.class);
- criteria.setProjection(Projections.max("column"));
- criteria.add(Restrictions.eq("parentMenuId", menuItem.parentMenuId));
- Integer maxColumn = (Integer) criteria.uniqueResult();
- if (maxColumn == null) {
- maxColumn = 0;
- }
- menuItem.column = maxColumn + 1;
- logger.debug(EELFLoggerDelegate.debugLogger, "about to create menu item: " + menuItem.toString());
-
- transaction = localSession.beginTransaction();
- // localSession.saveOrUpdate(newMenuItem);
- localSession.save(menuItem);
- Long menuid = menuItem.menuId;
- menuItemJson.menuId = menuid;
- logger.debug(EELFLoggerDelegate.debugLogger, "after saving menu object, new id: " + menuid);
-
- // Next, save all the roles
-
- addRoles(menuItemJson, localSession);
- transaction.commit();
- result = true;
- } catch (Exception e) {
- EcompPortalUtils.rollbackTransaction(transaction,
- "createFunctionalMenuItem rollback, exception = " + e);
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "createFunctionalMenuItem");
- }
- if (result) {
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: createFunctionalMenuItem: no result. setting httpStatusCode to "
- + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- } else {
- logger.error(EELFLoggerDelegate.errorLogger, "FunctionalMenuServiceImpl.createFunctionalMenuItem: bad request");
- }
- return fieldsValidator;
- }
-
- /* Add all the roles in the menu item to the database */
- public void addRoles(FunctionalMenuItemWithRoles menuItemJson, Session localSession) {
- logger.debug(EELFLoggerDelegate.debugLogger, "entering addRoles.");
- List<Integer> roles = menuItemJson.getRoles();
- if (roles != null && roles.size() > 0) {
- Integer appid = menuItemJson.appid;
- Long menuid = menuItemJson.menuId;
- for (Integer roleid : roles) {
- logger.debug(EELFLoggerDelegate.debugLogger, "about to create record for role: " + roleid);
- FunctionalMenuRole role = new FunctionalMenuRole();
- role.appId = appid;
- role.menuId = menuid;
- role.roleId = roleid;
- localSession.save(role);
- logger.debug(EELFLoggerDelegate.debugLogger, "after saving role menu object, new id: " + role.id);
- }
- }
- }
-
- /* Delete all the roles associated with the menu item from the database */
- public void deleteRoles(Long menuId) {
- dataAccessService.deleteDomainObjects(FunctionalMenuRole.class, "menu_id='" + menuId + "'", null);
- }
-
- /* Delete all favorites associated with the menu item from the database */
- public void deleteFavorites(Long menuId) {
- dataAccessService.deleteDomainObjects(FavoritesFunctionalMenuItem.class, "menu_id='" + menuId + "'", null);
- }
-
- private Boolean parentMenuIdEqual(Integer menuId1, Integer menuId2) {
- return ((menuId1 == null && menuId2 == null) || (menuId1 != null && menuId1.equals(menuId2)));
- }
-
- private void updateColumnForSiblings(Session localSession, Long menuId, Integer oldParentMenuId,
- Integer newParentMenuId, Integer oldColumn, Integer newColumn) {
- logger.debug(EELFLoggerDelegate.debugLogger, "entering updateColumnForSiblings");
- Criteria criteria = localSession.createCriteria(FunctionalMenuItem.class);
- criteria.add(Restrictions.ne("menuId", menuId));
- if (parentMenuIdEqual(oldParentMenuId, newParentMenuId)) {
- logger.debug(EELFLoggerDelegate.debugLogger, "moving under the same parent");
- // We are moving to a new position under the same parent
- if (newParentMenuId == null) {
- logger.debug(EELFLoggerDelegate.debugLogger, "newParentMenuId is null, so using isNull");
- criteria.add(Restrictions.isNull("parentMenuId"));
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "newParentMenuId is NOT null, so using eq");
- criteria.add(Restrictions.eq("parentMenuId", newParentMenuId));
- }
- if (oldColumn > newColumn) {
- logger.debug(EELFLoggerDelegate.debugLogger, "moving to a lower column under the same parent");
- // We are moving to a lower column under the same parent
- criteria.add(Restrictions.ge("column", newColumn));
- criteria.add(Restrictions.lt("column", oldColumn));
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItem> menuItems = criteria.list();
- for (FunctionalMenuItem menuItem : menuItems) {
- menuItem.column += 1;
- localSession.save(menuItem);
- }
- } else if (oldColumn < newColumn) {
- logger.debug(EELFLoggerDelegate.debugLogger, "moving to a higher column under the same parent");
- // We are moving to a higher column under the same parent
- criteria.add(Restrictions.gt("column", oldColumn));
- criteria.add(Restrictions.le("column", newColumn));
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItem> menuItems = criteria.list();
- for (FunctionalMenuItem menuItem : menuItems) {
- menuItem.column -= 1;
- localSession.save(menuItem);
- }
- } else {
- // No info has changed
- logger.debug(EELFLoggerDelegate.debugLogger, "no info has changed, so we are not moving");
- }
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "moving under a new parent");
- // We are moving under a new parent.
-
- // Adjust the children under the old parent
- logger.debug(EELFLoggerDelegate.debugLogger, "about to adjust the children under the old parent");
-
- // If the parentId is null, must check for its children differently
- if (oldParentMenuId == null) {
- logger.debug(EELFLoggerDelegate.debugLogger, "oldParentMenuId is null, so using isNull");
- criteria.add(Restrictions.isNull("parentMenuId"));
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "oldParentMenuId is NOT null, so using eq");
- criteria.add(Restrictions.eq("parentMenuId", oldParentMenuId));
- }
-
- criteria.add(Restrictions.gt("column", oldColumn));
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItem> menuItems1 = criteria.list();
- for (FunctionalMenuItem menuItem : menuItems1) {
- menuItem.column -= 1;
- localSession.save(menuItem);
- }
- // Adjust the children under the new parent.
- logger.debug(EELFLoggerDelegate.debugLogger, "about to adjust the children under the new parent");
- logger.debug(EELFLoggerDelegate.debugLogger, "get all menu items where menuId!=" + menuId + "; parentMenuId==" + newParentMenuId
- + "; column>=" + newColumn);
- criteria = localSession.createCriteria(FunctionalMenuItem.class);
- criteria.add(Restrictions.ne("menuId", menuId));
- if (newParentMenuId == null) {
- logger.debug(EELFLoggerDelegate.debugLogger, "newParentMenuId is null, so using isNull");
- criteria.add(Restrictions.isNull("parentMenuId"));
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "newParentMenuId is NOT null, so using eq");
- criteria.add(Restrictions.eq("parentMenuId", newParentMenuId));
- }
-
- criteria.add(Restrictions.ge("column", newColumn));
- @SuppressWarnings("unchecked")
- List<FunctionalMenuItem> menuItems2 = criteria.list();
- if (menuItems2 != null) {
- logger.debug(EELFLoggerDelegate.debugLogger, "found " + menuItems2.size() + " menu items");
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "found null menu items");
- }
- for (FunctionalMenuItem menuItem : menuItems2) {
- menuItem.column += 1;
- localSession.save(menuItem);
- }
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "done with updateColumnForSiblings");
- }
-
- public void removeAppInfo(Session localSession, Long menuId) {
- // Remove the url, role, and app info from a menu item
- FunctionalMenuItem menuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class, menuId);
- menuItem.url = "";
- deleteRoles(menuId);
- }
-
- public FieldsValidator editFunctionalMenuItem(FunctionalMenuItemWithRoles menuItemJson) {
- boolean result = false;
- Session localSession = null;
- Transaction transaction = null;
- Long menuId = menuItemJson.menuId;
-
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: editFunctionalMenuItem: test 1");
- FieldsValidator fieldsValidator = menuItemFieldsChecker(menuItemJson);
- if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- // TODO: make sure menuId is here. And, it might not already exist
- // in db table.
- if (menuId == null) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
- logger.error(EELFLoggerDelegate.errorLogger, "FunctionalMenuServiceImpl.editFunctionalMenuItem: bad request");
- } else {
- // To simplify the code, assume we will have a transaction
- try {
- localSession = sessionFactory.openSession();
- transaction = localSession.beginTransaction();
-
- // Get the existing info associated with menuItem from the DB
- FunctionalMenuItem menuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class, menuId);
- Integer oldColumn = menuItem.column;
- Integer oldParentMenuId = menuItem.parentMenuId;
- Integer newColumn = menuItemJson.column;
- Integer newParentMenuId = menuItemJson.parentMenuId;
-
- logger.debug(EELFLoggerDelegate.debugLogger, "prev info: column: " + oldColumn + "; parentMenuId: " + oldParentMenuId);
-
- if (menuItemJson.appid != null && menuItemJson.getRoles() != null && !menuItemJson.getRoles().isEmpty()
- && menuItemJson.url != null && !menuItemJson.url.isEmpty() && menuItemJson.text != null
- && !menuItemJson.text.isEmpty()) {
- // Scenario: appid, roles, url and text are all non-null.
- // This menu item is associated with an app.
- // (Note: this should only occur for a bottom-level menu
- // item with no children.)
- // 1) Remove all the records from fn_menu_functional_role
- // for this menuId.
- // 2) Add records to the fn_menu_function_role table for the
- // appId and each roleId
- // 3) Update the url and text for this menu item.
-
- // Because of foreign key constraints, delete the roles,
- // then update the menuItem then add the roles.
- deleteRoles(menuId);
- // Assumption: this is not a Move, so don't change the
- // parentMenuId and column.
- menuItem.appid = menuItemJson.appid;
- menuItem.setRoles(menuItemJson.getRoles());
- menuItem.url = menuItemJson.url;
- menuItem.text = menuItemJson.text;
-
- // If the app is disabled, deactivate the menu item.
- Long appidLong = Long.valueOf(menuItemJson.appid);
- EPApp app = (EPApp) localSession.get(EPApp.class, appidLong);
- if (app != null && ! app.getEnabled()) {
- menuItem.active_yn = "N";
- } else {
- menuItem.active_yn = "Y";
- }
-
-
- localSession.update(menuItem);
- addRoles(menuItemJson, localSession);
-
- } else if (menuItemJson.appid == null && (menuItemJson.getRoles() == null || menuItemJson.getRoles().isEmpty())
- && (menuItemJson.url == null || menuItemJson.url.isEmpty()) && menuItemJson.text != null
- && !menuItemJson.text.isEmpty()) {
- // Scenario: appid, roles and url are all null; text is
- // non-null.
- // This menu item is NOT associated with an app.
- // 1) Remove all the records from fn_menu_functional_role
- // for this menuId
- // (in case it was previously associated with an app).
- // 2) Update the text for this menu item.
- // 3) Set the url to ""
- deleteRoles(menuId);
- // Assumption: this is not a Move, so don't change the
- // parentMenuId and column.
- menuItem.text = menuItemJson.text;
- menuItem.url = "";
- menuItem.active_yn = "Y";
- localSession.update(menuItem);
-
- } else if (newColumn != null) {
- // This is a "move" request.
- // Menu item has been moved to a different position under
- // the same parent, or under a new parent.
- logger.debug(EELFLoggerDelegate.debugLogger, "Doing a move operation.");
- if (parentMenuIdEqual(oldParentMenuId, newParentMenuId)) {
- // The parent is the same. We have just changed the
- // column
- logger.debug(EELFLoggerDelegate.debugLogger, "moving under the same parent");
- menuItem.column = newColumn;
- localSession.update(menuItem);
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "moving under a different parent");
- menuItem.parentMenuId = newParentMenuId;
- menuItem.column = newColumn;
- localSession.update(menuItem);
- // If we are moving under a new parent, must delete any
- // app/role info from
- // the new parent, since it is no longer a leaf menu
- // item and cannot have app info
- // associated with it. The front end will have warned
- // the user and gotten confirmation.
- if (menuItemJson.parentMenuId != null) {
- Long parentMenuIdLong = new Long(menuItemJson.parentMenuId);
- removeAppInfo(localSession, parentMenuIdLong);
- // deleteRoles(parentMenuIdLong);
- }
- }
- // must update the column for all old and new sibling menu
- // items
- updateColumnForSiblings(localSession, menuId, oldParentMenuId, newParentMenuId, oldColumn,
- newColumn);
- }
-
- transaction.commit();
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: editFunctionalMenuItem: finished committing transaction");
- result = true;
- } catch (Exception e) {
- EcompPortalUtils.rollbackTransaction(transaction,
- "createFunctionalMenuItem rollback, exception = " + e);
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "editFunctionalMenuItem");
- }
-
- if (result) {
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: createFunctionalMenuItem: no result. setting httpStatusCode to "
- + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- }
- }
-
- return fieldsValidator;
- }
-
- public FieldsValidator deleteFunctionalMenuItem(Long menuId) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: deleteFunctionalMenuItem: test 1");
- boolean result = false;
- Session localSession = null;
- Transaction transaction = null;
-
- try {
- localSession = sessionFactory.openSession();
- transaction = localSession.beginTransaction();
- // We must turn off foreign keys before deleting a menu item. Otherwise there will be a
- // constraint violation from the ancestors table.
- setForeignKeys(localSession, false);
- deleteRoles(menuId);
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteFunctionalMenuItem: after deleting roles");
- deleteFavorites(menuId);
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteFunctionalMenuItem: after deleting favorites");
- localSession.delete(localSession.get(FunctionalMenuItem.class, menuId));
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteFunctionalMenuItem: about to commit");
- transaction.commit();
- result = true;
- } catch (Exception e) {
- EcompPortalUtils.rollbackTransaction(transaction,
- "deleteFunctionalMenuItem rollback, exception = " + e);
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "deleteFunctionalMenuItem");
- }
- if (result) {
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: deleteFunctionalMenuItem: no result. setting httpStatusCode to "
- + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- return fieldsValidator;
- }
-
- // Regenerate the fn_menu_functional_ancestors table, which is used
- // by the queries that return the functional menu items.
- public FieldsValidator regenerateAncestorTable() {
- FieldsValidator fieldsValidator = new FieldsValidator();
- Session localSession = null;
- Transaction transaction = null;
-
- try {
- localSession = sessionFactory.openSession();
- transaction = localSession.beginTransaction();
- String sql = "DELETE FROM fn_menu_functional_ancestors";
- logQuery(sql);
- Query query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- logger.debug(EELFLoggerDelegate.debugLogger, "regenerateAncestorTable: finished query 1");
-
- sql = "ALTER TABLE fn_menu_functional_ancestors AUTO_INCREMENT=1";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- logger.debug(EELFLoggerDelegate.debugLogger, "regenerateAncestorTable: reset AUTO_INCREMENT to 1");
-
- int depth = 0;
- sql = "INSERT INTO fn_menu_functional_ancestors(menu_id, ancestor_menu_id, depth) "
- + "SELECT m.menu_id, m.menu_id, " + depth + " FROM fn_menu_functional m";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- logger.debug(EELFLoggerDelegate.debugLogger, "regenerateAncestorTable: finished query 2");
- for (depth = 0; depth < 3; depth++) {
- int depthPlusOne = depth + 1;
- sql = "INSERT INTO fn_menu_functional_ancestors(menu_id, ancestor_menu_id, depth) "
- + " SELECT a.menu_id, m.parent_menu_id, " + depthPlusOne
- + " FROM fn_menu_functional m, fn_menu_functional_ancestors a " + " WHERE a.depth='" + depth
- + "' AND " + " a.ancestor_menu_id = m.menu_id AND " + " m.parent_menu_id != '-1'";
- logQuery(sql);
- query = localSession.createSQLQuery(sql);
- query.executeUpdate();
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "regenerateAncestorTable: finished query 3");
- transaction.commit();
- } catch (Exception e) {
- EcompPortalUtils.rollbackTransaction(transaction,
- "regenerateAncestorTable rollback, exception = " + e);
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "regenerateAncestorTable");
- }
- return fieldsValidator;
- }
-
- private void logQuery(String sql) {
- logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
- }
-
- public FieldsValidator setFavoriteItem(FavoritesFunctionalMenuItem menuItemJson) {
- boolean result = false;
- FieldsValidator fieldsValidator = new FieldsValidator();
-
- Session localSession = null;
- Transaction transaction = null;
-
- try {
- logger.debug(EELFLoggerDelegate.debugLogger, String.format("Before adding favorite for user id:{0} and menu id:{1} ",menuItemJson.userId,menuItemJson.menuId));
- localSession = sessionFactory.openSession();
- transaction = localSession.beginTransaction();
- localSession.save(menuItemJson);
- transaction.commit();
- result = true;
- logger.debug(EELFLoggerDelegate.debugLogger, String.format("After adding favorite for user id:{0} and menu id:{1} ",menuItemJson.userId,menuItemJson.menuId));
- } catch (Exception e) {
- EcompPortalUtils.rollbackTransaction(transaction,"setFavoriteItem rollback, exception = " + e);
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "setFavoriteItem");
- }
-
- if(result) {
- }
- else {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
-
- return fieldsValidator;
- }
-
- public List<FavoritesFunctionalMenuItemJson> getFavoriteItems(Long userId) {
- try {
- logger.debug(EELFLoggerDelegate.debugLogger, "Before getting favorites for user id: " + userId);
-
- // Divide this into 2 queries: one which returns the favorites items associated with Restricted apps,
- // and one that returns all the other favorites items. Then we can easily add the boolean flag
- // restrictedApp to each FavoritesFunctionalMenuItemJson, to be used by the front end.
-
- String sql = "SELECT f.user_id,f.menu_id,m.text,m.url "
- + " FROM fn_menu_favorites f, fn_menu_functional m, fn_menu_functional_roles mr "
- + " WHERE f.user_id='" + userId + "' AND f.menu_id = m.menu_id "
- + " AND f.menu_id = mr.menu_id "
- + " AND mr.role_id = '" + RESTRICTED_APP_ROLE_ID + "' ";
-
- @SuppressWarnings("unchecked")
- List<FavoritesFunctionalMenuItemJson> menuItems = dataAccessService.executeSQLQuery(sql, FavoritesFunctionalMenuItemJson.class, null);
- for (FavoritesFunctionalMenuItemJson menuItem : menuItems) {
- menuItem.restrictedApp = true;
- }
-
- sql = "SELECT DISTINCT f.user_id,f.menu_id,m.text,m.url "
- + " FROM fn_menu_favorites f, fn_menu_functional m, fn_menu_functional_roles mr "
- + " WHERE f.user_id='" + userId + "' AND f.menu_id = m.menu_id "
- + " AND f.menu_id = mr.menu_id "
- + " AND mr.role_id != '" + RESTRICTED_APP_ROLE_ID + "' ";
- @SuppressWarnings("unchecked")
- List<FavoritesFunctionalMenuItemJson> menuItems2 = dataAccessService.executeSQLQuery(sql, FavoritesFunctionalMenuItemJson.class, null);
- for (FavoritesFunctionalMenuItemJson menuItem : menuItems2) {
- menuItem.restrictedApp = false;
- menuItems.add(menuItem);
- }
-
- return menuItems;
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in FunctionalMenuServiceImpl.getFavoriteItems. Details: " + EcompPortalUtils.getStackTrace(e));
- List<FavoritesFunctionalMenuItemJson> menuItems = new ArrayList<FavoritesFunctionalMenuItemJson>();
- return menuItems;
- }
- }
-
- public FieldsValidator removeFavoriteItem(Long userId, Long menuId) {
- boolean result = false;
- FieldsValidator fieldsValidator = new FieldsValidator();
-
- Session localSession = null;
- Transaction transaction = null;
-
- try {
-
- FavoritesFunctionalMenuItem menuItemJson = new FavoritesFunctionalMenuItem();
- menuItemJson.userId = userId;
- menuItemJson.menuId = menuId;
-
- localSession = sessionFactory.openSession();
- transaction = localSession.beginTransaction();
- localSession.delete(menuItemJson);
- localSession.flush();
- transaction.commit();
- result = true;
- logger.debug(EELFLoggerDelegate.debugLogger, String.format("After removing favorite for user id: " + userId + "; menu id: " + menuId));
- } catch (Exception e) {
- EcompPortalUtils.rollbackTransaction(transaction,"removeFavoriteItem rollback, exception = " + e);
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "removeFavoriteItem");
- }
-
- if(result) {
- }
- else {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
-
- return fieldsValidator;
- }
-
- @Override
- public void assignHelpURLs(List<FunctionalMenuItem> menuItems) {
- try {
- String user_guide_link = SystemProperties.getProperty(EPCommonSystemProperties.USER_GUIDE_URL);
-
- for(FunctionalMenuItem menuItem: menuItems){
- if(menuItem.text.equalsIgnoreCase("Contact Us")){
- menuItem.setUrl("contactUs");
- //menuItem.setRestrictedApp(true);
- }
- if(menuItem.text.equalsIgnoreCase("Get Access")) {
- menuItem.setUrl("getAccess");
- }
- if(menuItem.text.equalsIgnoreCase("User Guide")) {
- menuItem.setUrl(user_guide_link);
- menuItem.setRestrictedApp(true);
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "assignHelpURLs process failed. Details: " + EcompPortalUtils.getStackTrace(e));
- }
-
- }
-
- public List<FunctionalMenuRole> getFunctionalMenuRole() {
- String sql = "SELECT * from fn_menu_functional_roles";
- logQuery(sql);
- logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuRole: logged the query");
-
- @SuppressWarnings("unchecked")
- List<FunctionalMenuRole> functionalMenuRole = dataAccessService.executeSQLQuery(sql, FunctionalMenuRole.class, null);
-
- return functionalMenuRole;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<BusinessCardApplicationRole> getUserAppRolesList(String userId) {
- Map<String, String> params = new HashMap<>();
- params.put("userId", userId);
-
- List<BusinessCardApplicationRole> userAppRoles = null;
- try {
- userAppRoles = dataAccessService
- .executeNamedQuery("getUserApproles", params, null);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- logger.error(EELFLoggerDelegate.errorLogger, "getUserAppRolesList failed", e);
- }
- return userAppRoles;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang3.StringUtils; +import org.hibernate.Criteria; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.FunctionalMenuItemWithAppID; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRole; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItemWithRoles; +import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; + +@Service("functionalMenuService") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class FunctionalMenuServiceImpl implements FunctionalMenuService { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuServiceImpl.class); + + private Long ACCOUNT_ADMIN_ROLE_ID = 999L; + private String RESTRICTED_APP_ROLE_ID = "900"; + + @Autowired + private DataAccessService dataAccessService; + @Autowired + private SessionFactory sessionFactory; + + @PostConstruct + private void init() { + try { + ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID)); + RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPCommonSystemProperties.RESTRICTED_APP_ROLE_ID); + } catch(Exception e) { + } + } + + public List<FunctionalMenuItem> getFunctionalMenuItems(EPUser user) { + List<FunctionalMenuItem> menuItems = new ArrayList<FunctionalMenuItem>(); + return menuItems; + } + + public List<FunctionalMenuItem> getFunctionalMenuItems() { + return getFunctionalMenuItems(false); + } + + public List<FunctionalMenuItem> getFunctionalMenuItems(Boolean all) { + // Divide this into 2 queries: one which returns the bottom-level menu items associated with Restricted apps, + // and one that returns all the other menu items. Then we can easily add the boolean flag + // restrictedApp to each FunctionalMenuItem, to be used by the front end. + String activeWhereClause = ""; + if (! all) { + activeWhereClause = " AND UPPER(m.active_yn) = 'Y' "; + } + String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn, r.app_id " + + "FROM fn_menu_functional m, fn_menu_functional_roles r " + + "WHERE m.menu_id = r.menu_id " + + activeWhereClause //" AND UPPER(m.active_yn) = 'Y' " + + " AND r.role_id != '" + RESTRICTED_APP_ROLE_ID + "' " + + " UNION " + + " SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn,-1 app_id " + + " FROM fn_menu_functional m " + + " WHERE m.url='' " + + activeWhereClause; //" AND UPPER(m.active_yn) = 'Y' "; + logQuery(sql); + + @SuppressWarnings("unchecked") + List<FunctionalMenuItemWithAppID> menuItemsWithAppIdList = dataAccessService.executeSQLQuery(sql,FunctionalMenuItemWithAppID.class, null); + List<FunctionalMenuItem> menuItems = new ArrayList<>(); + menuItems = transformFunctionalMenuItemWithAppIDToFunctionalMenuItem(menuItemsWithAppIdList); + for (FunctionalMenuItem menuItem : menuItems) { + menuItem.restrictedApp = false; + } + + sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn, r.app_id " + + "FROM fn_menu_functional m, fn_menu_functional_roles r " + + "WHERE m.menu_id = r.menu_id " + + activeWhereClause //" AND UPPER(m.active_yn) = 'Y' " + + " AND r.role_id = '" + RESTRICTED_APP_ROLE_ID + "' "; + logQuery(sql); + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> menuItems2 = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null); + for (FunctionalMenuItem menuItem : menuItems2) { + menuItem.restrictedApp = true; + menuItems.add(menuItem); + } + + return menuItems; + } + + + public List<FunctionalMenuItem> getFunctionalMenuItemsForNotificationTree(Boolean all) { + // Divide this into 2 queries: one which returns the bottom-level menu items associated with Restricted apps, + // and one that returns all the other menu items which are active. Then we can easily add the boolean flag + // restrictedApp to each FunctionalMenuItem, to be used by the front end. + String activeWhereClause = ""; + if (! all) { + activeWhereClause = " AND UPPER(m.active_yn) = 'Y' "; + } + String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn, r.app_id " + + "FROM fn_menu_functional m, fn_menu_functional_roles r " + + "WHERE m.menu_id = r.menu_id " + + activeWhereClause + " AND UPPER(m.active_yn) = 'Y' " + + " AND r.role_id != '" + RESTRICTED_APP_ROLE_ID + "' " + + " UNION " + + " SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn,-1 app_id " + + " FROM fn_menu_functional m " + + " WHERE m.url='' " + + activeWhereClause + " AND UPPER(m.active_yn) = 'Y' "; + logQuery(sql); + + @SuppressWarnings("unchecked") + List<FunctionalMenuItemWithAppID> menuItemsWithAppIdList = dataAccessService.executeSQLQuery(sql,FunctionalMenuItemWithAppID.class, null); + List<FunctionalMenuItem> menuItems = new ArrayList<>(); + menuItems = transformFunctionalMenuItemWithAppIDToFunctionalMenuItem(menuItemsWithAppIdList); + for (FunctionalMenuItem menuItem : menuItems) { + menuItem.restrictedApp = false; + } + + sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn, r.app_id " + + "FROM fn_menu_functional m, fn_menu_functional_roles r " + + "WHERE m.menu_id = r.menu_id " + + activeWhereClause + " AND UPPER(m.active_yn) = 'Y' " + + " AND r.role_id = '" + RESTRICTED_APP_ROLE_ID + "' "; + logQuery(sql); + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> menuItems2 = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null); + for (FunctionalMenuItem menuItem : menuItems2) { + menuItem.restrictedApp = true; + menuItems.add(menuItem); + } + + return menuItems; + } + + public List<FunctionalMenuItem> getFunctionalMenuItemsForApp(Integer appId) { + String sql = "SELECT DISTINCT m1.menu_id, m1.column_num, m1.text, m1.parent_menu_id, m1.url, m.active_yn " + + " FROM fn_menu_functional m, fn_menu_functional m1, fn_menu_functional_ancestors a, fn_menu_functional_roles mr " + + " WHERE " + " mr.app_id='" + appId + "' " + " AND mr.menu_id = m.menu_id " + " AND UPPER(m.active_yn) = 'Y'" + + " AND UPPER(m1.active_yn) ='Y'" + " AND a.menu_id = m.menu_id " + " AND a.ancestor_menu_id = m1.menu_id"; + logQuery(sql); + logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuItemsForApp: logged the query"); + + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null); + + return menuItems; + } + /** + * convert List of FunctionalMenuItemWithAppID into List of FunctionalMenuItem + * + */ + public List<FunctionalMenuItem> transformFunctionalMenuItemWithAppIDToFunctionalMenuItem(List<FunctionalMenuItemWithAppID> functionalMenuItemWithAppIDList) { + List<FunctionalMenuItem> functionalMenuItemList = new ArrayList<FunctionalMenuItem>(); + for (FunctionalMenuItemWithAppID functionalMenuItemWithAppID : functionalMenuItemWithAppIDList) { + FunctionalMenuItem menuItem = new FunctionalMenuItem(); + menuItem.menuId=functionalMenuItemWithAppID.menuId; + menuItem.column=functionalMenuItemWithAppID.column; + menuItem.text=functionalMenuItemWithAppID.text; + menuItem.parentMenuId=functionalMenuItemWithAppID.parentMenuId; + menuItem.url=functionalMenuItemWithAppID.url; + menuItem.active_yn=functionalMenuItemWithAppID.active_yn; + menuItem.appid=functionalMenuItemWithAppID.appid; + menuItem.setRoles(functionalMenuItemWithAppID.roles); + menuItem.restrictedApp=functionalMenuItemWithAppID.restrictedApp; + functionalMenuItemList.add(menuItem); + } + return functionalMenuItemList; + } + + public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(String orgUserId) { + // m represents the functional menu items that are the leaf nodes + // m1 represents the functional menu items for all the nodes + + // Divide this into 2 queries: one which returns the bottom-level menu items associated with Restricted apps, + // and one that returns all the other menu items. Then we can easily add the boolean flag + // restrictedApp to each FunctionalMenuItem, to be used by the front end. + String sql = "SELECT DISTINCT m1.menu_id, m1.column_num, m1.text, m1.parent_menu_id, m1.url, m.active_yn " + + " FROM fn_menu_functional m, fn_menu_functional m1, fn_menu_functional_ancestors a, " + + " fn_menu_functional_roles mr, fn_user u , fn_user_role ur " + " WHERE " + " u.org_user_id='" + orgUserId + + "' " + " AND u.user_id = ur.user_id " + " AND ur.app_id = mr.app_id " + + // " AND ur.role_id = mr.role_id " + + " AND (ur.role_id = mr.role_id " + " OR ur.role_id = '" + ACCOUNT_ADMIN_ROLE_ID + "') " + + " AND m.menu_id = mr.menu_id " + " AND UPPER(m.active_yn) = 'Y'" + " AND UPPER(m1.active_yn) ='Y' " + + " AND a.menu_id = m.menu_id " + " AND a.ancestor_menu_id = m1.menu_id " + + " UNION " + // the ancestors of the restricted app menu items + + " select m1.menu_id, m1.column_num, m1.text, m1.parent_menu_id, m1.url, m1.active_yn " + + " FROM fn_menu_functional m, fn_menu_functional_roles mr, fn_menu_functional m1, " + + " fn_menu_functional_ancestors a " + + " where a.menu_id = m.menu_id " + + " AND a.ancestor_menu_id = m1.menu_id " + + " AND m.menu_id != m1.menu_id " + + " AND m.menu_id = mr.menu_id " + + " AND mr.role_id = '" + RESTRICTED_APP_ROLE_ID + "' " + + " AND UPPER(m.active_yn) = 'Y'" + " AND UPPER(m1.active_yn) ='Y' " + // Add the Favorites menu item + + " UNION " + + " SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn " + + " FROM fn_menu_functional m " + + " WHERE m.text in ('Favorites','Get Access','Contact Us','Support','User Guide','Help')"; + + logQuery(sql); + logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuItemsForUser: logged the query"); + + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null); + for (FunctionalMenuItem menuItem : menuItems) { + menuItem.restrictedApp = false; + } + + sql = " SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn " + + " FROM fn_menu_functional m, fn_menu_functional_roles r " + + " WHERE m.menu_id = r.menu_id " + + " AND UPPER(m.active_yn) = 'Y' " + + " AND r.role_id = '" + RESTRICTED_APP_ROLE_ID + "' "; + logQuery(sql); + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> menuItems2 = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null); + for (FunctionalMenuItem menuItem : menuItems2) { + menuItem.restrictedApp = true; + menuItems.add(menuItem); + } + + return menuItems; + } + + public FunctionalMenuItem getFunctionalMenuItemDetails(Integer menuid) { + // First, fill in the fields that apply to all menu items + + String sql = "SELECT * FROM fn_menu_functional WHERE menu_id = '" + menuid + "'"; + logQuery(sql); + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null); + FunctionalMenuItem menuItem = (menuItems == null || menuItems.isEmpty() ? null : menuItems.get(0)); + // If it is a bottom-level menu item, must fill in the appid and the + // roles + sql = "SELECT * FROM fn_menu_functional_roles WHERE menu_id = '" + menuid + "'"; + logQuery(sql); + @SuppressWarnings("unchecked") + List<FunctionalMenuRole> roleItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuRole.class, null); + if (roleItems.size() > 0) { + Integer appid = roleItems.get(0).appId; + menuItem.appid = appid; + List<Integer> roles = new ArrayList<Integer>(); + for (FunctionalMenuRole roleItem : roleItems) { + logger.debug(EELFLoggerDelegate.debugLogger, "LR: app_id: " + roleItem.appId + "; role_id: " + roleItem.roleId + "\n"); + roles.add(roleItem.roleId); + } + menuItem.setRoles(roles); + } + + return menuItem; + } + + private FieldsValidator menuItemFieldsChecker(FunctionalMenuItemWithRoles menuItemJson) { + FieldsValidator fieldsValidator = new FieldsValidator(); + try { + // TODO: validate all the fields + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> functionalMenuItems = dataAccessService.getList(FunctionalMenuItem.class, + " where text = '" + menuItemJson.text + "'", null, null); + + boolean dublicatedName = false; + for (FunctionalMenuItem fnMenuItem : functionalMenuItems) { + if (menuItemJson.menuId != null && menuItemJson.menuId.equals(fnMenuItem.menuId)) { + // FunctionalMenuItem should not be compared with itself + continue; + } + + if (!dublicatedName && fnMenuItem.text.equalsIgnoreCase(menuItemJson.text)) { + dublicatedName = true; + break; + } + } + if (dublicatedName) { + fieldsValidator.addProblematicFieldName("text"); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT); + fieldsValidator.errorCode = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR); + logger.debug(EELFLoggerDelegate.debugLogger, "In menuItemFieldsChecker, Error: we have an duplicate text field"); + } else if (StringUtils.isEmpty(menuItemJson.text) && menuItemJson.menuId == null) { + // text must be non empty for a create. For an edit, can be empty, which means it is a move request. + // a null menuId indicates a create. + fieldsValidator.addProblematicFieldName("text"); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + logger.debug(EELFLoggerDelegate.debugLogger, "In menuItemFieldsChecker, Error: we have an empty text field"); + } else { + // The url, appid, and roles must either be all filled or all empty. + Boolean urlIsEmpty = StringUtils.isEmpty(menuItemJson.url); + Boolean rolesIsEmpty = menuItemJson.getRoles() == null || menuItemJson.getRoles().isEmpty(); + Boolean appidIsEmpty = menuItemJson.appid == null || menuItemJson.appid == 0; + logger.debug(EELFLoggerDelegate.debugLogger, "LR: menuItemfieldsChecker: urlIsEmpty: " + urlIsEmpty + "; rolesIsEmpty: " + rolesIsEmpty + "; appidIsEmpty: " + appidIsEmpty +"\n"); + if (!((urlIsEmpty && rolesIsEmpty && appidIsEmpty) || (!urlIsEmpty && !rolesIsEmpty && !appidIsEmpty))) + { + fieldsValidator.addProblematicFieldName("url,roles,appid"); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + logger.debug(EELFLoggerDelegate.debugLogger, "In menuItemFieldsChecker, Error: we don't have: either all 3 fields empty or all 3 fields nonempty"); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "In menuItemFieldsChecker, Success: either all 3 fields empty or all 3 fields nonempty"); + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while validating the FunctionalMenuItems. Details: " + EcompPortalUtils.getStackTrace(e)); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + + return fieldsValidator; + } + + // Turn foreign key checks on or off + protected void setForeignKeys(Session localSession, Boolean on) { + String keyCheck = "0"; + if (on) { + keyCheck = "1"; + } + String sql = "set FOREIGN_KEY_CHECKS="+keyCheck; + logQuery(sql); + Query query = localSession.createSQLQuery(sql); + query.executeUpdate(); + } + + public FieldsValidator createFunctionalMenuItem(FunctionalMenuItemWithRoles menuItemJson) { + FieldsValidator fieldsValidator = menuItemFieldsChecker(menuItemJson); + if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { + logger.debug(EELFLoggerDelegate.debugLogger, "LR: createFunctionalMenuItem: test 1"); + boolean result = false; + Session localSession = null; + Transaction transaction = null; + try { + FunctionalMenuItem menuItem = new FunctionalMenuItem(); + menuItem.appid = menuItemJson.appid; + menuItem.setRoles(menuItemJson.getRoles()); + menuItem.url = menuItemJson.url; + menuItem.text = menuItemJson.text; + menuItem.parentMenuId = menuItemJson.parentMenuId; + menuItem.active_yn = "Y"; + localSession = sessionFactory.openSession(); + + // If the app is disabled, deactivate the menu item. + if (menuItemJson.appid != null) { + Long appidLong = Long.valueOf(menuItemJson.appid); + EPApp app = (EPApp) localSession.get(EPApp.class, appidLong); + if (app != null && ! app.getEnabled()) { + menuItem.active_yn = "N"; + } + } + + // Set the column number to 1 higher than the highest column + // number under this parent. + Criteria criteria = localSession.createCriteria(FunctionalMenuItem.class); + criteria.setProjection(Projections.max("column")); + criteria.add(Restrictions.eq("parentMenuId", menuItem.parentMenuId)); + Integer maxColumn = (Integer) criteria.uniqueResult(); + if (maxColumn == null) { + maxColumn = 0; + } + menuItem.column = maxColumn + 1; + logger.debug(EELFLoggerDelegate.debugLogger, "about to create menu item: " + menuItem.toString()); + + transaction = localSession.beginTransaction(); + // localSession.saveOrUpdate(newMenuItem); + localSession.save(menuItem); + Long menuid = menuItem.menuId; + menuItemJson.menuId = menuid; + logger.debug(EELFLoggerDelegate.debugLogger, "after saving menu object, new id: " + menuid); + + // Next, save all the roles + + addRoles(menuItemJson, localSession); + transaction.commit(); + result = true; + } catch (Exception e) { + EcompPortalUtils.rollbackTransaction(transaction, + "createFunctionalMenuItem rollback, exception = " + e); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "createFunctionalMenuItem"); + } + if (result) { + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "LR: createFunctionalMenuItem: no result. setting httpStatusCode to " + + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, "FunctionalMenuServiceImpl.createFunctionalMenuItem: bad request"); + } + return fieldsValidator; + } + + /* Add all the roles in the menu item to the database */ + public void addRoles(FunctionalMenuItemWithRoles menuItemJson, Session localSession) { + logger.debug(EELFLoggerDelegate.debugLogger, "entering addRoles."); + List<Integer> roles = menuItemJson.getRoles(); + if (roles != null && roles.size() > 0) { + Integer appid = menuItemJson.appid; + Long menuid = menuItemJson.menuId; + for (Integer roleid : roles) { + logger.debug(EELFLoggerDelegate.debugLogger, "about to create record for role: " + roleid); + FunctionalMenuRole role = new FunctionalMenuRole(); + role.appId = appid; + role.menuId = menuid; + role.roleId = roleid; + localSession.save(role); + logger.debug(EELFLoggerDelegate.debugLogger, "after saving role menu object, new id: " + role.id); + } + } + } + + /* Delete all the roles associated with the menu item from the database */ + public void deleteRoles(Long menuId) { + dataAccessService.deleteDomainObjects(FunctionalMenuRole.class, "menu_id='" + menuId + "'", null); + } + + /* Delete all favorites associated with the menu item from the database */ + public void deleteFavorites(Long menuId) { + dataAccessService.deleteDomainObjects(FavoritesFunctionalMenuItem.class, "menu_id='" + menuId + "'", null); + } + + private Boolean parentMenuIdEqual(Integer menuId1, Integer menuId2) { + return ((menuId1 == null && menuId2 == null) || (menuId1 != null && menuId1.equals(menuId2))); + } + + private void updateColumnForSiblings(Session localSession, Long menuId, Integer oldParentMenuId, + Integer newParentMenuId, Integer oldColumn, Integer newColumn) { + logger.debug(EELFLoggerDelegate.debugLogger, "entering updateColumnForSiblings"); + Criteria criteria = localSession.createCriteria(FunctionalMenuItem.class); + criteria.add(Restrictions.ne("menuId", menuId)); + if (parentMenuIdEqual(oldParentMenuId, newParentMenuId)) { + logger.debug(EELFLoggerDelegate.debugLogger, "moving under the same parent"); + // We are moving to a new position under the same parent + if (newParentMenuId == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "newParentMenuId is null, so using isNull"); + criteria.add(Restrictions.isNull("parentMenuId")); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "newParentMenuId is NOT null, so using eq"); + criteria.add(Restrictions.eq("parentMenuId", newParentMenuId)); + } + if (oldColumn > newColumn) { + logger.debug(EELFLoggerDelegate.debugLogger, "moving to a lower column under the same parent"); + // We are moving to a lower column under the same parent + criteria.add(Restrictions.ge("column", newColumn)); + criteria.add(Restrictions.lt("column", oldColumn)); + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> menuItems = criteria.list(); + for (FunctionalMenuItem menuItem : menuItems) { + menuItem.column += 1; + localSession.save(menuItem); + } + } else if (oldColumn < newColumn) { + logger.debug(EELFLoggerDelegate.debugLogger, "moving to a higher column under the same parent"); + // We are moving to a higher column under the same parent + criteria.add(Restrictions.gt("column", oldColumn)); + criteria.add(Restrictions.le("column", newColumn)); + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> menuItems = criteria.list(); + for (FunctionalMenuItem menuItem : menuItems) { + menuItem.column -= 1; + localSession.save(menuItem); + } + } else { + // No info has changed + logger.debug(EELFLoggerDelegate.debugLogger, "no info has changed, so we are not moving"); + } + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "moving under a new parent"); + // We are moving under a new parent. + + // Adjust the children under the old parent + logger.debug(EELFLoggerDelegate.debugLogger, "about to adjust the children under the old parent"); + + // If the parentId is null, must check for its children differently + if (oldParentMenuId == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "oldParentMenuId is null, so using isNull"); + criteria.add(Restrictions.isNull("parentMenuId")); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "oldParentMenuId is NOT null, so using eq"); + criteria.add(Restrictions.eq("parentMenuId", oldParentMenuId)); + } + + criteria.add(Restrictions.gt("column", oldColumn)); + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> menuItems1 = criteria.list(); + for (FunctionalMenuItem menuItem : menuItems1) { + menuItem.column -= 1; + localSession.save(menuItem); + } + // Adjust the children under the new parent. + logger.debug(EELFLoggerDelegate.debugLogger, "about to adjust the children under the new parent"); + logger.debug(EELFLoggerDelegate.debugLogger, "get all menu items where menuId!=" + menuId + "; parentMenuId==" + newParentMenuId + + "; column>=" + newColumn); + criteria = localSession.createCriteria(FunctionalMenuItem.class); + criteria.add(Restrictions.ne("menuId", menuId)); + if (newParentMenuId == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "newParentMenuId is null, so using isNull"); + criteria.add(Restrictions.isNull("parentMenuId")); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "newParentMenuId is NOT null, so using eq"); + criteria.add(Restrictions.eq("parentMenuId", newParentMenuId)); + } + + criteria.add(Restrictions.ge("column", newColumn)); + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> menuItems2 = criteria.list(); + if (menuItems2 != null) { + logger.debug(EELFLoggerDelegate.debugLogger, "found " + menuItems2.size() + " menu items"); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "found null menu items"); + } + for (FunctionalMenuItem menuItem : menuItems2) { + menuItem.column += 1; + localSession.save(menuItem); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "done with updateColumnForSiblings"); + } + + public void removeAppInfo(Session localSession, Long menuId) { + // Remove the url, role, and app info from a menu item + FunctionalMenuItem menuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class, menuId); + menuItem.url = ""; + deleteRoles(menuId); + } + + public FieldsValidator editFunctionalMenuItem(FunctionalMenuItemWithRoles menuItemJson) { + boolean result = false; + Session localSession = null; + Transaction transaction = null; + Long menuId = menuItemJson.menuId; + + logger.debug(EELFLoggerDelegate.debugLogger, "LR: editFunctionalMenuItem: test 1"); + FieldsValidator fieldsValidator = menuItemFieldsChecker(menuItemJson); + if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { + // TODO: make sure menuId is here. And, it might not already exist + // in db table. + if (menuId == null) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + logger.error(EELFLoggerDelegate.errorLogger, "FunctionalMenuServiceImpl.editFunctionalMenuItem: bad request"); + } else { + // To simplify the code, assume we will have a transaction + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + + // Get the existing info associated with menuItem from the DB + FunctionalMenuItem menuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class, menuId); + Integer oldColumn = menuItem.column; + Integer oldParentMenuId = menuItem.parentMenuId; + Integer newColumn = menuItemJson.column; + Integer newParentMenuId = menuItemJson.parentMenuId; + + logger.debug(EELFLoggerDelegate.debugLogger, "prev info: column: " + oldColumn + "; parentMenuId: " + oldParentMenuId); + + if (menuItemJson.appid != null && menuItemJson.getRoles() != null && !menuItemJson.getRoles().isEmpty() + && menuItemJson.url != null && !menuItemJson.url.isEmpty() && menuItemJson.text != null + && !menuItemJson.text.isEmpty()) { + // Scenario: appid, roles, url and text are all non-null. + // This menu item is associated with an app. + // (Note: this should only occur for a bottom-level menu + // item with no children.) + // 1) Remove all the records from fn_menu_functional_role + // for this menuId. + // 2) Add records to the fn_menu_function_role table for the + // appId and each roleId + // 3) Update the url and text for this menu item. + + // Because of foreign key constraints, delete the roles, + // then update the menuItem then add the roles. + deleteRoles(menuId); + // Assumption: this is not a Move, so don't change the + // parentMenuId and column. + menuItem.appid = menuItemJson.appid; + menuItem.setRoles(menuItemJson.getRoles()); + menuItem.url = menuItemJson.url; + menuItem.text = menuItemJson.text; + + // If the app is disabled, deactivate the menu item. + Long appidLong = Long.valueOf(menuItemJson.appid); + EPApp app = (EPApp) localSession.get(EPApp.class, appidLong); + if (app != null && ! app.getEnabled()) { + menuItem.active_yn = "N"; + } else { + menuItem.active_yn = "Y"; + } + + + localSession.update(menuItem); + addRoles(menuItemJson, localSession); + + } else if (menuItemJson.appid == null && (menuItemJson.getRoles() == null || menuItemJson.getRoles().isEmpty()) + && (menuItemJson.url == null || menuItemJson.url.isEmpty()) && menuItemJson.text != null + && !menuItemJson.text.isEmpty()) { + // Scenario: appid, roles and url are all null; text is + // non-null. + // This menu item is NOT associated with an app. + // 1) Remove all the records from fn_menu_functional_role + // for this menuId + // (in case it was previously associated with an app). + // 2) Update the text for this menu item. + // 3) Set the url to "" + deleteRoles(menuId); + // Assumption: this is not a Move, so don't change the + // parentMenuId and column. + menuItem.text = menuItemJson.text; + menuItem.url = ""; + menuItem.active_yn = "Y"; + localSession.update(menuItem); + + } else if (newColumn != null) { + // This is a "move" request. + // Menu item has been moved to a different position under + // the same parent, or under a new parent. + logger.debug(EELFLoggerDelegate.debugLogger, "Doing a move operation."); + if (parentMenuIdEqual(oldParentMenuId, newParentMenuId)) { + // The parent is the same. We have just changed the + // column + logger.debug(EELFLoggerDelegate.debugLogger, "moving under the same parent"); + menuItem.column = newColumn; + localSession.update(menuItem); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "moving under a different parent"); + menuItem.parentMenuId = newParentMenuId; + menuItem.column = newColumn; + localSession.update(menuItem); + // If we are moving under a new parent, must delete any + // app/role info from + // the new parent, since it is no longer a leaf menu + // item and cannot have app info + // associated with it. The front end will have warned + // the user and gotten confirmation. + if (menuItemJson.parentMenuId != null) { + Long parentMenuIdLong = new Long(menuItemJson.parentMenuId); + removeAppInfo(localSession, parentMenuIdLong); + // deleteRoles(parentMenuIdLong); + } + } + // must update the column for all old and new sibling menu + // items + updateColumnForSiblings(localSession, menuId, oldParentMenuId, newParentMenuId, oldColumn, + newColumn); + } + + transaction.commit(); + logger.debug(EELFLoggerDelegate.debugLogger, "LR: editFunctionalMenuItem: finished committing transaction"); + result = true; + } catch (Exception e) { + EcompPortalUtils.rollbackTransaction(transaction, + "createFunctionalMenuItem rollback, exception = " + e); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "editFunctionalMenuItem"); + } + + if (result) { + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "LR: createFunctionalMenuItem: no result. setting httpStatusCode to " + + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + } + + return fieldsValidator; + } + + public FieldsValidator deleteFunctionalMenuItem(Long menuId) { + FieldsValidator fieldsValidator = new FieldsValidator(); + logger.debug(EELFLoggerDelegate.debugLogger, "LR: deleteFunctionalMenuItem: test 1"); + boolean result = false; + Session localSession = null; + Transaction transaction = null; + + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + // We must turn off foreign keys before deleting a menu item. Otherwise there will be a + // constraint violation from the ancestors table. + setForeignKeys(localSession, false); + deleteRoles(menuId); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteFunctionalMenuItem: after deleting roles"); + deleteFavorites(menuId); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteFunctionalMenuItem: after deleting favorites"); + localSession.delete(localSession.get(FunctionalMenuItem.class, menuId)); + logger.debug(EELFLoggerDelegate.debugLogger, "deleteFunctionalMenuItem: about to commit"); + transaction.commit(); + result = true; + } catch (Exception e) { + EcompPortalUtils.rollbackTransaction(transaction, + "deleteFunctionalMenuItem rollback, exception = " + e); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "deleteFunctionalMenuItem"); + } + if (result) { + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "LR: deleteFunctionalMenuItem: no result. setting httpStatusCode to " + + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return fieldsValidator; + } + + // Regenerate the fn_menu_functional_ancestors table, which is used + // by the queries that return the functional menu items. + public FieldsValidator regenerateAncestorTable() { + FieldsValidator fieldsValidator = new FieldsValidator(); + Session localSession = null; + Transaction transaction = null; + + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + String sql = "DELETE FROM fn_menu_functional_ancestors"; + logQuery(sql); + Query query = localSession.createSQLQuery(sql); + query.executeUpdate(); + logger.debug(EELFLoggerDelegate.debugLogger, "regenerateAncestorTable: finished query 1"); + + sql = "ALTER TABLE fn_menu_functional_ancestors AUTO_INCREMENT=1"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + logger.debug(EELFLoggerDelegate.debugLogger, "regenerateAncestorTable: reset AUTO_INCREMENT to 1"); + + int depth = 0; + sql = "INSERT INTO fn_menu_functional_ancestors(menu_id, ancestor_menu_id, depth) " + + "SELECT m.menu_id, m.menu_id, " + depth + " FROM fn_menu_functional m"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + logger.debug(EELFLoggerDelegate.debugLogger, "regenerateAncestorTable: finished query 2"); + for (depth = 0; depth < 3; depth++) { + int depthPlusOne = depth + 1; + sql = "INSERT INTO fn_menu_functional_ancestors(menu_id, ancestor_menu_id, depth) " + + " SELECT a.menu_id, m.parent_menu_id, " + depthPlusOne + + " FROM fn_menu_functional m, fn_menu_functional_ancestors a " + " WHERE a.depth='" + depth + + "' AND " + " a.ancestor_menu_id = m.menu_id AND " + " m.parent_menu_id != '-1'"; + logQuery(sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + } + logger.debug(EELFLoggerDelegate.debugLogger, "regenerateAncestorTable: finished query 3"); + transaction.commit(); + } catch (Exception e) { + EcompPortalUtils.rollbackTransaction(transaction, + "regenerateAncestorTable rollback, exception = " + e); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "regenerateAncestorTable"); + } + return fieldsValidator; + } + + private void logQuery(String sql) { + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + } + + public FieldsValidator setFavoriteItem(FavoritesFunctionalMenuItem menuItemJson) { + boolean result = false; + FieldsValidator fieldsValidator = new FieldsValidator(); + + Session localSession = null; + Transaction transaction = null; + + try { + logger.debug(EELFLoggerDelegate.debugLogger, String.format("Before adding favorite for user id:{0} and menu id:{1} ",menuItemJson.userId,menuItemJson.menuId)); + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + localSession.save(menuItemJson); + transaction.commit(); + result = true; + logger.debug(EELFLoggerDelegate.debugLogger, String.format("After adding favorite for user id:{0} and menu id:{1} ",menuItemJson.userId,menuItemJson.menuId)); + } catch (Exception e) { + EcompPortalUtils.rollbackTransaction(transaction,"setFavoriteItem rollback, exception = " + e); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "setFavoriteItem"); + } + + if(result) { + } + else { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + + return fieldsValidator; + } + + public List<FavoritesFunctionalMenuItemJson> getFavoriteItems(Long userId) { + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Before getting favorites for user id: " + userId); + + // Divide this into 2 queries: one which returns the favorites items associated with Restricted apps, + // and one that returns all the other favorites items. Then we can easily add the boolean flag + // restrictedApp to each FavoritesFunctionalMenuItemJson, to be used by the front end. + + String sql = "SELECT f.user_id,f.menu_id,m.text,m.url " + + " FROM fn_menu_favorites f, fn_menu_functional m, fn_menu_functional_roles mr " + + " WHERE f.user_id='" + userId + "' AND f.menu_id = m.menu_id " + + " AND f.menu_id = mr.menu_id " + + " AND mr.role_id = '" + RESTRICTED_APP_ROLE_ID + "' "; + + @SuppressWarnings("unchecked") + List<FavoritesFunctionalMenuItemJson> menuItems = dataAccessService.executeSQLQuery(sql, FavoritesFunctionalMenuItemJson.class, null); + for (FavoritesFunctionalMenuItemJson menuItem : menuItems) { + menuItem.restrictedApp = true; + } + + sql = "SELECT DISTINCT f.user_id,f.menu_id,m.text,m.url " + + " FROM fn_menu_favorites f, fn_menu_functional m, fn_menu_functional_roles mr " + + " WHERE f.user_id='" + userId + "' AND f.menu_id = m.menu_id " + + " AND f.menu_id = mr.menu_id " + + " AND mr.role_id != '" + RESTRICTED_APP_ROLE_ID + "' "; + @SuppressWarnings("unchecked") + List<FavoritesFunctionalMenuItemJson> menuItems2 = dataAccessService.executeSQLQuery(sql, FavoritesFunctionalMenuItemJson.class, null); + for (FavoritesFunctionalMenuItemJson menuItem : menuItems2) { + menuItem.restrictedApp = false; + menuItems.add(menuItem); + } + + return menuItems; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in FunctionalMenuServiceImpl.getFavoriteItems. Details: " + EcompPortalUtils.getStackTrace(e)); + List<FavoritesFunctionalMenuItemJson> menuItems = new ArrayList<FavoritesFunctionalMenuItemJson>(); + return menuItems; + } + } + + public FieldsValidator removeFavoriteItem(Long userId, Long menuId) { + boolean result = false; + FieldsValidator fieldsValidator = new FieldsValidator(); + + Session localSession = null; + Transaction transaction = null; + + try { + + FavoritesFunctionalMenuItem menuItemJson = new FavoritesFunctionalMenuItem(); + menuItemJson.userId = userId; + menuItemJson.menuId = menuId; + + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + localSession.delete(menuItemJson); + localSession.flush(); + transaction.commit(); + result = true; + logger.debug(EELFLoggerDelegate.debugLogger, String.format("After removing favorite for user id: " + userId + "; menu id: " + menuId)); + } catch (Exception e) { + EcompPortalUtils.rollbackTransaction(transaction,"removeFavoriteItem rollback, exception = " + e); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "removeFavoriteItem"); + } + + if(result) { + } + else { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + + return fieldsValidator; + } + + @Override + public void assignHelpURLs(List<FunctionalMenuItem> menuItems) { + try { + String user_guide_link = SystemProperties.getProperty(EPCommonSystemProperties.USER_GUIDE_URL); + + for(FunctionalMenuItem menuItem: menuItems){ + if(menuItem.text.equalsIgnoreCase("Contact Us")){ + menuItem.setUrl("contactUs"); + //menuItem.setRestrictedApp(true); + } + if(menuItem.text.equalsIgnoreCase("Get Access")) { + menuItem.setUrl("getAccess"); + } + if(menuItem.text.equalsIgnoreCase("User Guide")) { + menuItem.setUrl(user_guide_link); + menuItem.setRestrictedApp(true); + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "assignHelpURLs process failed. Details: " + EcompPortalUtils.getStackTrace(e)); + } + + } + + public List<FunctionalMenuRole> getFunctionalMenuRole() { + String sql = "SELECT * from fn_menu_functional_roles"; + logQuery(sql); + logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuRole: logged the query"); + + @SuppressWarnings("unchecked") + List<FunctionalMenuRole> functionalMenuRole = dataAccessService.executeSQLQuery(sql, FunctionalMenuRole.class, null); + + return functionalMenuRole; + } + + @SuppressWarnings("unchecked") + @Override + public List<BusinessCardApplicationRole> getUserAppRolesList(String userId) { + Map<String, String> params = new HashMap<>(); + params.put("userId", userId); + + List<BusinessCardApplicationRole> userAppRoles = null; + try { + userAppRoles = dataAccessService + .executeNamedQuery("getUserApproles", params, null); + } catch (Exception e) { + // TODO Auto-generated catch block + logger.error(EELFLoggerDelegate.errorLogger, "getUserAppRolesList failed", e); + } + return userAppRoles; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/GetAccessService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/GetAccessService.java index 8b5e72e5..e9dc2818 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/GetAccessService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/GetAccessService.java @@ -1,33 +1,33 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.GetAccessResult;
-
-public interface GetAccessService {
- /**
- * @return One entry per application function AND role; i.e., each application
- * appears many times.
- */
- List<GetAccessResult> getAppAccessList(EPUser user);
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.GetAccessResult; + +public interface GetAccessService { + /** + * @return One entry per application function AND role; i.e., each application + * appears many times. + */ + List<GetAccessResult> getAppAccessList(EPUser user); +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/GetAccessServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/GetAccessServiceImpl.java index 37af1dab..1f215921 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/GetAccessServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/GetAccessServiceImpl.java @@ -1,61 +1,61 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-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 org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.GetAccessResult;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-
-@Service("getAccessService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class GetAccessServiceImpl implements GetAccessService{
-
- @Autowired
- private DataAccessService dataAccessService;
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.GetAccessService#getAppAccessList()
- */
- @SuppressWarnings("unchecked")
- @Override
- public List<GetAccessResult> getAppAccessList(EPUser user) {
- final Map<String, Long> params = new HashMap<>();
- List<GetAccessResult> appAccessList = null;
- params.put("userId", user.getId());
- appAccessList = dataAccessService
- .executeNamedQuery("getAppAccessFunctionRole", params, null);
- return appAccessList;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +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 org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.GetAccessResult; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; + +@Service("getAccessService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class GetAccessServiceImpl implements GetAccessService{ + + @Autowired + private DataAccessService dataAccessService; + + /* + * (non-Javadoc) + * @see org.openecomp.portalapp.portal.service.GetAccessService#getAppAccessList() + */ + @SuppressWarnings("unchecked") + @Override + public List<GetAccessResult> getAppAccessList(EPUser user) { + final Map<String, Long> params = new HashMap<>(); + List<GetAccessResult> appAccessList = null; + params.put("userId", user.getId()); + appAccessList = dataAccessService + .executeNamedQuery("getAppAccessFunctionRole", params, null); + return appAccessList; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ManifestService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ManifestService.java index 7a10568d..66932bf6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ManifestService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ManifestService.java @@ -1,33 +1,33 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.io.IOException;
-import java.util.jar.Attributes;
-
-public interface ManifestService {
- /**
- * Gets the content of the webapp manifest file META-INF/MANIFEST.MF.
- *
- * @return Attributes object with key-value pairs from the manifest
- * @throws IOException
- */
- public Attributes getWebappManifest() throws IOException;
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.io.IOException; +import java.util.jar.Attributes; + +public interface ManifestService { + /** + * Gets the content of the webapp manifest file META-INF/MANIFEST.MF. + * + * @return Attributes object with key-value pairs from the manifest + * @throws IOException + */ + public Attributes getWebappManifest() throws IOException; +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ManifestServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ManifestServiceImpl.java index 3d0f34a2..5136985c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ManifestServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ManifestServiceImpl.java @@ -1,62 +1,62 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.jar.Attributes;
-import java.util.jar.Manifest;
-
-import javax.servlet.ServletContext;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.stereotype.Service;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-
-@Service("manifestService")
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class ManifestServiceImpl implements ManifestService {
- @Autowired
- ServletContext context;
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.ManifestService#getWebappManifest()
- */
- public Attributes getWebappManifest() throws IOException {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ManifestServiceImpl.class);
- // Path to resource on classpath
- final String MANIFEST_RESOURCE_PATH = "/META-INF/MANIFEST.MF";
- // Manifest is formatted as Java-style properties
- try {
- InputStream inputStream = context.getResourceAsStream(MANIFEST_RESOURCE_PATH);
- Manifest manifest = new Manifest(inputStream);
- inputStream.close();
- return manifest.getMainAttributes();
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getWebappManifest: failed to read/find manifest");
- throw e;
- }
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +import javax.servlet.ServletContext; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; + +@Service("manifestService") +@EnableAspectJAutoProxy +@EPMetricsLog +public class ManifestServiceImpl implements ManifestService { + @Autowired + ServletContext context; + + /* + * (non-Javadoc) + * @see org.openecomp.portalapp.portal.service.ManifestService#getWebappManifest() + */ + public Attributes getWebappManifest() throws IOException { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ManifestServiceImpl.class); + // Path to resource on classpath + final String MANIFEST_RESOURCE_PATH = "/META-INF/MANIFEST.MF"; + // Manifest is formatted as Java-style properties + try { + InputStream inputStream = context.getResourceAsStream(MANIFEST_RESOURCE_PATH); + Manifest manifest = new Manifest(inputStream); + inputStream.close(); + return manifest.getMainAttributes(); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, "getWebappManifest: failed to read/find manifest"); + throw e; + } + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceProxyService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceProxyService.java index 00fc9ad8..3feffde6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceProxyService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceProxyService.java @@ -1,59 +1,59 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.springframework.web.client.RestClientException;
-
-public interface MicroserviceProxyService {
-
- /**
- * Gets the specific microservice from table ep_microservice, communicates
- * to microservice with the specified security type. The microservice sends
- * back the response.
- *
- * Gets the data while testing the microservice with no widget associated with
- *
- * @param serviceId
- * Id of microservice to be used
- * @return response sent from microservice
- * @throws Exception
- */
- String proxyToDestination(long serviceId, EPUser user, HttpServletRequest request) throws Exception;
-
-
-
- /**
- * Gets the microservice data based on the user id and widget id. Different
- * users have his/her own parameters for one widget. The method sends back
- * the response.
- *
- * @param widgetId
- * Id of widget to be used
- * @param user
- * User information
- * @param request
- * @return response sent from microserivce
- * @throws Exception
- */
- String proxyToDestinationByWidgetId(long widgetId, EPUser user, HttpServletRequest request) throws Exception;
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.springframework.web.client.RestClientException; + +public interface MicroserviceProxyService { + + /** + * Gets the specific microservice from table ep_microservice, communicates + * to microservice with the specified security type. The microservice sends + * back the response. + * + * Gets the data while testing the microservice with no widget associated with + * + * @param serviceId + * Id of microservice to be used + * @return response sent from microservice + * @throws Exception + */ + String proxyToDestination(long serviceId, EPUser user, HttpServletRequest request) throws Exception; + + + + /** + * Gets the microservice data based on the user id and widget id. Different + * users have his/her own parameters for one widget. The method sends back + * the response. + * + * @param widgetId + * Id of widget to be used + * @param user + * User information + * @param request + * @return response sent from microserivce + * @throws Exception + */ + String proxyToDestinationByWidgetId(long widgetId, EPUser user, HttpServletRequest request) throws Exception; +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceProxyServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceProxyServiceImpl.java index 3a520c88..df835a92 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceProxyServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceProxyServiceImpl.java @@ -1,222 +1,242 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.commons.codec.binary.Base64;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.MicroserviceData;
-import org.openecomp.portalapp.portal.domain.MicroserviceParameter;
-import org.openecomp.portalapp.portal.domain.WidgetCatalog;
-import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter;
-import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.stereotype.Service;
-import org.springframework.web.client.HttpClientErrorException;
-import org.springframework.web.client.RestTemplate;
-
-@Service("microserviceProxyService")
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class MicroserviceProxyServiceImpl implements MicroserviceProxyService {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyServiceImpl.class);
- private static final String BASIC_AUTH = "Basic Authentication";
- private static final String NO_AUTH = "No Authentication";
- private static final String COOKIE_AUTH = "Cookie based Authentication";
- private static final String QUESTION_MARK = "?";
- private static final String ADD_MARK = "&";
-
- String whatService = "widgets-service";
-
- @Autowired
- private ConsulHealthService consulHealthService;
-
- @Autowired
- MicroserviceService microserviceService;
-
- @Autowired
- WidgetParameterService widgetParameterService;
-
- RestTemplate template = new RestTemplate();
-
- @Override
- public String proxyToDestination(long serviceId, EPUser user, HttpServletRequest request) throws Exception {
-
- String response = null;
-
- // get the microservice object by the id
- MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
-
- // No such microservice available
- if (data == null) {
- return response;
- }
- List<MicroserviceParameter> params = data.getParameterList();
- if (data.getSecurityType().equals(NO_AUTH)) {
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(headers);
-
- String url = microserviceUrlConverter(data, params);
- response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
-
- } else if (data.getSecurityType().equals(BASIC_AUTH)) {
- // encoding the username and password
- String plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
- byte[] plainCredsBytes = plainCreds.getBytes();
- byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
- String base64Creds = new String(base64CredsBytes);
-
- HttpHeaders headers = new HttpHeaders();
- headers.add("Authorization", "Basic " + base64Creds);
- headers.setContentType(MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(headers);
-
- String url = microserviceUrlConverter(data, params);
- response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
- } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_JSON);
- String rawCookie = request.getHeader("Cookie");
- headers.add("Cookie", rawCookie);
- HttpEntity<String> entity = new HttpEntity<String>(headers);
-
- String url = microserviceUrlConverter(data, params);
- response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
- }
- return response;
- }
-
- @Override
- public String proxyToDestinationByWidgetId(long widgetId, EPUser user, HttpServletRequest request) throws Exception {
-
- String response = null;
-
- ResponseEntity<Long> ans = (ResponseEntity<Long>) template.exchange(
- "https://" + consulHealthService.getServiceLocation(whatService)
- + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
- HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class);
- Long serviceId = ans.getBody();
-
- // get the microservice object by the id
- MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
-
- // No such microservice available
- if (data == null) {
- return response;
- }
-
- List<MicroserviceParameter> params = data.getParameterList();
-
- for (MicroserviceParameter p : params) {
- WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(), p.getId());
- if (userValue != null)
- p.setPara_value(userValue.getUser_value());
- }
-
- if (data.getSecurityType().equals(NO_AUTH)) {
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(headers);
-
- String url = microserviceUrlConverter(data, params);
- try {
- response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
- } catch (HttpClientErrorException e) {
- throw e;
- }
- } else if (data.getSecurityType().equals(BASIC_AUTH)) {
- // encoding the username and password
- String plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
- byte[] plainCredsBytes = plainCreds.getBytes();
- byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
- String base64Creds = new String(base64CredsBytes);
-
- HttpHeaders headers = new HttpHeaders();
- headers.add("Authorization", "Basic " + base64Creds);
- headers.setContentType(MediaType.APPLICATION_JSON);
- HttpEntity<String> entity = new HttpEntity<String>(headers);
-
- String url = microserviceUrlConverter(data, params);
- try {
- response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
- } catch (HttpClientErrorException e) {
- throw e;
- }
- } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_JSON);
- String rawCookie = request.getHeader("Cookie");
- headers.add("Cookie", rawCookie);
- HttpEntity<String> entity = new HttpEntity<String>(headers);
-
- String url = microserviceUrlConverter(data, params);
- try {
- response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
- } catch (HttpClientErrorException e) {
- throw e;
- }
- }
- return response;
- }
-
- private String decryptedPassword(String encryptedPwd) throws Exception {
- String result = "";
- if (encryptedPwd != null & encryptedPwd.length() > 0) {
- try {
- result = CipherUtil.decrypt(encryptedPwd,
- SystemProperties.getProperty(SystemProperties.Decryption_Key));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
- throw e;
- }
- }
- return result;
- }
-
- private String microserviceUrlConverter(MicroserviceData data, List<MicroserviceParameter> params) {
- String url = data.getUrl();
- for (int i = 0; i < params.size(); i++) {
- if (i == 0) {
- url += QUESTION_MARK;
- }
- url += params.get(i).getPara_key() + "=" + params.get(i).getPara_value();
- if (i != (params.size() - 1)) {
- url += ADD_MARK;
- }
- }
- return url;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.codec.binary.Base64; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.MicroserviceData; +import org.openecomp.portalapp.portal.domain.MicroserviceParameter; +import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter; +import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; + +@Service("microserviceProxyService") +@EnableAspectJAutoProxy +@EPMetricsLog +public class MicroserviceProxyServiceImpl implements MicroserviceProxyService { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyServiceImpl.class); + private static final String BASIC_AUTH = "Basic Authentication"; + private static final String NO_AUTH = "No Authentication"; + private static final String COOKIE_AUTH = "Cookie based Authentication"; + private static final String QUESTION_MARK = "?"; + private static final String ADD_MARK = "&"; + + String whatService = "widgets-service"; + + @Autowired + private ConsulHealthService consulHealthService; + + @Autowired + MicroserviceService microserviceService; + + @Autowired + WidgetParameterService widgetParameterService; + + RestTemplate template = new RestTemplate(); + + @Override + public String proxyToDestination(long serviceId, EPUser user, HttpServletRequest request) throws Exception { + + String response = null; + + // get the microservice object by the id + MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId); + + // No such microservice available + if (data == null) { + return response; + } + List<MicroserviceParameter> params = data.getParameterList(); + MicroserviceParameter userId_param = new MicroserviceParameter(); + userId_param.setPara_key("userId"); + userId_param.setPara_value(user.getOrgUserId()); + params.add(userId_param); + + if (data.getSecurityType().equals(NO_AUTH)) { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(headers); + + String url = microserviceUrlConverter(data, params); + logger.debug(EELFLoggerDelegate.debugLogger, "Before making no authentication call: {}", url); + response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, "No authentication call response: {}", response); + + } else if (data.getSecurityType().equals(BASIC_AUTH)) { + // encoding the username and password + String plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword()); + byte[] plainCredsBytes = plainCreds.getBytes(); + byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); + String base64Creds = new String(base64CredsBytes); + + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic " + base64Creds); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(headers); + + String url = microserviceUrlConverter(data, params); + logger.debug(EELFLoggerDelegate.debugLogger, "Before making basic authentication call: {}", url); + response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, "Basic authentication call response: {}", response); + + } else if (data.getSecurityType().equals(COOKIE_AUTH)) { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + String rawCookie = request.getHeader("Cookie"); + headers.add("Cookie", rawCookie); + HttpEntity<String> entity = new HttpEntity<String>(headers); + + String url = microserviceUrlConverter(data, params); + logger.debug(EELFLoggerDelegate.debugLogger, "Before making cookie-based authentication call: {}", url); + response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, "Cookie-based authentication call response: {}", response); + } + return response; + } + + @Override + public String proxyToDestinationByWidgetId(long widgetId, EPUser user, HttpServletRequest request) + throws Exception { + + String response = null; + + @SuppressWarnings({ "rawtypes", "unchecked" }) + ResponseEntity<Long> ans = (ResponseEntity<Long>) template.exchange( + "https://" + + consulHealthService.getServiceLocation(whatService, + SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/widgetCatalog/parameters/" + widgetId, + HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class); + Long serviceId = ans.getBody(); + + // get the microservice object by the id + MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId); + + // No such microservice available + if (data == null) { + return response; + } + + List<MicroserviceParameter> params = data.getParameterList(); + MicroserviceParameter userId_param = new MicroserviceParameter(); + userId_param.setPara_key("userId"); + userId_param.setPara_value(user.getOrgUserId()); + params.add(userId_param); + + for (MicroserviceParameter p : params) { + WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(), + p.getId()); + if (userValue != null) + p.setPara_value(userValue.getUser_value()); + } + + if (data.getSecurityType().equals(NO_AUTH)) { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(headers); + + String url = microserviceUrlConverter(data, params); + try { + response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody(); + } catch (HttpClientErrorException e) { + throw e; + } + } else if (data.getSecurityType().equals(BASIC_AUTH)) { + // encoding the username and password + String plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword()); + byte[] plainCredsBytes = plainCreds.getBytes(); + byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); + String base64Creds = new String(base64CredsBytes); + + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic " + base64Creds); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(headers); + + String url = microserviceUrlConverter(data, params); + try { + response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody(); + } catch (HttpClientErrorException e) { + throw e; + } + } else if (data.getSecurityType().equals(COOKIE_AUTH)) { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + String rawCookie = request.getHeader("Cookie"); + headers.add("Cookie", rawCookie); + HttpEntity<String> entity = new HttpEntity<String>(headers); + + String url = microserviceUrlConverter(data, params); + try { + response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody(); + } catch (HttpClientErrorException e) { + throw e; + } + } + return response; + } + + private String decryptedPassword(String encryptedPwd) throws Exception { + String result = ""; + if (encryptedPwd != null & encryptedPwd.length() > 0) { + try { + result = CipherUtil.decrypt(encryptedPwd, + SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e); + throw e; + } + } + return result; + } + + private String microserviceUrlConverter(MicroserviceData data, List<MicroserviceParameter> params) { + String url = data.getUrl(); + for (int i = 0; i < params.size(); i++) { + if (i == 0) { + url += QUESTION_MARK; + } + url += params.get(i).getPara_key() + "=" + params.get(i).getPara_value(); + if (i != (params.size() - 1)) { + url += ADD_MARK; + } + } + return url; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceService.java index cfc7ddb1..df55abb4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceService.java @@ -1,86 +1,87 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalapp.portal.domain.MicroserviceData;
-import org.openecomp.portalapp.portal.domain.MicroserviceParameter;
-
-public interface MicroserviceService {
-
- /**
- * Get all microservices from the ep_microservice
- *
- * @return list of all microservices
- * @throws Exception
- */
- List<MicroserviceData> getMicroserviceData() throws Exception;
-
- /**
- * Gets the specified microservice with id from ep_microservice
- *
- * @param id
- * ID of microservice to be fetched
- * @return the microservice with the specified id
- */
- MicroserviceData getMicroserviceDataById(long id);
-
- /**
- * Saves the specified microservice to the table ep_microservice
- *
- * @param newService
- * Content of microservice to be saved
- * @return new microservice id
- * @throws Exception
- */
- Long saveMicroservice(MicroserviceData newService) throws Exception;
-
- void saveServiceParameters(long serviceId, List<MicroserviceParameter> list) throws Exception;
-
- /**
- * Deletes the specified microservice from all tables where the serviceId is
- * used
- *
- * @param serviceId
- * @throws Exception
- */
- void deleteMicroservice(long serviceId) throws Exception;
-
- /**
- * Updates the specified microservice from all tables where the serviceId is
- * used
- *
- * @param serviceId
- * Id of microservice to be updated
- * @param newService
- * Content of microservice to be updated
- * @throws Exception
- */
- void updateMicroservice(long serviceId, MicroserviceData newService) throws Exception;
-
- /**
- * Gets the Service parameters by the service Id
- * @param serviceId
- * @return
- */
- List<MicroserviceParameter> getParametersById(long serviceId);
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.MicroserviceData; +import org.openecomp.portalapp.portal.domain.MicroserviceParameter; + +public interface MicroserviceService { + + /** + * Get all microservices from the ep_microservice + * + * @return list of all microservices + * @throws Exception + */ + List<MicroserviceData> getMicroserviceData() throws Exception; + + /** + * Gets the specified microservice with id from ep_microservice + * + * @param id + * ID of microservice to be fetched + * @return the microservice with the specified id + */ + MicroserviceData getMicroserviceDataById(long id); + + /** + * Saves the specified microservice to the table ep_microservice + * + * @param newService + * Content of microservice to be saved + * @return new microservice id + * @throws Exception + */ + Long saveMicroservice(MicroserviceData newService) throws Exception; + + void saveServiceParameters(long serviceId, List<MicroserviceParameter> list) throws Exception; + + /** + * Deletes the specified microservice from all tables where the serviceId is + * used + * + * @param serviceId + * @throws Exception + */ + void deleteMicroservice(long serviceId) throws Exception; + + /** + * Updates the specified microservice from all tables where the serviceId is + * used + * + * @param serviceId + * Id of microservice to be updated + * @param newService + * Content of microservice to be updated + * @throws Exception + */ + void updateMicroservice(long serviceId, MicroserviceData newService) throws Exception; + + /** + * Gets the Service parameters by the service Id + * + * @param serviceId + * @return List<MicroserviceParameter> + */ + List<MicroserviceParameter> getParametersById(long serviceId); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceServiceImpl.java index c0a2fa41..aaadfa18 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/MicroserviceServiceImpl.java @@ -1,212 +1,195 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.Transaction;
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Restrictions;
-import org.openecomp.portalapp.portal.domain.BasicAuthCredentials;
-import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail;
-import org.openecomp.portalapp.portal.domain.MicroserviceData;
-import org.openecomp.portalapp.portal.domain.MicroserviceParameter;
-import org.openecomp.portalapp.portal.domain.WidgetCatalog;
-import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders;
-import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.core.ParameterizedTypeReference;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.ResponseEntity;
-import org.springframework.stereotype.Service;
-import org.springframework.web.client.RestTemplate;
-
-@Service("microserviceService")
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class MicroserviceServiceImpl implements MicroserviceService {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceServiceImpl.class);
-
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @Autowired
- private SessionFactory sessionFactory;
-
- public Long saveMicroservice(MicroserviceData newService) throws Exception {
- if (newService.getPassword() != null)
- newService.setPassword(encryptedPassword(newService.getPassword()));
- getDataAccessService().saveDomainObject(newService, null);
- return newService.getId();
- }
-
- public void saveServiceParameters(long serviceId, List<MicroserviceParameter> list) throws Exception {
- for (int i = 0; i < list.size(); i++) {
- MicroserviceParameter para = list.get(i);
- para.setServiceId(serviceId);
- getDataAccessService().saveDomainObject(para, null);
- }
- }
-
- @Override
- public MicroserviceData getMicroserviceDataById(long id) {
- MicroserviceData data = null;
- try {
- data = (MicroserviceData) dataAccessService
- .getList(MicroserviceData.class, " where id = '" + id + "'", null, null).get(0);
- data.setParameterList(getServiceParameters(id));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "getMicroserviceDataById failed", e);
- throw e;
- }
- return data;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<MicroserviceData> getMicroserviceData() throws Exception {
- List<MicroserviceData> list = (List<MicroserviceData>) dataAccessService.getList(MicroserviceData.class, null);
- for (int i = 0; i < list.size(); i++) {
- if (list.get(i).getPassword() != null)
- list.get(i).setPassword(decryptedPassword(list.get(i).getPassword()));
- list.get(i).setParameterList(getServiceParameters(list.get(i).getId()));
- }
- return list;
- }
-
- @SuppressWarnings("unchecked")
- private List<MicroserviceParameter> getServiceParameters(long serviceId) {
- List<MicroserviceParameter> list = (List<MicroserviceParameter>) dataAccessService
- .getList(MicroserviceParameter.class, " where service_id = '" + serviceId + "'", null, null);
- return list;
- }
-
- @Override
- public void deleteMicroservice(long serviceId) throws Exception {
-
- try {
- Map<String, String> params = new HashMap<String, String>();
- params.put("serviceId", Long.toString(serviceId));
-
- dataAccessService.executeNamedQuery("deleteMicroserviceParameter", params, null);
- dataAccessService.executeNamedQuery("deleteMicroservice", params, null);
-
- } catch (Exception e) {
- e.printStackTrace();
- logger.error(EELFLoggerDelegate.errorLogger, "deleteMicroservice failed", e);
- throw e;
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public void updateMicroservice(long serviceId, MicroserviceData newService) throws Exception {
- try {
- newService.setId(serviceId);
- if (newService.getPassword() != null)
- newService.setPassword(encryptedPassword(newService.getPassword()));
- getDataAccessService().saveDomainObject(newService, null);
- List<MicroserviceParameter> oldService = getServiceParameters(serviceId);
- boolean foundParam;
- for (int i = 0; i < oldService.size(); i++) {
- foundParam = false;
- for (int n = 0; n < newService.getParameterList().size(); n++) {
- if (newService.getParameterList().get(n).getId() == oldService.get(i).getId()) {
- foundParam = true;
- break;
- }
- }
- if (foundParam == false) {
- MicroserviceParameter pd = oldService.get(i);
- Session localSession = sessionFactory.openSession();
- localSession.delete(pd);
- localSession.flush();
- localSession.clear();
- }
-
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "updateMicroservice failed", e);
- throw e;
- }
- saveServiceParameters(serviceId, newService.getParameterList());
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public List<MicroserviceParameter> getParametersById(long serviceId) {
- List<Criterion> restrictionsList = new ArrayList<Criterion>();
- Criterion contextIdCrit = Restrictions.eq("serviceId", serviceId);
- restrictionsList.add(contextIdCrit);
- List<MicroserviceParameter> list = (List<MicroserviceParameter>) dataAccessService
- .getList(MicroserviceParameter.class, null, restrictionsList, null);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "getParametersById: microservice parameters list size: " + list.size());
- return list;
- }
-
- private String decryptedPassword(String encryptedPwd) throws Exception {
- String result = "";
- if (encryptedPwd != null & encryptedPwd.length() > 0) {
- try {
- result = CipherUtil.decrypt(encryptedPwd,
- SystemProperties.getProperty(SystemProperties.Decryption_Key));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
- throw e;
- }
- }
- return result;
- }
-
- private String encryptedPassword(String decryptedPwd) throws Exception {
- String result = "";
- if (decryptedPwd != null & decryptedPwd.length() > 0) {
- try {
- result = CipherUtil.encrypt(decryptedPwd,
- SystemProperties.getProperty(SystemProperties.Decryption_Key));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed", e);
- throw e;
- }
- }
- return result;
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.openecomp.portalapp.portal.domain.MicroserviceData; +import org.openecomp.portalapp.portal.domain.MicroserviceParameter; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +@Service("microserviceService") +@EnableAspectJAutoProxy +@EPMetricsLog +public class MicroserviceServiceImpl implements MicroserviceService { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + public Long saveMicroservice(MicroserviceData newService) throws Exception { + if (newService.getPassword() != null) + newService.setPassword(encryptedPassword(newService.getPassword())); + getDataAccessService().saveDomainObject(newService, null); + return newService.getId(); + } + + public void saveServiceParameters(long serviceId, List<MicroserviceParameter> list) throws Exception { + for (int i = 0; i < list.size(); i++) { + MicroserviceParameter para = list.get(i); + para.setServiceId(serviceId); + getDataAccessService().saveDomainObject(para, null); + } + } + + @Override + public MicroserviceData getMicroserviceDataById(long id) { + MicroserviceData data = null; + try { + data = (MicroserviceData) dataAccessService + .getList(MicroserviceData.class, " where id = '" + id + "'", null, null).get(0); + data.setParameterList(getServiceParameters(id)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getMicroserviceDataById failed", e); + throw e; + } + return data; + } + + @SuppressWarnings("unchecked") + @Override + public List<MicroserviceData> getMicroserviceData() throws Exception { + List<MicroserviceData> list = (List<MicroserviceData>) dataAccessService.getList(MicroserviceData.class, null); + for (int i = 0; i < list.size(); i++) { + if (list.get(i).getPassword() != null) + list.get(i).setPassword(decryptedPassword(list.get(i).getPassword())); + list.get(i).setParameterList(getServiceParameters(list.get(i).getId())); + } + return list; + } + + @SuppressWarnings("unchecked") + private List<MicroserviceParameter> getServiceParameters(long serviceId) { + List<MicroserviceParameter> list = (List<MicroserviceParameter>) dataAccessService + .getList(MicroserviceParameter.class, " where service_id = '" + serviceId + "'", null, null); + return list; + } + + @Override + public void deleteMicroservice(long serviceId) throws Exception { + + try { + Map<String, String> params = new HashMap<String, String>(); + params.put("serviceId", Long.toString(serviceId)); + + dataAccessService.executeNamedQuery("deleteMicroserviceParameter", params, null); + dataAccessService.executeNamedQuery("deleteMicroservice", params, null); + + } catch (Exception e) { + e.printStackTrace(); + logger.error(EELFLoggerDelegate.errorLogger, "deleteMicroservice failed", e); + throw e; + } + } + + @SuppressWarnings("unchecked") + @Override + public void updateMicroservice(long serviceId, MicroserviceData newService) throws Exception { + try { + newService.setId(serviceId); + if (newService.getPassword() != null) + newService.setPassword(encryptedPassword(newService.getPassword())); + getDataAccessService().saveDomainObject(newService, null); + List<MicroserviceParameter> oldService = getServiceParameters(serviceId); + boolean foundParam; + for (int i = 0; i < oldService.size(); i++) { + foundParam = false; + for (int n = 0; n < newService.getParameterList().size(); n++) { + if (newService.getParameterList().get(n).getId().equals(oldService.get(i).getId())) { + foundParam = true; + break; + } + } + if (foundParam == false) { + MicroserviceParameter pd = oldService.get(i); + getDataAccessService().deleteDomainObject(pd, null); + } + } + for (int i = 0; i < newService.getParameterList().size(); i++) { + MicroserviceParameter param = newService.getParameterList().get(i); + param.setServiceId(serviceId); + getDataAccessService().saveDomainObject(param, null); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "updateMicroservice failed", e); + throw e; + } + saveServiceParameters(serviceId, newService.getParameterList()); + } + + @Override + @SuppressWarnings("unchecked") + public List<MicroserviceParameter> getParametersById(long serviceId) { + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion contextIdCrit = Restrictions.eq("serviceId", serviceId); + restrictionsList.add(contextIdCrit); + List<MicroserviceParameter> list = (List<MicroserviceParameter>) dataAccessService + .getList(MicroserviceParameter.class, null, restrictionsList, null); + logger.debug(EELFLoggerDelegate.debugLogger, + "getParametersById: microservice parameters list size: " + list.size()); + return list; + } + + private String decryptedPassword(String encryptedPwd) throws Exception { + String result = ""; + if (encryptedPwd != null & encryptedPwd.length() > 0) { + try { + result = CipherUtil.decrypt(encryptedPwd, + SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e); + throw e; + } + } + return result; + } + + private String encryptedPassword(String decryptedPwd) throws Exception { + String result = ""; + if (decryptedPwd != null & decryptedPwd.length() > 0) { + try { + result = CipherUtil.encrypt(decryptedPwd, + SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed", e); + throw e; + } + } + return result; + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppService.java index 7874fa74..af957dc4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppService.java @@ -1,42 +1,42 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EPUser;
-
-public interface PersUserAppService {
-
- /**
- * Sets the appropriate code in the user personalization table to indicate
- * the application is (de)selected and/or pending.
- *
- * @param user
- * EP User
- * @param app
- * EP Application
- * @param select
- * True or false
- * @param select
- * True or false
- */
- void setPersUserAppValue(EPUser user, EPApp app, boolean select, boolean pending);
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPUser; + +public interface PersUserAppService { + + /** + * Sets the appropriate code in the user personalization table to indicate + * the application is (de)selected and/or pending. + * + * @param user + * EP User + * @param app + * EP Application + * @param select + * True or false + * @param pending + * True or false + */ + void setPersUserAppValue(EPUser user, EPApp app, boolean select, boolean pending); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppServiceImpl.java index 6ff10ab4..243b61eb 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppServiceImpl.java @@ -1,141 +1,141 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EPUserApp;
-import org.openecomp.portalapp.portal.domain.PersUserAppSelection;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-
-@Service("persUserAppService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class PersUserAppServiceImpl implements PersUserAppService {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PersUserAppServiceImpl.class);
-
- @Autowired
- private DataAccessService dataAccessService;
- @Autowired
- private AdminRolesService adminRolesService;
- @Autowired
- private UserRolesService userRolesService;
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalapp.portal.service.UserAppSelectService#
- * setAppCatalogSelection(org.openecomp.portalapp.portal.domain.EPUser,
- * org.openecomp.portalapp.portal.transport.AppCatalogSelection)
- */
- @Override
- public void setPersUserAppValue(EPUser user, EPApp app, boolean select, boolean pending) {
- if (user == null || app == null)
- throw new IllegalArgumentException("setPersUserAppValue: Null values");
-
- // Find the record for this user-app combo, if any
- String filter = " where user_id = " + Long.toString(user.getId()) + " and app_id = "
- + Long.toString(app.getId());
- @SuppressWarnings("unchecked")
- List<PersUserAppSelection> persList = dataAccessService.getList(PersUserAppSelection.class, filter, null, null);
-
- // Key constraint limits to 1 row
- PersUserAppSelection persRow = null;
- if (persList.size() == 1)
- persRow = persList.get(0);
- else
- persRow = new PersUserAppSelection(null, user.getId(), app.getId(), null);
-
- if (app.getOpen()) {
- // Pending status is not meaningful for open apps.
- if (pending)
- logger.error(EELFLoggerDelegate.errorLogger,
- "setPersUserAppValue: invalid request, ignoring set-pending for open app");
-
- // Open apps have same behavior for regular and admin users
- if (select) {
- // Selection of an open app requires a record
- persRow.setStatusCode("S"); // show
- dataAccessService.saveDomainObject(persRow, null);
- } else {
- // De-selection of an open app requires no record
- if (persRow.getId() != null)
- dataAccessService.deleteDomainObject(persRow, null);
- }
- } else {
- // Non-open app.
-
- // Pending overrides select.
- if (pending) {
- persRow.setStatusCode("P");
- dataAccessService.saveDomainObject(persRow, null);
- } else {
- // Behavior depends on Portal (super) admin status, bcos an
- // admin can force an app onto the dashboard.
- boolean isPortalAdmin = adminRolesService.isSuperAdmin(user);
- boolean adminUserHasAppRole = false;
- if (isPortalAdmin) {
- List<EPUserApp> roles = userRolesService.getCachedAppRolesForUser(app.getId(), user.getId());
- adminUserHasAppRole = (roles.size() > 0);
- logger.debug(EELFLoggerDelegate.debugLogger, "setPersUserAppValue: app {}, admin user {}, role count {}",
- app.getId(), user.getId(), roles.size());
- }
-
- if (select) {
- if (isPortalAdmin && !adminUserHasAppRole) {
- // The special case: portal admin, no role
- persRow.setStatusCode("S"); // show
- dataAccessService.saveDomainObject(persRow, null);
- } else {
- // User has role-based access to the app.
- // Showing an accessible app requires no record.
- if (persRow.getId() != null)
- dataAccessService.deleteDomainObject(persRow, null);
- }
- } // select
- else {
- if (isPortalAdmin && !adminUserHasAppRole) {
- // The special case: portal admin, no role
- if (persRow.getId() != null)
- dataAccessService.deleteDomainObject(persRow, null);
- } else {
- // User has role-based access to the app.
- // Hiding an accessible app requires a record
- persRow.setStatusCode("H"); // hide
- dataAccessService.saveDomainObject(persRow, null);
- }
- } // deselect
- }
- }
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.domain.PersUserAppSelection; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; + +@Service("persUserAppService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class PersUserAppServiceImpl implements PersUserAppService { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PersUserAppServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + @Autowired + private AdminRolesService adminRolesService; + @Autowired + private UserRolesService userRolesService; + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.UserAppSelectService# + * setAppCatalogSelection(org.openecomp.portalapp.portal.domain.EPUser, + * org.openecomp.portalapp.portal.transport.AppCatalogSelection) + */ + @Override + public void setPersUserAppValue(EPUser user, EPApp app, boolean select, boolean pending) { + if (user == null || app == null) + throw new IllegalArgumentException("setPersUserAppValue: Null values"); + + // Find the record for this user-app combo, if any + String filter = " where user_id = " + Long.toString(user.getId()) + " and app_id = " + + Long.toString(app.getId()); + @SuppressWarnings("unchecked") + List<PersUserAppSelection> persList = dataAccessService.getList(PersUserAppSelection.class, filter, null, null); + + // Key constraint limits to 1 row + PersUserAppSelection persRow = null; + if (persList.size() == 1) + persRow = persList.get(0); + else + persRow = new PersUserAppSelection(null, user.getId(), app.getId(), null); + + if (app.getOpen()) { + // Pending status is not meaningful for open apps. + if (pending) + logger.error(EELFLoggerDelegate.errorLogger, + "setPersUserAppValue: invalid request, ignoring set-pending for open app"); + + // Open apps have same behavior for regular and admin users + if (select) { + // Selection of an open app requires a record + persRow.setStatusCode("S"); // show + dataAccessService.saveDomainObject(persRow, null); + } else { + // De-selection of an open app requires no record + if (persRow.getId() != null) + dataAccessService.deleteDomainObject(persRow, null); + } + } else { + // Non-open app. + + // Pending overrides select. + if (pending) { + persRow.setStatusCode("P"); + dataAccessService.saveDomainObject(persRow, null); + } else { + // Behavior depends on Portal (super) admin status, bcos an + // admin can force an app onto the dashboard. + boolean isPortalAdmin = adminRolesService.isSuperAdmin(user); + boolean adminUserHasAppRole = false; + if (isPortalAdmin) { + List<EPUserApp> roles = userRolesService.getCachedAppRolesForUser(app.getId(), user.getId()); + adminUserHasAppRole = (roles.size() > 0); + logger.debug(EELFLoggerDelegate.debugLogger, "setPersUserAppValue: app {}, admin user {}, role count {}", + app.getId(), user.getId(), roles.size()); + } + + if (select) { + if (isPortalAdmin) { + // The special case: portal admin + persRow.setStatusCode("S"); // show + dataAccessService.saveDomainObject(persRow, null); + } else { + // User has role-based access to the app. + // Showing an accessible app requires no record. + if (persRow.getId() != null) + dataAccessService.deleteDomainObject(persRow, null); + } + } // select + else { + if (isPortalAdmin && !adminUserHasAppRole) { + // The special case: portal admin, no role + if (persRow.getId() != null) + dataAccessService.deleteDomainObject(persRow, null); + } else { + // User has role-based access to the app. + // Hiding an accessible app requires a record + persRow.setStatusCode("H"); // hide + dataAccessService.saveDomainObject(persRow, null); + } + } // deselect + } + } + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserWidgetService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserWidgetService.java index d3a46d98..1b18e65d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserWidgetService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserWidgetService.java @@ -1,41 +1,39 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import org.openecomp.portalapp.portal.domain.EPUser;
-
-public interface PersUserWidgetService {
-
- /**
- * Sets the appropriate code in the user personalization table to indicate
- * the application is (de)selected and/or pending.
- *
- * @param user
- * EP User
- * @param app
- * EP Application
- * @param select
- * True or false
- * @param select
- * True or false
- */
- void setPersUserAppValue(EPUser user, Long widgetId, boolean select);
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import org.openecomp.portalapp.portal.domain.EPUser; + +public interface PersUserWidgetService { + + /** + * Sets the appropriate code in the user personalization table to indicate + * the application is (de)selected and/or pending. + * + * @param user + * EP User + * @param widgetId + * widget + * @param select + * True or false + */ + void setPersUserAppValue(EPUser user, Long widgetId, boolean select); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserWidgetServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserWidgetServiceImpl.java index 9a45dea6..189b3107 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserWidgetServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PersUserWidgetServiceImpl.java @@ -1,81 +1,81 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.PersUserWidgetSelection;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-
-@Service("persUserWidgetService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class PersUserWidgetServiceImpl implements PersUserWidgetService{
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PersUserAppServiceImpl.class);
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @Override
- public void setPersUserAppValue(EPUser user, Long widgetId, boolean select) {
- if (user == null || widgetId == null)
- throw new IllegalArgumentException("setPersUserAppValue: Null values");
-
- String filter = " where user_id = " + Long.toString(user.getId()) + " and widget_id = "
- + Long.toString(widgetId);
- @SuppressWarnings("unchecked")
- List<PersUserWidgetSelection> persList = dataAccessService.getList(PersUserWidgetSelection.class, filter, null, null);
-
- // Key constraint limits to 1 row
- PersUserWidgetSelection persRow = null;
- if (persList.size() == 1){
- persRow = persList.get(0);
- }
- else {
- persRow = new PersUserWidgetSelection(null, user.getId(), widgetId, null);
- }
- if(select){
- if (persRow.getId() != null){
- dataAccessService.deleteDomainObject(persRow, null);
- }
- persRow.setStatusCode("S"); // show
- dataAccessService.saveDomainObject(persRow, null);
- } else{
- if (persRow.getId() != null){
- dataAccessService.deleteDomainObject(persRow, null);
- }
- persRow.setStatusCode("H"); // Hide
- dataAccessService.saveDomainObject(persRow, null);
- }
-
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.PersUserWidgetSelection; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; + +@Service("persUserWidgetService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class PersUserWidgetServiceImpl implements PersUserWidgetService{ + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PersUserAppServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + @Override + public void setPersUserAppValue(EPUser user, Long widgetId, boolean select) { + if (user == null || widgetId == null) + throw new IllegalArgumentException("setPersUserAppValue: Null values"); + + String filter = " where user_id = " + Long.toString(user.getId()) + " and widget_id = " + + Long.toString(widgetId); + @SuppressWarnings("unchecked") + List<PersUserWidgetSelection> persList = dataAccessService.getList(PersUserWidgetSelection.class, filter, null, null); + + // Key constraint limits to 1 row + PersUserWidgetSelection persRow = null; + if (persList.size() == 1){ + persRow = persList.get(0); + } + else { + persRow = new PersUserWidgetSelection(null, user.getId(), widgetId, null); + } + if(select){ + if (persRow.getId() != null){ + dataAccessService.deleteDomainObject(persRow, null); + } + persRow.setStatusCode("S"); // show + dataAccessService.saveDomainObject(persRow, null); + } else{ + if (persRow.getId() != null){ + dataAccessService.deleteDomainObject(persRow, null); + } + persRow.setStatusCode("H"); // Hide + dataAccessService.saveDomainObject(persRow, null); + } + + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminService.java index 55b3afd6..ebbe52f3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminService.java @@ -1,31 +1,31 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.PortalAdmin;
-
-public interface PortalAdminService {
- List<PortalAdmin> getPortalAdmins ();
- FieldsValidator createPortalAdmin(String orgUserId);
- FieldsValidator deletePortalAdmin(Long userId);
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.PortalAdmin; + +public interface PortalAdminService { + List<PortalAdmin> getPortalAdmins (); + FieldsValidator createPortalAdmin(String orgUserId); + FieldsValidator deletePortalAdmin(Long userId); +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java index 639bfc4c..0963f048 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java @@ -1,210 +1,207 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import javax.annotation.PostConstruct;
-import javax.servlet.http.HttpServletResponse;
-
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.Transaction;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.stereotype.Service;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.PortalAdmin;
-import org.openecomp.portalapp.portal.transport.PortalAdminUserRole;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-
-@Service("portalAdminService")
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class PortalAdminServiceImpl implements PortalAdminService {
-
- private String SYS_ADMIN_ROLE_ID = "1";
- private String ECOMP_APP_ID = "1";
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminServiceImpl.class);
-
- @Autowired
- private SessionFactory sessionFactory;
- @Autowired
- private DataAccessService dataAccessService;
- @Autowired
- SearchService searchService;
-
- @PostConstruct
- private void init() {
- SYS_ADMIN_ROLE_ID = SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID);
- ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
- }
-
- public List<PortalAdmin> getPortalAdmins() {
- try {
- String sql = "SELECT u.user_id, u.first_name, u.last_name, u.login_id "
- + " FROM fn_user u, fn_user_role ur WHERE u.user_id = ur.user_id AND ur.role_id="
- + SYS_ADMIN_ROLE_ID;
- logQuery(sql);
-
- @SuppressWarnings("unchecked")
- List<PortalAdmin> portalAdmins = dataAccessService.executeSQLQuery(sql, PortalAdmin.class, null);
- logger.debug(EELFLoggerDelegate.debugLogger, "getPortalAdmins was successful");
- return portalAdmins;
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred while performing getPortalAdmins operation, Details: "
- + EcompPortalUtils.getStackTrace(e));
- return null;
- }
- }
-
- @SuppressWarnings("unchecked")
- public FieldsValidator createPortalAdmin(String orgUserId) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: createPortalAdmin: test 1");
- boolean result = false;
- EPUser user = null;
- boolean createNewUser = false;
- List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where orgUserId='" + orgUserId + "'",
- null, null);
- if (localUserList.size() > 0) {
- user = localUserList.get(0);
- } else {
- createNewUser = true;
- }
-
- if (user!=null && isLoggedInUserPortalAdmin(user.getId())) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
- logger.error(EELFLoggerDelegate.errorLogger, "User '" + user.getOrgUserId() + "' already has PortalAdmin role assigned.");
- }
- else if (user != null || createNewUser) {
- Session localSession = null;
- Transaction transaction = null;
- try {
- localSession = sessionFactory.openSession();
-
- transaction = localSession.beginTransaction();
- if (createNewUser) {
- user = this.searchService.searchUserByUserId(orgUserId);
- if (user != null) {
- // insert the user with active true in order to
- // pass login phase.
- user.setActive(true);
- localSession.save(EPUser.class.getName(), user);
- }
- }
- if (user != null) {
- Long userid = user.getId();
- PortalAdminUserRole userRole = new PortalAdminUserRole();
- userRole.userId = userid;
- userRole.roleId = Long.valueOf(SYS_ADMIN_ROLE_ID);
- userRole.appId = Long.valueOf(ECOMP_APP_ID);
-
- localSession.save(PortalAdminUserRole.class.getName(), userRole);
- }
- // logger.debug(EELFLoggerDelegate.debugLogger, "after saving menu object, new id: " + userid);
-
- transaction.commit();
- result = true;
- } catch (Exception e) {
- EcompPortalUtils.rollbackTransaction(transaction,
- "createPortalAdmin rollback, exception = " + e);
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "createPortalAdmin");
- }
- if (!result) {
- logger.debug(EELFLoggerDelegate.debugLogger, "LR: createPortalAdmin: no result. setting httpStatusCode to "
- + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- logger.error(EELFLoggerDelegate.errorLogger, "PortalAdminServiceImpl.createPortalAdmin: bad request");
- }
- }
- return fieldsValidator;
- }
-
- public FieldsValidator deletePortalAdmin(Long userId) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- logger.debug(EELFLoggerDelegate.debugLogger, "deletePortalAdmin: test 1");
- boolean result = false;
- Session localSession = null;
- Transaction transaction = null;
-
- try {
- localSession = sessionFactory.openSession();
- transaction = localSession.beginTransaction();
- dataAccessService.deleteDomainObjects(PortalAdminUserRole.class,
- "user_id='" + userId + "' AND role_id='" + SYS_ADMIN_ROLE_ID + "'", null);
- transaction.commit();
- result = true;
- } catch (Exception e) {
- EcompPortalUtils.rollbackTransaction(transaction, "deletePortalAdmin rollback, exception = " + e);
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "deletePortalAdmin");
- }
- if (result) {
- } else {
- logger.debug(EELFLoggerDelegate.debugLogger, "deletePortalAdmin: no result. setting httpStatusCode to "
- + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- return fieldsValidator;
- }
-
- private void logQuery(String sql) {
- logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
- }
-
- private boolean isLoggedInUserPortalAdmin(Long userId) {
- try {
- String sql = "SELECT u.user_id, u.first_name, u.last_name, u.login_id " +
- " FROM fn_user u, fn_user_role ur " +
- " WHERE u.user_id = ur.user_id " +
- " AND ur.user_id=" + userId +
- " AND ur.role_id=" + SYS_ADMIN_ROLE_ID;
-
- logQuery(sql);
-
- @SuppressWarnings("unchecked")
- List<PortalAdmin> portalAdmins = dataAccessService.executeSQLQuery(sql, PortalAdmin.class, null);
- logger.debug(EELFLoggerDelegate.debugLogger, portalAdmins.toString());
- if (portalAdmins==null || portalAdmins.size()<=0) {
- return false;
- }
- return true;
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing isLoggedInUserPortalAdmin operation, Details: " + EcompPortalUtils.getStackTrace(e));
- return false;
- }
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.PortalAdmin; +import org.openecomp.portalapp.portal.transport.PortalAdminUserRole; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +@Service("portalAdminService") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class PortalAdminServiceImpl implements PortalAdminService { + + private String SYS_ADMIN_ROLE_ID = "1"; + private String ECOMP_APP_ID = "1"; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminServiceImpl.class); + + @Autowired + private SessionFactory sessionFactory; + @Autowired + private DataAccessService dataAccessService; + @Autowired + SearchService searchService; + + @PostConstruct + private void init() { + SYS_ADMIN_ROLE_ID = SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID); + ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID); + } + + public List<PortalAdmin> getPortalAdmins() { + try { + Map<String, String> params = new HashMap<>(); + params.put("adminRoleId", SYS_ADMIN_ROLE_ID); + @SuppressWarnings("unchecked") + List<PortalAdmin> portalAdmins = (List<PortalAdmin>) dataAccessService.executeNamedQuery("getPortalAdmins", + params, null); + logger.debug(EELFLoggerDelegate.debugLogger, "getPortalAdmins was successful"); + return portalAdmins; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while performing getPortalAdmins operation, Details: " + + EcompPortalUtils.getStackTrace(e)); + return null; + } + } + + @SuppressWarnings("unchecked") + public FieldsValidator createPortalAdmin(String orgUserId) { + FieldsValidator fieldsValidator = new FieldsValidator(); + logger.debug(EELFLoggerDelegate.debugLogger, "LR: createPortalAdmin: test 1"); + boolean result = false; + EPUser user = null; + boolean createNewUser = false; + List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where orgUserId='" + orgUserId + "'", + null, null); + if (localUserList.size() > 0) { + user = localUserList.get(0); + } else { + createNewUser = true; + } + + if (user != null && isLoggedInUserPortalAdmin(user.getId())) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT); + logger.error(EELFLoggerDelegate.errorLogger, + "User '" + user.getOrgUserId() + "' already has PortalAdmin role assigned."); + } else if (user != null || createNewUser) { + Session localSession = null; + Transaction transaction = null; + try { + localSession = sessionFactory.openSession(); + + transaction = localSession.beginTransaction(); + if (createNewUser) { + user = this.searchService.searchUserByUserId(orgUserId); + if (user != null) { + // insert the user with active true in order to + // pass login phase. + user.setActive(true); + localSession.save(EPUser.class.getName(), user); + } + } + if (user != null) { + Long userid = user.getId(); + PortalAdminUserRole userRole = new PortalAdminUserRole(); + userRole.userId = userid; + userRole.roleId = Long.valueOf(SYS_ADMIN_ROLE_ID); + userRole.appId = Long.valueOf(ECOMP_APP_ID); + + localSession.save(PortalAdminUserRole.class.getName(), userRole); + } + + transaction.commit(); + result = true; + } catch (Exception e) { + EcompPortalUtils.rollbackTransaction(transaction, "createPortalAdmin rollback, exception = " + e); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "createPortalAdmin"); + } + if (!result) { + logger.debug(EELFLoggerDelegate.debugLogger, + "LR: createPortalAdmin: no result. setting httpStatusCode to " + + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + logger.error(EELFLoggerDelegate.errorLogger, "PortalAdminServiceImpl.createPortalAdmin: bad request"); + } + } + return fieldsValidator; + } + + public FieldsValidator deletePortalAdmin(Long userId) { + FieldsValidator fieldsValidator = new FieldsValidator(); + logger.debug(EELFLoggerDelegate.debugLogger, "deletePortalAdmin: test 1"); + boolean result = false; + Session localSession = null; + Transaction transaction = null; + + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + dataAccessService.deleteDomainObjects(PortalAdminUserRole.class, + "user_id='" + userId + "' AND role_id='" + SYS_ADMIN_ROLE_ID + "'", null); + transaction.commit(); + result = true; + } catch (Exception e) { + EcompPortalUtils.rollbackTransaction(transaction, "deletePortalAdmin rollback, exception = " + e); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "deletePortalAdmin"); + } + if (result) { + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "deletePortalAdmin: no result. setting httpStatusCode to " + + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return fieldsValidator; + } + + private void logQuery(String sql) { + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + } + + private boolean isLoggedInUserPortalAdmin(Long userId) { + try { + String sql = "SELECT u.user_id, u.first_name, u.last_name, u.login_id " + + " FROM fn_user u, fn_user_role ur " + " WHERE u.user_id = ur.user_id " + " AND ur.user_id=" + + userId + " AND ur.role_id=" + SYS_ADMIN_ROLE_ID; + + logQuery(sql); + + @SuppressWarnings("unchecked") + List<PortalAdmin> portalAdmins = dataAccessService.executeSQLQuery(sql, PortalAdmin.class, null); + logger.debug(EELFLoggerDelegate.debugLogger, portalAdmins.toString()); + if (portalAdmins == null || portalAdmins.size() <= 0) { + return false; + } + return true; + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while performing isLoggedInUserPortalAdmin operation, Details: " + + EcompPortalUtils.getStackTrace(e)); + return false; + } + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java index 9aa24692..cf88fb7f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java @@ -1,30 +1,30 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import org.openecomp.portalapp.portal.domain.EPUser;
-
-public interface SearchService {
-
- public String searchUsersInPhoneBook(String searchString);
-
- public EPUser searchUserByUserId(String orgUserId);
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import org.openecomp.portalapp.portal.domain.EPUser; + +public interface SearchService { + + public String searchUsersInPhoneBook(String searchString); + + public EPUser searchUserByUserId(String orgUserId); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java index 88dc299f..a2b56e5a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java @@ -1,175 +1,175 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.ArrayList;
-import java.util.List;
-
-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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalapp.portal.transport.UserWithNameSurnameTitle;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-@Service("searchService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class SearchServiceImpl implements SearchService {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SearchServiceImpl.class);
-
- // TODO: the values below should be defined in other place
- private static final int maxSizeOfSearchResult = 100;
-
-
- @Autowired
- EPLdapService ldapService;
-
- @Override
- public String searchUsersInPhoneBook(String searchString) {
- String orgUserId = null;
- List<String> tokens = EcompPortalUtils.parsingByRegularExpression(searchString, " ");
- for (int i = 0; i < tokens.size(); i++) { // find orgUserId if possible and remove it from tokens
- if (tokens.get(i).matches(".*\\d+.*")) {
- orgUserId = tokens.get(i);
- tokens.remove(i);
- }
- }
- while (tokens.size() > 2) { // we use no more then first 2 tokens (orgUserId is removed, see above)
- tokens.remove(tokens.size() - 1);
- }
- EPUser attrUser = new EPUser();
- attrUser.setOrgUserId(orgUserId);
- List<UserWithNameSurnameTitle> resultOfSearch = new ArrayList<UserWithNameSurnameTitle>(), resultOfAdditionalSearch = null;
- if (tokens.size() == 2) {
- attrUser.setFirstName(tokens.get(0));
- attrUser.setLastName(tokens.get(1));
- resultOfSearch = this.searchUsersByAttrs(attrUser);
- resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0));
- resultOfSearch = this.removeWrongLastNames(resultOfSearch, tokens.get(1));
- if (resultOfSearch.size() < maxSizeOfSearchResult) {
- attrUser.setFirstName(tokens.get(1));
- attrUser.setLastName(tokens.get(0));
- resultOfAdditionalSearch = this.searchUsersByAttrs(attrUser);
- resultOfAdditionalSearch = this.removeWrongFirstNames(resultOfAdditionalSearch, tokens.get(1));
- resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0));
- }
- } else if (tokens.size() == 1) {
- attrUser.setFirstName(tokens.get(0));
- resultOfSearch = this.searchUsersByAttrs(attrUser);
- resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0));
- if (resultOfSearch.size() < maxSizeOfSearchResult) {
- attrUser.setFirstName(null);
- attrUser.setLastName(tokens.get(0));
- resultOfAdditionalSearch = this.searchUsersByAttrs(attrUser);
- resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0));
- }
- } else if (orgUserId != null) {
- resultOfSearch = this.searchUsersByAttrs(attrUser);
- }
- if (resultOfAdditionalSearch != null) {
- resultOfSearch.addAll(resultOfAdditionalSearch);
- }
- resultOfSearch = this.cutSearchResultToMaximumSize(resultOfSearch);
- ObjectMapper mapper = new ObjectMapper();
- String result = "[]";
- try {
- result = mapper.writeValueAsString(resultOfSearch);
- } catch (JsonProcessingException e) {
- logger.error(EELFLoggerDelegate.errorLogger, "searchUsersInPhoneBook Exception = " + EcompPortalUtils.getStackTrace(e));
- }
- return result;
- }
-
- private List<UserWithNameSurnameTitle> searchUsersByAttrs(EPUser attrUser) {
- List<UserWithNameSurnameTitle> foundUsers = new ArrayList<UserWithNameSurnameTitle>();
- try {
- org.openecomp.portalsdk.core.command.support.SearchResult searchResult = this.ldapService.searchPost(attrUser, null, null, null, 0, 0, -1);
- for (Object obj : searchResult) {
- EPUser user = (EPUser) obj;
- UserWithNameSurnameTitle foundUser = new UserWithNameSurnameTitle(user.getOrgUserId(), user.getFirstName(), user.getLastName(), user.getJobTitle());
- foundUsers.add(foundUser);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e));
- }
- return foundUsers;
- }
-
- private List<UserWithNameSurnameTitle> removeWrongFirstNames(List<UserWithNameSurnameTitle> resultOfSearch, String firstName) {
- firstName = firstName.toUpperCase();
- for (int i = resultOfSearch.size() - 1; i >= 0; i--) {
- UserWithNameSurnameTitle user = resultOfSearch.get(i);
- if ((user.firstName == null) || !user.firstName.toUpperCase().startsWith(firstName)) {
- resultOfSearch.remove(i);
- }
- }
- return resultOfSearch;
- }
-
- private List<UserWithNameSurnameTitle> removeWrongLastNames(List<UserWithNameSurnameTitle> resultOfSearch, String lastName) {
- lastName = lastName.toUpperCase();
- for (int i = resultOfSearch.size() - 1; i >= 0; i--) {
- UserWithNameSurnameTitle user = resultOfSearch.get(i);
- if ((user.lastName == null) || !user.lastName.toUpperCase().startsWith(lastName)) {
- resultOfSearch.remove(i);
- }
- }
- return resultOfSearch;
- }
-
- private List<UserWithNameSurnameTitle> cutSearchResultToMaximumSize(List<UserWithNameSurnameTitle> resultOfSearch) {
- for (int i = resultOfSearch.size() - 1; i >= maxSizeOfSearchResult; i--) {
- resultOfSearch.remove(i);
- }
- return resultOfSearch;
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public EPUser searchUserByUserId(String orgUserId) {
- EPUser user = null;
- EPUser searchedUser = new EPUser();
- searchedUser.setOrgUserId(orgUserId);
- try {
- List<Object> searchResult = ldapService.searchPost(searchedUser, "", null, null, 0, -1, 1);
- for (Object obj : searchResult) {
- if (obj instanceof EPUser) {
- user = (EPUser) obj;
- // This assignment should be checked later!
- user.setLoginId(orgUserId);
- break;
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "searchUserBy orgUserId exception = " + EcompPortalUtils.getStackTrace(e));
- }
- return user;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.List; + +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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.transport.UserWithNameSurnameTitle; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Service("searchService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class SearchServiceImpl implements SearchService { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SearchServiceImpl.class); + + // TODO: the values below should be defined in other place + private static final int maxSizeOfSearchResult = 100; + + + @Autowired + EPLdapService ldapService; + + @Override + public String searchUsersInPhoneBook(String searchString) { + String orgUserId = null; + List<String> tokens = EcompPortalUtils.parsingByRegularExpression(searchString, " "); + for (int i = 0; i < tokens.size(); i++) { // find orgUserId if possible and remove it from tokens + if (tokens.get(i).matches(".*\\d+.*")) { + orgUserId = tokens.get(i); + tokens.remove(i); + } + } + while (tokens.size() > 2) { // we use no more then first 2 tokens (orgUserId is removed, see above) + tokens.remove(tokens.size() - 1); + } + EPUser attrUser = new EPUser(); + attrUser.setOrgUserId(orgUserId); + List<UserWithNameSurnameTitle> resultOfSearch = new ArrayList<UserWithNameSurnameTitle>(), resultOfAdditionalSearch = null; + if (tokens.size() == 2) { + attrUser.setFirstName(tokens.get(0)); + attrUser.setLastName(tokens.get(1)); + resultOfSearch = this.searchUsersByAttrs(attrUser); + resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0)); + resultOfSearch = this.removeWrongLastNames(resultOfSearch, tokens.get(1)); + if (resultOfSearch.size() < maxSizeOfSearchResult) { + attrUser.setFirstName(tokens.get(1)); + attrUser.setLastName(tokens.get(0)); + resultOfAdditionalSearch = this.searchUsersByAttrs(attrUser); + resultOfAdditionalSearch = this.removeWrongFirstNames(resultOfAdditionalSearch, tokens.get(1)); + resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0)); + } + } else if (tokens.size() == 1) { + attrUser.setFirstName(tokens.get(0)); + resultOfSearch = this.searchUsersByAttrs(attrUser); + resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0)); + if (resultOfSearch.size() < maxSizeOfSearchResult) { + attrUser.setFirstName(null); + attrUser.setLastName(tokens.get(0)); + resultOfAdditionalSearch = this.searchUsersByAttrs(attrUser); + resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0)); + } + } else if (orgUserId != null) { + resultOfSearch = this.searchUsersByAttrs(attrUser); + } + if (resultOfAdditionalSearch != null) { + resultOfSearch.addAll(resultOfAdditionalSearch); + } + resultOfSearch = this.cutSearchResultToMaximumSize(resultOfSearch); + ObjectMapper mapper = new ObjectMapper(); + String result = "[]"; + try { + result = mapper.writeValueAsString(resultOfSearch); + } catch (JsonProcessingException e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchUsersInPhoneBook Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return result; + } + + private List<UserWithNameSurnameTitle> searchUsersByAttrs(EPUser attrUser) { + List<UserWithNameSurnameTitle> foundUsers = new ArrayList<UserWithNameSurnameTitle>(); + try { + org.openecomp.portalsdk.core.command.support.SearchResult searchResult = this.ldapService.searchPost(attrUser, null, null, null, 0, 0, -1); + for (Object obj : searchResult) { + EPUser user = (EPUser) obj; + UserWithNameSurnameTitle foundUser = new UserWithNameSurnameTitle(user.getOrgUserId(), user.getFirstName(), user.getLastName(), user.getJobTitle()); + foundUsers.add(foundUser); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return foundUsers; + } + + private List<UserWithNameSurnameTitle> removeWrongFirstNames(List<UserWithNameSurnameTitle> resultOfSearch, String firstName) { + firstName = firstName.toUpperCase(); + for (int i = resultOfSearch.size() - 1; i >= 0; i--) { + UserWithNameSurnameTitle user = resultOfSearch.get(i); + if ((user.firstName == null) || !user.firstName.toUpperCase().startsWith(firstName)) { + resultOfSearch.remove(i); + } + } + return resultOfSearch; + } + + private List<UserWithNameSurnameTitle> removeWrongLastNames(List<UserWithNameSurnameTitle> resultOfSearch, String lastName) { + lastName = lastName.toUpperCase(); + for (int i = resultOfSearch.size() - 1; i >= 0; i--) { + UserWithNameSurnameTitle user = resultOfSearch.get(i); + if ((user.lastName == null) || !user.lastName.toUpperCase().startsWith(lastName)) { + resultOfSearch.remove(i); + } + } + return resultOfSearch; + } + + private List<UserWithNameSurnameTitle> cutSearchResultToMaximumSize(List<UserWithNameSurnameTitle> resultOfSearch) { + for (int i = resultOfSearch.size() - 1; i >= maxSizeOfSearchResult; i--) { + resultOfSearch.remove(i); + } + return resultOfSearch; + } + + @Override + @SuppressWarnings("unchecked") + public EPUser searchUserByUserId(String orgUserId) { + EPUser user = null; + EPUser searchedUser = new EPUser(); + searchedUser.setOrgUserId(orgUserId); + try { + List<Object> searchResult = ldapService.searchPost(searchedUser, "", null, null, 0, -1, 1); + for (Object obj : searchResult) { + if (obj instanceof EPUser) { + user = (EPUser) obj; + // This assignment should be checked later! + user.setLoginId(orgUserId); + break; + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchUserBy orgUserId exception = " + EcompPortalUtils.getStackTrace(e)); + } + return user; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextService.java index 0b1a6df7..72f3bcb5 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextService.java @@ -1,98 +1,100 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalapp.portal.domain.SharedContext;
-
-/**
- * Defines the methods exposed by the service that manages shared context
- * objects in the database via Hibernate.
- */
-public interface SharedContextService {
-
- /**
- * Gets all shared context objects for the specified context ID.
- *
- * @return List of SharedContext objects
- */
- List<SharedContext> getSharedContexts(String contextId);
-
- /**
- * Gets the shared context with the specified context ID and key.
- *
- * @param contextId
- * Context ID; usually a session ID
- * @param key
- * Key for the key-value pair
- * @return Value found in the database, null if any parameter is null or no
- * shared context exists with that context ID - key pair.
- */
- SharedContext getSharedContext(String contextId, String key);
-
- /**
- * Creates a new shared context in the database with the specified context
- * ID, key and value.
- *
- * @param context
- * SharedContext object to save.
- * @param key
- * Key for the key-value pair.
- * @param value
- * Value for the key-value pair.
- */
- void addSharedContext(String contextId, String key, String value);
-
- /**
- * Saves the specified shared context to the database.
- *
- * @param context
- * SharedContext object to save.
- */
- void saveSharedContext(SharedContext context);
-
- /**
- * Deletes the specified shared context from the database.
- *
- * @param context
- * SharedContext object to delete.
- */
- void deleteSharedContext(SharedContext context);
-
- /**
- * Deletes all shared contexts with the specified context ID.
- *
- * @param contextId
- * Context ID; usually a session ID
- * @return number of shared-context objects deleted
- */
- int deleteSharedContexts(String contextId);
-
- /**
- * Deletes all shared contexts with a creation time that is older than the
- * specified value.
- *
- * @param ageInSeconds
- * Expiration threshold in seconds
- */
- void expireSharedContexts(int ageInSeconds);
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.SharedContext; + +/** + * Defines the methods exposed by the service that manages shared context + * objects in the database. + */ +public interface SharedContextService { + + /** + * Gets all shared context objects for the specified context ID. + * + * @param contextId + * SharedContext ID + * @return List of SharedContext objects + */ + List<SharedContext> getSharedContexts(String contextId); + + /** + * Gets the shared context with the specified context ID and key. + * + * @param contextId + * Context ID; usually a session ID + * @param key + * Key for the key-value pair + * @return Value found in the database, null if any parameter is null or no + * shared context exists with that context ID - key pair. + */ + SharedContext getSharedContext(String contextId, String key); + + /** + * Creates a new shared context entry with the specified context ID, key and + * value. + * + * @param contextId + * SharedContext ID + * @param key + * Key for the key-value pair. + * @param value + * Value for the key-value pair. + */ + void addSharedContext(String contextId, String key, String value); + + /** + * Saves the specified shared context. + * + * @param context + * SharedContext object to save. + */ + void saveSharedContext(SharedContext context); + + /** + * Deletes the specified shared context. + * + * @param context + * SharedContext object to delete. + */ + void deleteSharedContext(SharedContext context); + + /** + * Deletes all shared contexts with the specified context ID. + * + * @param contextId + * Context ID; usually a session ID + * @return number of shared-context objects deleted + */ + int deleteSharedContexts(String contextId); + + /** + * Deletes all shared contexts with a creation time that is older than the + * specified value. + * + * @param ageInSeconds + * Expiration threshold in seconds + */ + void expireSharedContexts(int ageInSeconds); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java index 428f1354..1b1b6069 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java @@ -1,177 +1,177 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Restrictions;
-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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalapp.portal.domain.SharedContext;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-
-/**
- * Implementation of the shared-context service that talks to the database.
- */
-@Service("sharedContextService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class SharedContextServiceImpl implements SharedContextService {
-
- @Autowired
- private DataAccessService dataAccessService;
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextServiceImpl.class);
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalsdk.core.service.SharedContextService#
- * getSharedContexts()
- */
- @Override
- @SuppressWarnings("unchecked")
- public List<SharedContext> getSharedContexts(String contextId) {
- List<Criterion> restrictionsList = new ArrayList<Criterion>();
- Criterion contextIdCrit = Restrictions.eq("context_id", contextId);
- restrictionsList.add(contextIdCrit);
- List<SharedContext> contexts = (List<SharedContext>) getDataAccessService().getList(SharedContext.class, null,
- restrictionsList, null);
-
- return contexts;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalsdk.core.service.SharedContextService#
- * getSharedContext(java. lang.String, java.lang.String)
- */
- @Override
- public SharedContext getSharedContext(String contextId, String key) {
- SharedContext context = null;
- List<Criterion> restrictionsList = new ArrayList<Criterion>();
- Criterion contextIdCrit = Restrictions.eq("context_id", contextId);
- Criterion keyCrit = Restrictions.eq("ckey", key);
- restrictionsList.add(contextIdCrit);
- restrictionsList.add(keyCrit);
- @SuppressWarnings("unchecked")
- List<SharedContext> contexts = (List<SharedContext>) getDataAccessService().getList(SharedContext.class, null,
- restrictionsList, null);
- if (contexts != null && contexts.size() == 1)
- context = contexts.get(0);
-
- return context;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalapp.portal.service.SharedContextService#
- * addSharedContext(java.lang.String, java.lang.String, java.lang.String)
- */
- @Override
- public void addSharedContext(String contextId, String key, String value) {
- SharedContext context = new SharedContext(contextId, key, value);
- saveSharedContext(context);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalsdk.core.service.SharedContextService#
- * saveSharedContext(com. att.fusion.core.domain.SharedContext)
- */
- @Override
- public void saveSharedContext(SharedContext context) {
- getDataAccessService().saveDomainObject(context, null);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalsdk.core.service.SharedContextService#
- * deleteSharedContext(com. att.fusion.core.domain.SharedContext)
- */
- @Override
- public void deleteSharedContext(SharedContext context) {
- getDataAccessService().deleteDomainObject(context, null);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalapp.portal.service.SharedContextService#
- * deleteSharedContexts(java.lang.String)
- */
- @Override
- 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<SharedContext> contexts = getSharedContexts(contextId);
- if (contexts == null)
- return 0;
-
- logger.debug(EELFLoggerDelegate.debugLogger, "deleteSharedContexts: count is " + contexts.size());
- for (SharedContext sc : contexts)
- deleteSharedContext(sc);
-
- return contexts.size();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalapp.portal.service.SharedContextService#
- * expireSharedContexts(int)
- */
- @Override
- public void expireSharedContexts(int ageInSeconds) {
- // Specific to the MySQL database.
- // final String whereClause = " where create_time < ADDDATE(NOW(),
- // INTERVAL - " + ageInSeconds + " SECOND)";
- final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date expiredDateTime = new Date(System.currentTimeMillis() - ageInSeconds * 1000);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "expireSharedContexts: expire time is " + expiredDateTime.toString());
- final String whereClause = " create_time < '" + dateFormat.format(expiredDateTime) + "'";
- getDataAccessService().deleteDomainObjects(SharedContext.class, whereClause, null);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalapp.portal.domain.SharedContext; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; + +/** + * Implementation of the shared-context service that talks to the database. + */ +@Service("sharedContextService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class SharedContextServiceImpl implements SharedContextService { + + @Autowired + private DataAccessService dataAccessService; + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextServiceImpl.class); + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalsdk.core.service.SharedContextService# + * getSharedContexts() + */ + @Override + @SuppressWarnings("unchecked") + public List<SharedContext> getSharedContexts(String contextId) { + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion contextIdCrit = Restrictions.eq("context_id", contextId); + restrictionsList.add(contextIdCrit); + List<SharedContext> contexts = (List<SharedContext>) getDataAccessService().getList(SharedContext.class, null, + restrictionsList, null); + + return contexts; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalsdk.core.service.SharedContextService# + * getSharedContext(java. lang.String, java.lang.String) + */ + @Override + public SharedContext getSharedContext(String contextId, String key) { + SharedContext context = null; + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion contextIdCrit = Restrictions.eq("context_id", contextId); + Criterion keyCrit = Restrictions.eq("ckey", key); + restrictionsList.add(contextIdCrit); + restrictionsList.add(keyCrit); + @SuppressWarnings("unchecked") + List<SharedContext> contexts = (List<SharedContext>) getDataAccessService().getList(SharedContext.class, null, + restrictionsList, null); + if (contexts != null && contexts.size() == 1) + context = contexts.get(0); + + return context; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.SharedContextService# + * addSharedContext(java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public void addSharedContext(String contextId, String key, String value) { + SharedContext context = new SharedContext(contextId, key, value); + saveSharedContext(context); + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalsdk.core.service.SharedContextService# + * saveSharedContext(com. att.fusion.core.domain.SharedContext) + */ + @Override + public void saveSharedContext(SharedContext context) { + getDataAccessService().saveDomainObject(context, null); + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalsdk.core.service.SharedContextService# + * deleteSharedContext(com. att.fusion.core.domain.SharedContext) + */ + @Override + public void deleteSharedContext(SharedContext context) { + getDataAccessService().deleteDomainObject(context, null); + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.SharedContextService# + * deleteSharedContexts(java.lang.String) + */ + @Override + 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<SharedContext> contexts = getSharedContexts(contextId); + if (contexts == null) + return 0; + + logger.debug(EELFLoggerDelegate.debugLogger, "deleteSharedContexts: count is " + contexts.size()); + for (SharedContext sc : contexts) + deleteSharedContext(sc); + + return contexts.size(); + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.SharedContextService# + * expireSharedContexts(int) + */ + @Override + public void expireSharedContexts(int ageInSeconds) { + // Specific to the MySQL database. + // final String whereClause = " where create_time < ADDDATE(NOW(), + // INTERVAL - " + ageInSeconds + " SECOND)"; + final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date expiredDateTime = new Date(System.currentTimeMillis() - ageInSeconds * 1000); + logger.debug(EELFLoggerDelegate.debugLogger, + "expireSharedContexts: expire time is " + expiredDateTime.toString()); + final String whereClause = " create_time < '" + dateFormat.format(expiredDateTime) + "'"; + getDataAccessService().deleteDomainObjects(SharedContext.class, whereClause, null); + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserNotificationService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserNotificationService.java index 063fdf07..447cacf4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserNotificationService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserNotificationService.java @@ -1,55 +1,140 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EcompAppRole;
-import org.openecomp.portalapp.portal.transport.EpNotificationItem;
-import org.openecomp.portalapp.portal.transport.EpNotificationItemVO;
-import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem;
-
-public interface UserNotificationService {
-
- List<EpNotificationItem> getNotifications(Long userId);
-
- List<EpRoleNotificationItem> getNotificationRoles(Long notificationId);
-
- List<EcompAppRole> getAppRoleList();
- /**
- * Marks the notification as viewed by the specified user.
- *
- * @param notificationId
- * @param userId
- */
- void setNotificationRead(Long notificationId, int userId);
-
- String saveNotification(EpNotificationItem notificationItem) throws Exception;
-
- List<EpNotificationItemVO> getNotificationHistoryVO(Long userId);
-
- List<EpNotificationItemVO> getAdminNotificationVOS();
-
- List<EPUser> getUsersByOrgIds(List<String> OrgIds);
-
- List<String> getMessageRecipients(Long notificationId);
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EcompAppRole; +import org.openecomp.portalapp.portal.transport.EpNotificationItem; +import org.openecomp.portalapp.portal.transport.EpNotificationItemVO; +import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem; + +public interface UserNotificationService { + + /** + * Gets the specified notifications with userId from ep_notification + * + * @param userId + * + * @return the notifications with the specified userId + */ + + List<EpNotificationItem> getNotifications(Long userId); + + /** + * Gets the specified roles from ep_role_notification + * + * @param notificationId + * + * @return the roles for a specified notification + */ + + List<EpRoleNotificationItem> getNotificationRoles(Long notificationId); + + /** + * Get all app role list from the fn_app and fn_role table + * + * @return list of all roles associated with the applications + */ + List<EcompAppRole> getAppRoleList(); + + /** + * Marks the notification as viewed by the specified user. + * + * @param notificationId + * @param userId + */ + void setNotificationRead(Long notificationId, int userId); + + /** + * Saves the specified notification to the table ep_notification + * + * @param notificationItem + * @throws Exception + */ + + String saveNotification(EpNotificationItem notificationItem) throws Exception; + + /** + * Gets the specified notification with the userId for view all recent + * notifications + * + * @param userId + * + * @return the notification list + */ + + List<EpNotificationItemVO> getNotificationHistoryVO(Long userId); + + /** + * Gets the notifications with the userId for user notifications + * + * @param userId + * + * @return the notification list + */ + + List<EpNotificationItemVO> getAdminNotificationVOS(Long userId); + + /** + * Gets the user list from fn_user + * + * @param OrgIds + * + * @return the users list + */ + + List<EPUser> getUsersByOrgIds(List<String> OrgIds); + + /** + * Gets the received recipient to whom the notification is delivered from + * external system + * + * @param notificationId + * + * @return the active users + */ + + List<String> getMessageRecipients(Long notificationId); + + /** + * delete the records from ep_notification table when the endtime is more + * than 3 months + * + */ + + void deleteNotificationsFromEpNotificationTable(); + + /** + * delete the records from ep_user_notification table when the endtime is + * more than 3 months + * + */ + void deleteNotificationsFromEpUserNotificationTable(); + + /** + * delete the records from ep_role_notification table when the endtime is + * more than 3 months + * + */ + void deleteNotificationsFromEpRoleNotificationTable(); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserNotificationServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserNotificationServiceImpl.java index 4017b2fc..52bc4922 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserNotificationServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserNotificationServiceImpl.java @@ -1,211 +1,244 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.hibernate.SessionFactory;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EPUserNotification;
-import org.openecomp.portalapp.portal.domain.EcompAppRole;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalapp.portal.transport.EpNotificationItem;
-import org.openecomp.portalapp.portal.transport.EpNotificationItemVO;
-import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.stereotype.Service;
-
-@Service("userNotificationService")
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class UserNotificationServiceImpl implements UserNotificationService {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuServiceImpl.class);
-
- @Autowired
- private DataAccessService dataAccessService;
- @Autowired
- private SessionFactory sessionFactory;
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.UserNotificationService#getNotifications(java.lang.Long)
- */
- @Override
- public List<EpNotificationItem> getNotifications(Long userId) {
- Map<String, String> params = new HashMap<String, String>();
- params.put("user_id", userId.toString());
- @SuppressWarnings("unchecked")
- List<EpNotificationItem> notificationList = dataAccessService.executeNamedQuery("getNotifications", params,
- null);
- // set the roles to null for pure retrieval of all notifications
- for (EpNotificationItem item : notificationList) {
- item.setRoles(null);
- }
- return notificationList;
- }
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.UserNotificationService#getNotificationHistoryVO(java.lang.Long)
- */
- @Override
- public List<EpNotificationItemVO> getNotificationHistoryVO(Long userId) {
- Map<String, String> params = new HashMap<String, String>();
- params.put("user_id", userId.toString());
- @SuppressWarnings("unchecked")
- List<EpNotificationItemVO> notificationList = dataAccessService.executeNamedQuery("getNotificationHistoryVO",
- params, null);
- return notificationList;
- }
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.UserNotificationService#getAdminNotificationVOS()
- */
- @Override
- public List<EpNotificationItemVO> getAdminNotificationVOS() {
- Map<String, String> params = new HashMap<String, String>();
- @SuppressWarnings("unchecked")
- List<EpNotificationItemVO> notificationList = dataAccessService
- .executeNamedQuery("getAdminNotificationHistoryVO", params, null);
- return notificationList;
- }
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.UserNotificationService#getNotificationRoles(java.lang.Long)
- */
- @Override
- public List<EpRoleNotificationItem> getNotificationRoles(Long notificationId) {
- Map<String, String> params = new HashMap<String, String>();
- params.put("notificationId", Long.toString(notificationId));
- @SuppressWarnings("unchecked")
- List<EpRoleNotificationItem> roleNotifList = dataAccessService.executeNamedQuery("getNotificationRoles", params,
- null);
- return roleNotifList;
- }
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.UserNotificationService#getAppRoleList()
- */
- @SuppressWarnings("unchecked")
- @Override
- public List<EcompAppRole> getAppRoleList() {
- List<EcompAppRole> appRoleList = (List<EcompAppRole>) dataAccessService.executeNamedQuery("getEpNotificationAppRoles", null, null);
- return appRoleList;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.openecomp.portalapp.portal.service.UserNotificationService#
- * setNotificationsRead(java.lang.Long, int)
- */
- @Override
- public void setNotificationRead(Long notificationId, int userId) {
- EPUserNotification userNotification = new EPUserNotification();
- userNotification.setNotificationId(notificationId);
- userNotification.setUpdateTime(new Date());
- userNotification.setViewed("Y");
- userNotification.setUserId((long) userId);
- getDataAccessService().saveDomainObject(userNotification, null);
- }
-
- /*
- * (non-Javadoc)
- * @see org.openecomp.portalapp.portal.service.UserNotificationService#saveNotification(org.openecomp.portalapp.portal.transport.EpNotificationItem)
- */
- @Override
- public String saveNotification(EpNotificationItem notificationItem) throws Exception {
-
- // gather the roles
- if (notificationItem.getRoleIds() != null && !notificationItem.getIsForAllRoles().equals("Y")) {
- if (notificationItem.getRoles() == null) {
- Set<EpRoleNotificationItem> roleSet = new HashSet<EpRoleNotificationItem>();
- notificationItem.setRoles(roleSet);
- }
- for (Long roleId : notificationItem.getRoleIds()) {
- EpRoleNotificationItem roleItem = new EpRoleNotificationItem();
- roleItem.setNotificationId(notificationItem.getNotificationId());
- roleItem.setRoleId(roleId.intValue());
- notificationItem.getRoles().add(roleItem);
- }
- }
-
-
- // for updates fetch roles and then save
- if (notificationItem.getNotificationId() != null) {
- EpNotificationItem updateNotificationItem = (EpNotificationItem) getDataAccessService()
- .getDomainObject(EpNotificationItem.class, notificationItem.getNotificationId(), null);
- notificationItem.setRoles(updateNotificationItem.getRoles());
- }
- if(notificationItem.msgSource == null)
- {
- notificationItem.setMsgSource("EP");
- }
- getDataAccessService().saveDomainObject(notificationItem, null);
- return "" ;
-
- }
- @Override
- public List<EPUser> getUsersByOrgIds(List<String> OrgIds) {
- Map<String, Object> params = new HashMap<String, Object>();
- params.put("OrgIds", OrgIds);
- @SuppressWarnings("unchecked")
- List<EPUser> userList = dataAccessService.executeNamedQuery("getUsersByOrgIdsNotifications", params, null);
- return userList;
- }
-
- @Override
- public List<String> getMessageRecipients(Long notificationId) {
- Map<String, String> params = new HashMap<>();
- params.put("notificationId", Long.toString(notificationId));
- @SuppressWarnings("unchecked")
- List<String> activeUsers = dataAccessService.executeNamedQuery("messageRecipients", params, null);
- return activeUsers;
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-
- public SessionFactory getSessionFactory() {
- return sessionFactory;
- }
-
- public void setSessionFactory(SessionFactory sessionFactory) {
- this.sessionFactory = sessionFactory;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.hibernate.SessionFactory; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserNotification; +import org.openecomp.portalapp.portal.domain.EcompAppRole; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.transport.EpNotificationItem; +import org.openecomp.portalapp.portal.transport.EpNotificationItemVO; +import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +@Service("userNotificationService") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class UserNotificationServiceImpl implements UserNotificationService { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + @Autowired + private SessionFactory sessionFactory; + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * getNotifications(java.lang.Long) + */ + @Override + public List<EpNotificationItem> getNotifications(Long userId) { + Map<String, String> params = new HashMap<String, String>(); + params.put("user_id", userId.toString()); + @SuppressWarnings("unchecked") + List<EpNotificationItem> notificationList = dataAccessService.executeNamedQuery("getNotifications", params, + null); + // set the roles to null for pure retrieval of all notifications + for (EpNotificationItem item : notificationList) { + item.setRoles(null); + } + return notificationList; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * getNotificationHistoryVO(java.lang.Long) + */ + @Override + public List<EpNotificationItemVO> getNotificationHistoryVO(Long userId) { + Map<String, String> params = new HashMap<String, String>(); + params.put("user_id", userId.toString()); + @SuppressWarnings("unchecked") + List<EpNotificationItemVO> notificationList = dataAccessService.executeNamedQuery("getNotificationHistoryVO", + params, null); + return notificationList; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * getAdminNotificationVOS() + */ + @Override + public List<EpNotificationItemVO> getAdminNotificationVOS(Long userId) { + Map<String, String> params = new HashMap<String, String>(); + params.put("user_id", userId.toString()); + @SuppressWarnings("unchecked") + List<EpNotificationItemVO> notificationList = dataAccessService + .executeNamedQuery("getAdminNotificationHistoryVO", params, null); + return notificationList; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * getNotificationRoles(java.lang.Long) + */ + @Override + public List<EpRoleNotificationItem> getNotificationRoles(Long notificationId) { + Map<String, String> params = new HashMap<String, String>(); + params.put("notificationId", Long.toString(notificationId)); + @SuppressWarnings("unchecked") + List<EpRoleNotificationItem> roleNotifList = dataAccessService.executeNamedQuery("getNotificationRoles", params, + null); + return roleNotifList; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * getAppRoleList() + */ + @SuppressWarnings("unchecked") + @Override + public List<EcompAppRole> getAppRoleList() { + List<EcompAppRole> appRoleList = (List<EcompAppRole>) dataAccessService + .executeNamedQuery("getEpNotificationAppRoles", null, null); + return appRoleList; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * setNotificationsRead(java.lang.Long, int) + */ + @Override + public void setNotificationRead(Long notificationId, int userId) { + EPUserNotification userNotification = new EPUserNotification(); + userNotification.setNotificationId(notificationId); + userNotification.setUpdateTime(new Date()); + userNotification.setViewed("Y"); + userNotification.setUserId((long) userId); + getDataAccessService().saveDomainObject(userNotification, null); + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * saveNotification(org.openecomp.portalapp.portal.transport. + * EpNotificationItem) + */ + @Override + public String saveNotification(EpNotificationItem notificationItem) throws Exception { + + // gather the roles + if (notificationItem.getRoleIds() != null && !notificationItem.getIsForAllRoles().equals("Y")) { + if (notificationItem.getRoles() == null) { + Set<EpRoleNotificationItem> roleSet = new HashSet<EpRoleNotificationItem>(); + notificationItem.setRoles(roleSet); + } + for (Long roleId : notificationItem.getRoleIds()) { + EpRoleNotificationItem roleItem = new EpRoleNotificationItem(); + roleItem.setNotificationId(notificationItem.getNotificationId()); + roleItem.setRoleId(roleId.intValue()); + notificationItem.getRoles().add(roleItem); + } + } + + // for updates fetch roles and then save + if (notificationItem.getNotificationId() != null) { + EpNotificationItem updateNotificationItem = (EpNotificationItem) getDataAccessService() + .getDomainObject(EpNotificationItem.class, notificationItem.getNotificationId(), null); + notificationItem.setRoles(updateNotificationItem.getRoles()); + } + if (notificationItem.msgSource == null) { + notificationItem.setMsgSource("EP"); + } + getDataAccessService().saveDomainObject(notificationItem, null); + return ""; + + } + + @Override + public List<EPUser> getUsersByOrgIds(List<String> OrgIds) { + Map<String, Object> params = new HashMap<String, Object>(); + params.put("OrgIds", OrgIds); + @SuppressWarnings("unchecked") + List<EPUser> userList = dataAccessService.executeNamedQuery("getUsersByOrgIdsNotifications", params, null); + return userList; + } + + @Override + public List<String> getMessageRecipients(Long notificationId) { + Map<String, String> params = new HashMap<>(); + params.put("notificationId", Long.toString(notificationId)); + @SuppressWarnings("unchecked") + List<String> activeUsers = dataAccessService.executeNamedQuery("messageRecipients", params, null); + return activeUsers; + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + public SessionFactory getSessionFactory() { + return sessionFactory; + } + + public void setSessionFactory(SessionFactory sessionFactory) { + this.sessionFactory = sessionFactory; + } + + @Override + public void deleteNotificationsFromEpNotificationTable() { + Map<String, String> params = new HashMap<String, String>(); + dataAccessService.executeNamedUpdateQuery("deleteNotificationsFromEpNotificationTable", params, null); + } + + @Override + public void deleteNotificationsFromEpUserNotificationTable() { + Map<String, String> params = new HashMap<String, String>(); + dataAccessService.executeNamedUpdateQuery("deleteNotificationsFromEpUserNotificationTable", params, null); + + } + + @Override + public void deleteNotificationsFromEpRoleNotificationTable() { + Map<String, String> params = new HashMap<String, String>(); + dataAccessService.executeNamedUpdateQuery("deleteNotificationsFromEpRoleNotificationTable", params, null); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java new file mode 100644 index 00000000..727f83dd --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java @@ -0,0 +1,1479 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ + +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.apache.cxf.transport.http.HTTPException; +import org.hibernate.Query; +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval; +import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.domain.EPUserAppCatalogRoles; +import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest; +import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail; +import org.openecomp.portalapp.portal.domain.EpUserAppRoles; +import org.openecomp.portalapp.portal.domain.ExternalSystemAccess; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; +import org.openecomp.portalapp.portal.transport.ExternalRequestFieldsValidator; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; +import org.openecomp.portalapp.portal.transport.RemoteUserWithRoles; +import org.openecomp.portalapp.portal.transport.RoleInAppForUser; +import org.openecomp.portalapp.portal.transport.RolesInAppForUser; +import org.openecomp.portalapp.portal.transport.UserApplicationRoles; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.RoleService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +@EPMetricsLog +public class UserRolesCommonServiceImpl { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesCommonServiceImpl.class); + + private static final Object syncRests = new Object(); + + @Autowired + private DataAccessService dataAccessService; + @Autowired + private SessionFactory sessionFactory; + @Autowired + private SearchService searchService; + @Autowired + private EPAppService appsService; + @Autowired + private ApplicationsRestClientService applicationsRestClientService; + @Autowired + private EPRoleService epRoleService; + @Autowired + private RoleService roleService; + + /** + * + * @param ecompRoles + * @return HashMap<Long, EcompRole> + */ + private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) { + HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>(); + if (ecompRoles != null) { + for (int i = 0; i < ecompRoles.length; i++) { + if (ecompRoles[i].getId() != null) { + result.put(ecompRoles[i].getId(), ecompRoles[i]); + } + } + } + return result; + } + + /** + * + * @param userId + */ + protected void createLocalUserIfNecessary(String userId) { + if (StringUtils.isEmpty(userId)) { + logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!"); + return; + } + Session localSession = null; + Transaction transaction = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + @SuppressWarnings("unchecked") + List<EPUser> userList = localSession + .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list(); + if (userList.size() == 0) { + EPUser client = searchService.searchUserByUserId(userId); + if (client == null) { + String msg = "createLocalUserIfNecessary: cannot create user " + userId + + ", because not found in phonebook"; + logger.error(EELFLoggerDelegate.errorLogger, msg); + } else { + client.setLoginId(userId); + client.setActive(true); + localSession.save(client); + } + } + transaction.commit(); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser"); + } + } + + /** + * This method return nothing and remove roles before adding any roles for an app + * @param userRole + * @param appId + * @param localSession + * @param userAppRoles + * @param newUserAppRolesMap + */ + private static void syncUserRolesExtension(EPUserApp userRole, Long appId, Session localSession, EcompRole[] userAppRoles, HashMap<Long, EcompRole> newUserAppRolesMap) { + + Long userAppRoleId = 0L; + if (appId == PortalConstants.PORTAL_APP_ID) { // local app + userAppRoleId = userRole.getRoleId(); + } else { // remote app + userAppRoleId = userRole.getAppRoleId(); + } + + if (!newUserAppRolesMap.containsKey(userAppRoleId)) { + localSession.delete(userRole); + } else { + newUserAppRolesMap.remove(userAppRoleId); + } + } + + /** + * Checks whether the role is inactive + * + * @param epRole + * @throws Exception + * if role is inactive, throws exception + */ + private void checkIfRoleInactive(EPRole epRole) throws Exception{ + if(!epRole.getActive()){ + throw new Exception(epRole.getName()+ " role is unavailable"); + } + } + + /** + * + * @param sessionFactory + * @param userId + * @param appId + * @param userAppRoles + * @param extRequestValue + * set to false if request is from users page otherwise true + * @throws Exception + */ + protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId, + EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception { + boolean result = false; + Session localSession = null; + Transaction transaction = null; + String roleActive = null; + final Map<String, String> userAppParams = new HashMap<>(); + final Map<String, String> appParams = new HashMap<>(); + HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles); + + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + @SuppressWarnings("unchecked") + List<EPUser> userList = localSession + .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + userId + "'").list(); + if (userList.size() > 0) { + EPUser client = userList.get(0); + roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'"; + @SuppressWarnings("unchecked") + List<EPUserApp> userRoles = localSession.createQuery("from " + EPUserApp.class.getName() + + " where app.id=" + appId + roleActive + " and userId=" + client.getId()).list(); + + if ("DELETE".equals(reqType)) { + for (EPUserApp userAppRoleList : userRoles) { + userAppParams.put("roleName", String.valueOf(userAppRoleList.getRole().getName())); + userAppParams.put("appId", String.valueOf(appId)); + appParams.put("appRoleName", userAppRoleList.getRole().getName()); + @SuppressWarnings("unchecked") + List<EPRole> rolesList = (!userAppRoleList.getRole().getName().equals(PortalConstants.ADMIN_ROLE)) ? (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", userAppParams, null) : (List<EPRole>) dataAccessService.executeNamedQuery("getPortalAppRoles", appParams, null); + if(rolesList.size() > 0 || !rolesList.isEmpty()){ + checkIfRoleInactive(rolesList.get(0)); + } + } + } + + for (EPUserApp userRole : userRoles) { + if (!userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && userRole.getRoleId() != PortalConstants.SYS_ADMIN_ROLE_ID && !extRequestValue){ + syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap); + } + else if (extRequestValue){ + syncUserRolesExtension(userRole, appId, localSession, userAppRoles, newUserAppRolesMap); + } + } + Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values(); + if (newRolesToAdd.size() > 0) { + EPApp app = (EPApp) localSession.get(EPApp.class, appId); + + HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>(); + if (appId == PortalConstants.PORTAL_APP_ID) { // local app + String appIdValue = null; + if(!extRequestValue){ + appIdValue = "and id != " + PortalConstants.PORTAL_APP_ID; + }else{ + appIdValue = ""; + } + @SuppressWarnings("unchecked") + List<EPRole> roles = localSession + .createQuery("from " + EPRole.class.getName() + " where appId is null " + appIdValue).list(); + for (EPRole role : roles) { + role.setAppId(1L); + rolesMap.put(role.getId(), role); + } + } else { // remote app + @SuppressWarnings("unchecked") + List<EPRole> roles = localSession + .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); + for (EPRole role : roles) { + rolesMap.put(role.getAppRoleId(), role); + } + } + EPRole role = null; + for (EcompRole userRole : newRolesToAdd) { + if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) { + role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)); + } else if (userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue){ + continue; + } + EPUserApp userApp = new EPUserApp(); + userApp.setUserId(client.getId()); + userApp.setApp(app); + userApp.setRole(("PUT".equals(reqType) || "POST".equals(reqType) && userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) ? role : rolesMap.get(userRole.getId())); + localSession.save(userApp); + localSession.flush(); + } + + if (appId == PortalConstants.PORTAL_APP_ID) { + /* + * for local app -- hack - always make sure fn_role + * table's app_id is null and not 1 for primary app in + * this case being ecomp portal app; reason: hibernate + * is rightly setting this to 1 while persisting to + * fn_role as per the mapping but SDK role management + * code expects the app_id to be null as there is no + * concept of App_id in SDK + */ + SQLQuery sqlQuery = localSession + .createSQLQuery("update fn_role set app_id = null where app_id = 1 "); + sqlQuery.executeUpdate(); + + + } + } + } + transaction.commit(); + result = true; + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + EcompPortalUtils.rollbackTransaction(transaction, + "Exception occurred in syncUserRoles, Details: " + EcompPortalUtils.getStackTrace(e)); + if("DELETE".equals(reqType)){ + throw new Exception(e.getMessage()); + } + } finally { + localSession.close(); + if (!result && !"DELETE".equals(reqType)) { + throw new Exception( + "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'."); + } + } + } + + /** + * Called when getting the list of roles for the user + * + * @param appRoles + * @param userAppRoles + * @return List<RoleInAppForUser> + */ + protected List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) { + List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>(); + + Set<Long> userAppRolesMap = new HashSet<Long>(); + if (userAppRoles != null) { + for (EcompRole ecompRole : userAppRoles) { + userAppRolesMap.add(ecompRole.getId()); + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "constructRolesInAppForUserGet has received userAppRoles list empty"); + } + + if (appRoles != null) { + for (EcompRole ecompRole : appRoles) { + RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName()); + roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId()); + rolesInAppForUser.add(roleForUser); + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, "constructRolesInAppForUser has received appRoles list empty"); + } + return rolesInAppForUser; + } + + /** + * Called when getting the list of roles for the user + * + * @param appRoles + * @param userAppRoles + * @param extRequestValue + * set to false if request is from users page otherwise true + * @return List<RoleInAppForUser> + */ + protected List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, EPRole[] userAppRoles, Boolean extRequestValue) { + List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>(); + + Set<Long> userAppRolesMap = new HashSet<Long>(); + if (userAppRoles != null) { + for (EPRole ecompRole : userAppRoles) { + userAppRolesMap.add(ecompRole.getId()); + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "constructRolesInAppForUserGet has received userAppRoles list empty."); + } + + if (appRoles != null) { + for (Role ecompRole : appRoles) { + if (ecompRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue) + continue; + RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName()); + roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId()); + rolesInAppForUser.add(roleForUser); + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "constructRolesInAppForUser has received appRoles list empty."); + } + return rolesInAppForUser; + } + + + /** + * copies of methods in GetAppsWithUserRoleState + * + * @param sessionFactory + * @param appId + * @param appRoles + * @throws Exception + */ + protected void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId); + HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles); + boolean result = false; + Session localSession = null; + Transaction transaction = null; + + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + // Attention! All roles from remote application supposed to be + // active! + @SuppressWarnings("unchecked") + List<EPRole> currentAppRoles = localSession + .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); + List<EPRole> obsoleteRoles = new ArrayList<EPRole>(); + for (int i = 0; i < currentAppRoles.size(); i++) { + EPRole oldAppRole = currentAppRoles.get(i); + if (oldAppRole.getAppRoleId() != null) { + EcompRole role = null; + role = newRolesMap.get(oldAppRole.getAppRoleId()); + if (role != null) { + if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) { + oldAppRole.setName(role.getName()); + localSession.update(oldAppRole); + } + newRolesMap.remove(oldAppRole.getAppRoleId()); + } else { + obsoleteRoles.add(oldAppRole); + } + } else { + obsoleteRoles.add(oldAppRole); + } + } + Collection<EcompRole> newRolesToAdd = newRolesMap.values(); + for (EcompRole role : newRolesToAdd) { + logger.debug(EELFLoggerDelegate.debugLogger, "about to add missing role: " + role.toString()); + EPRole newRole = new EPRole(); + // Attention! All roles from remote application supposed to be + // active! + newRole.setActive(true); + newRole.setName(role.getName()); + newRole.setAppId(appId); + newRole.setAppRoleId(role.getId()); + localSession.save(newRole); + } + if (obsoleteRoles.size() > 0) { + logger.debug(EELFLoggerDelegate.debugLogger, "we have obsolete roles to delete"); + for (EPRole role : obsoleteRoles) { + logger.debug(EELFLoggerDelegate.debugLogger, "obsolete role: " + role.toString()); + Long roleId = role.getId(); + // delete obsolete roles here + // Must delete all records with foreign key constraints on + // fn_role: + // fn_user_role, fn_role_composite, fn_role_function, + // fn_user_pseudo_role, fn_menu_functional_roles. + // And for fn_menu_functional, if no other roles for that + // menu item, remove the url. + + // Delete from fn_user_role + @SuppressWarnings("unchecked") + List<EPUserApp> userRoles = localSession.createQuery( + "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId) + .list(); + + logger.debug(EELFLoggerDelegate.debugLogger, "number of userRoles to delete: " + userRoles.size()); + for (EPUserApp userRole : userRoles) { + logger.debug(EELFLoggerDelegate.debugLogger, + "about to delete userRole: " + userRole.toString()); + localSession.delete(userRole); + logger.debug(EELFLoggerDelegate.debugLogger, + "finished deleting userRole: " + userRole.toString()); + } + + // Delete from fn_menu_functional_roles + @SuppressWarnings("unchecked") + List<FunctionalMenuRole> funcMenuRoles = localSession + .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId) + .list(); + int numMenuRoles = funcMenuRoles.size(); + logger.debug(EELFLoggerDelegate.debugLogger, + "number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles); + for (FunctionalMenuRole funcMenuRole : funcMenuRoles) { + Long menuId = funcMenuRole.menuId; + // If this is the only role for this menu item, then the + // app and roles will be gone, + // so must null out the url too, to be consistent + @SuppressWarnings("unchecked") + List<FunctionalMenuRole> funcMenuRoles2 = localSession + .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId) + .list(); + int numMenuRoles2 = funcMenuRoles2.size(); + logger.debug(EELFLoggerDelegate.debugLogger, + "number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2); + localSession.delete(funcMenuRole); + if (numMenuRoles2 == 1) { + // If this is the only role for this menu item, then + // the app and roles will be gone, + // so must null out the url too, to be consistent + logger.debug(EELFLoggerDelegate.debugLogger, + "There is exactly 1 menu item for this role, so emptying the url"); + @SuppressWarnings("unchecked") + List<FunctionalMenuItem> funcMenuItems = localSession + .createQuery( + "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId) + .list(); + if (funcMenuItems.size() > 0) { + logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item"); + FunctionalMenuItem funcMenuItem = funcMenuItems.get(0); + funcMenuItem.url = ""; + localSession.update(funcMenuItem); + } + } + } + + // Delete from fn_role_function + String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + Query query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from ep_role_notification + sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from fn_role_composite + sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from fn_user_pseudo_role + sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString()); + localSession.delete(role); + logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role"); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction"); + transaction.commit(); + logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction"); + result = true; + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + EcompPortalUtils.rollbackTransaction(transaction, + "Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e)); + } finally { + localSession.close(); + if (!result) { + throw new Exception( + "Exception occurred in syncAppRoles while closing database session for app: '" + appId + "'."); + } + } + } + + /** + * Called when updating the list of roles for the user + * + * @param userId + * @param appId + * @param userRolesInRemoteApp + * @return RolesInAppForUser + */ + protected RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId, + Set<EcompRole> userRolesInRemoteApp) { + RolesInAppForUser result; + result = new RolesInAppForUser(); + result.appId = appId; + result.orgUserId = userId; + for (EcompRole role : userRolesInRemoteApp) { + RoleInAppForUser roleInAppForUser = new RoleInAppForUser(); + roleInAppForUser.roleId = role.getId(); + roleInAppForUser.roleName = role.getName(); + roleInAppForUser.isApplied = new Boolean(true); + result.roles.add(roleInAppForUser); + } + return result; + } + + /** + * + * @param roleInAppForUserList + * @return boolean + */ + protected boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) { + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.isApplied.booleanValue()) { + return true; + } + } + return false; + } + + /** + * Builds JSON and posts it to a remote application to update user roles. + * + * @param roleInAppForUserList + * @param mapper + * @param applicationsRestClientService + * @param appId + * @param userId + * @return Set of roles as sent; NOT the response from the app. + * @throws JsonProcessingException + * @throws HTTPException + */ + protected Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper, + ApplicationsRestClientService applicationsRestClientService, Long appId, String userId) + throws JsonProcessingException, HTTPException { + Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList); + Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList); + String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote); + applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString, + String.format("/user/%s/roles", userId)); + // TODO: We should add code that verifies that the post operation did + // succeed. Because the SDK may still return 200 OK with an html page + // even when it fails! + return updateUserRolesInEcomp; + } + + /** + * + * @param roleInAppForUserList + * @return Set<EcompRole> + */ + protected Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) { + Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>(); + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.isApplied) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(roleInAppForUser.roleId); + ecompRole.setName(roleInAppForUser.roleName); + existingUserRoles.add(ecompRole); + } + } + return existingUserRoles; + } + + /** + * Constructs user app roles excluding Account Administrator role + * + * @param roleInAppForUserList + * @return + * List of roles with Role name, Role Id + */ + protected Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) { + Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>(); + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.isApplied && !roleInAppForUser.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(roleInAppForUser.roleId); + ecompRole.setName(roleInAppForUser.roleName); + existingUserRoles.add(ecompRole); + } + } + return existingUserRoles; + } + + /** + * This is for a single app + * + * @param rolesInAppForUser + * @param externalSystemRequest + * set to false if requests from Users page otherwise true + * @return true on success, false otherwise + */ + protected boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser, boolean externalSystemRequest, String reqType) throws Exception { + boolean result = false; + String userId = rolesInAppForUser.orgUserId; + Long appId = rolesInAppForUser.appId; + synchronized (syncRests) { + if (rolesInAppForUser != null) { + createLocalUserIfNecessary(userId); + } + + if (rolesInAppForUser != null) { + EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.size()]; + for (int i = 0; i < rolesInAppForUser.roles.size(); i++) { + RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i); + EcompRole role = new EcompRole(); + role.setId(roleInAppForUser.roleId); + role.setName(roleInAppForUser.roleName); + userAppRoles[i] = role; + } + try { + syncUserRoles(sessionFactory, userId, appId, userAppRoles, externalSystemRequest, reqType); + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for attuid " + userId, e); + if("DELETE".equals(reqType)){ + throw new Exception(e.getMessage()); + } + } + } + } + return result; + } + + /** + * + * @param appId + * @param remoteUser + * @return UserApplicationRoles + */ + protected UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) { + UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles(); + userWithRemoteAppRoles.setAppId(appId); + userWithRemoteAppRoles.setOrgUserId(remoteUser.getOrgUserId()); + userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName()); + userWithRemoteAppRoles.setLastName(remoteUser.getLastName()); + userWithRemoteAppRoles.setRoles(remoteUser.getRoles()); + return userWithRemoteAppRoles; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.UserRolesService# + * importRolesFromRemoteApplication(java.lang.Long) + */ + public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException { + EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull"); + List<EPRole> rolesList = Arrays.asList(appRolesFull); + for (EPRole externalAppRole : rolesList) { + + // Try to find an existing extern role for the app in the local + // ecomp DB. If so, then use its id to update the existing external + // application role record. + Long externAppId = externalAppRole.getId(); + EPRole existingAppRole = epRoleService.getRole(appId, externAppId); + if (existingAppRole != null) { + logger.debug(EELFLoggerDelegate.debugLogger, + String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.", + appId, externAppId)); + continue; + } + // persistExternalRoleInEcompDb(externalAppRole, appId, + // roleService); + } + + return rolesList; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.UserRolesService# + * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain. + * EPUser, org.openecomp.portalapp.portal.transport.AppWithRolesForUser) + */ + public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) { + boolean result = false; + boolean epRequestValue = false; + String userId = ""; + if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) { + userId = newAppRolesForUser.orgUserId.trim(); + } + Long appId = newAppRolesForUser.appId; + List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles; + if (userId.length() > 0) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + try { + EPApp app = appsService.getApp(appId); + applyChangesToUserAppRolesForMyLoginsRequest(user, appId); + + // if local app + if (appId == PortalConstants.PORTAL_APP_ID) { + // EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService); + Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, + applicationsRestClientService, appId, userId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, + userRolesInLocalApp); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null); + + } else {// remote app + EPUser remoteAppUser = null; + try { + remoteAppUser = getUserFromApp(userId, app, applicationsRestClientService); + } catch (HTTPException e) { + // Some apps are returning 400 if user is not found. + if (e.getResponseCode() == 400) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing", + e); + } else { + // Other response code, let it come thru. + throw e; + } + } + if (remoteAppUser == null) { + if (remoteUserShouldBeCreated(roleInAppForUserList)) { + + createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app)); + // If we succeed, we know that the new user was + // persisted on remote app. + remoteAppUser = getUserFromApp(userId, app, applicationsRestClientService); + if (remoteAppUser == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Failed to persist new user: " + userId + " in remote app. appId = " + appId); + // return null; + } + } + } + if (remoteAppUser != null) { + Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, + applicationsRestClientService, appId, userId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, + userRolesInRemoteApp); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null); + + // If no roles remain, request app to set user inactive. + if (userRolesInRemoteApp.size() == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app, + userId); + remoteAppUser.setActive(false); + postUserToRemoteApp(userId, user, app, applicationsRestClientService); + } + } + } + } catch (Exception e) { + String message = String.format( + "Failed to create user or update user roles for User %s, AppId %s", + userId, Long.toString(appId)); + logger.error(EELFLoggerDelegate.errorLogger, message, e); + result = false; + } + + } + return result; + } + + /** + * + * @param userId + * @param app + * @param applicationsRestClientService + * @param searchService + * @param mapper + * @throws Exception + */ + protected void createNewUserOnRemoteApp(String userId, EPApp app, + ApplicationsRestClientService applicationsRestClientService, SearchService searchService, + ObjectMapper mapper, boolean postOpenSource) throws Exception { + + + EPUser client = searchService.searchUserByUserId(userId); + + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + if (client == null) { + String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook."; + logger.error(EELFLoggerDelegate.errorLogger, msg); + throw new Exception(msg); + } + + client.setLoginId(userId); + client.setActive(true); + + String userInString = null; + userInString = mapper.writerFor(EPUser.class).writeValueAsString(client); + logger.debug(EELFLoggerDelegate.debugLogger, + "about to post new client to remote application, users json = " + userInString); + applicationsRestClientService.post(EPUser.class, app.getId(), userInString, String.format("/user", userId)); + + } + + @SuppressWarnings("unchecked") + protected void applyChangesToAppRolesRequest(Long appId, Long userId, String updateStatus, EPUserAppRolesRequest epUserAppRolesRequest) { + final Map<String, Long> epRequestParams = new HashMap<>(); + try { + EPUserAppRolesRequest epAppRolesRequestData = epUserAppRolesRequest; + epAppRolesRequestData.setUpdatedDate(new Date()); + epAppRolesRequestData.setRequestStatus(updateStatus); + HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>(); + addiotonalUpdateParam.put("userId", userId); + dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam); + epRequestParams.put("reqId", epUserAppRolesRequest.getId()); + List<EPUserAppRolesRequestDetail> epUserAppRolessDetailList = new ArrayList<EPUserAppRolesRequestDetail>(); + epUserAppRolessDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList", + epRequestParams, null); + if (epUserAppRolessDetailList.size() > 0) { + for (EPUserAppRolesRequestDetail epRequestUpdateData : epUserAppRolessDetailList) { + EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateData; + epAppRoleDetailData.setReqType(updateStatus); + epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData); + HashMap<String, Long> updateDetailsParam = new HashMap<String, Long>(); + addiotonalUpdateParam.put("reqId", epUserAppRolesRequest.getId()); + dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParam); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete"); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e); + } + } + + @SuppressWarnings("unchecked") + public void applyChangesToUserAppRolesForMyLoginsRequest(EPUser user, Long appId) { + final Map<String, Long> params = new HashMap<>(); + final Map<String, Long> epDetailParams = new HashMap<>(); + List<EPUserAppRolesRequest> epRequestIdVal = new ArrayList<EPUserAppRolesRequest>(); + params.put("appId", appId); + params.put("userId", user.getId()); + try { + epRequestIdVal = (List<EPUserAppRolesRequest>) dataAccessService + .executeNamedQuery("userAppRolesRequestList", params, null); + if (epRequestIdVal.size() > 0) { + EPUserAppRolesRequest epAppRolesRequestData = epRequestIdVal.get(0); + epAppRolesRequestData.setUpdatedDate(new Date()); + epAppRolesRequestData.setRequestStatus("O"); + HashMap<String, Long> addiotonalUpdateParam = new HashMap<String, Long>(); + addiotonalUpdateParam.put("userId", user.getId()); + dataAccessService.saveDomainObject(epAppRolesRequestData, addiotonalUpdateParam); + epDetailParams.put("reqId", epAppRolesRequestData.getId()); + List<EPUserAppRolesRequestDetail> epUserAppRolesDetailList = new ArrayList<EPUserAppRolesRequestDetail>(); + epUserAppRolesDetailList = dataAccessService.executeNamedQuery("userAppRolesRequestDetailList", + epDetailParams, null); + if (epUserAppRolesDetailList.size() > 0) { + for (EPUserAppRolesRequestDetail epRequestUpdateList : epUserAppRolesDetailList) { + EPUserAppRolesRequestDetail epAppRoleDetailData = epRequestUpdateList; + epAppRoleDetailData.setReqType("O"); + epAppRoleDetailData.setEpRequestIdData(epAppRolesRequestData); + HashMap<String, Long> updateDetailsParams = new HashMap<String, Long>(); + addiotonalUpdateParam.put("reqId", epAppRolesRequestData.getId()); + dataAccessService.saveDomainObject(epAppRoleDetailData, updateDetailsParams); + } + logger.debug(EELFLoggerDelegate.debugLogger, "User App roles request from User Page is overridden"); + } + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e); + } + } + + /** + * Pushes specified user details to the specified remote app. + * + * @param userId + * ATT UID identifying user at remote app in REST endpoint path + * @param user + * User details to be pushed + * @param app + * Remote app + * @param applicationsRestClientService + * @throws HTTPException + */ + protected void postUserToRemoteApp(String userId, EPUser user, EPApp app, + ApplicationsRestClientService applicationsRestClientService) throws HTTPException { + + getUser(userId, app, applicationsRestClientService); + + } + + /** + * It returns user details for single org user id + * + * @param userParams + * @return + * if user exists it returns list of user details otherwise empty value + */ + @SuppressWarnings("unchecked") + private List<EPUser> checkIfUserExists(Map<String, String> userParams){ + return (List<EPUser>)dataAccessService.executeNamedQuery("epUserAppId", userParams, null); + } + + /** + * It checks whether the new user is valid or not otherwise throws exception + * + * @param orgUserId + * @param app + * @return + * Checks if user is valid and returns message otherwise throws exception + * @throws Exception + */ + private String validateNewUser(String orgUserId, EPApp app) throws Exception { + EPUser epUser = searchService.searchUserByUserId(orgUserId); + if (epUser == null) { + throw new Exception("User does not exist"); + } else if (!epUser.getOrgUserId().equals(orgUserId)) { + throw new Exception("User does not exist"); + } else if (app == null) { + throw new Exception("Application does not exist"); + } + return "Saved Successfully"; + } + + /** + * Checks if the fields exists or not + * + * @param userList + * contains user information + * @param app + * contains app name + * @throws Exception + * throws exception if the field is not valid + */ + private void validateExternalRequestFields(List<EPUser> userList, EPApp app) throws Exception{ + if (userList.size() == 0 || userList.isEmpty() ) { + throw new Exception("User does not exist"); + } else if(app == null) { + throw new Exception("Application does not exist"); + } else if(!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + throw new Exception(app.getMlAppName()+" application is unavailable"); + } + } + + @SuppressWarnings("unchecked") + public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType) { + boolean result = false; + boolean externalSystemRequest = true; + final Map<String, Long> params = new HashMap<>(); + final Map<String, String> userParams = new HashMap<>(); + List<EPUser> userInfo = null; + EPUser userId = null; + List<EPUserAppRolesRequest> epRequestId = null; + String orgUserId = ""; + String updateStatus = ""; + String reqMessage = ""; + EPApp app = null; + if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) { + orgUserId = newAppRolesForUser.getLoginId().trim(); + } + String appName = newAppRolesForUser.getApplicationName(); + String logMessage = ("DELETE").equals(reqType) ? "Deleting": "Assigning/Updating" ; + if (orgUserId.length() > 0) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + int epRequestIdSize = 0; + try { + app = appsService.getAppDetail(appName); + userParams.put("orgUserIdValue", orgUserId); + userInfo = checkIfUserExists(userParams); + reqMessage = "Updated Successfully"; + if (!reqType.equals("DELETE") && (userInfo.size() == 0 || userInfo.isEmpty())) { + reqMessage = validateNewUser(orgUserId, app); + } + if (userInfo.size() != 0 || !userInfo.isEmpty()) { + validateExternalRequestFields(userInfo, app); + userId = userInfo.get(0); + params.put("appId", app.getId()); + params.put("userId", userId.getId()); + epRequestId = (List<EPUserAppRolesRequest>) dataAccessService + .executeNamedQuery("userAppRolesRequestList", params, null); + epRequestIdSize = epRequestId.size(); + } + if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles"); + syncAppRoles(sessionFactory, app.getId(), appRoles); + } + + List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(), + app.getId(), app.getMlAppName()); + // if local app + if (app.getId() == PortalConstants.PORTAL_APP_ID) { + // EPUser localUser = getUserFromApp(orgUserId, app, applicationsRestClientService); + Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, + applicationsRestClientService, app.getId(), orgUserId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), + userRolesInLocalApp); + logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", + logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); + } else {// remote app + EPUser remoteAppUser = null; + try { + remoteAppUser = getUserFromApp(orgUserId, app, applicationsRestClientService); + } catch (HTTPException e) { + // Some apps are returning 400 if user is not found. + if (e.getResponseCode() == 400) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing", + e); + } else { + // Other response code, let it come thru. + throw e; + } + } + if (remoteAppUser == null) { + createNewUserOnRemoteApp(orgUserId, app, applicationsRestClientService, searchService, mapper, + isAppUpgradeVersion(app)); + // If we succeed, we know that the new user was + // persisted on remote app. + remoteAppUser = getUserFromApp(orgUserId, app, applicationsRestClientService); + if (remoteAppUser == null) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to persist new user: " + orgUserId + + " in remote app. appId = " + app.getId()); + // return null; + } + reqMessage = "Saved Successfully"; + } + if (remoteAppUser != null) { + Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, + mapper, applicationsRestClientService, app.getId(), orgUserId); + + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, + app.getId(), userRolesInRemoteApp); + logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", + logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); + // If no roles remain, request app to set user inactive. + /*if (userRolesInRemoteApp.size() == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app, + attuid); + //TODO Need to fix the logged in user is not set to inactive + remoteAppUser.setActive(false); + postUserToRemoteApp(attuid, user, app, applicationsRestClientService); + }*/ + + } + if(!result){ + reqMessage = "Failed to save the user app role(s)"; + } + if (epRequestIdSize > 0 && !userInfo.isEmpty()) { + updateStatus = "C"; + applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0)); + } + + } + } catch (Exception e) { + String message = String.format("Failed to create user or update user roles for User %s, AppId %s", + orgUserId, appName); + logger.error(EELFLoggerDelegate.errorLogger, message, e); + result = false; + reqMessage = e.getMessage(); + if(epRequestIdSize > 0 && !userInfo.isEmpty()){ + updateStatus = "F"; + applyChangesToAppRolesRequest(app.getId(), userId.getId(), + updateStatus, epRequestId.get(0)); + } + } + + } + return new ExternalRequestFieldsValidator(result, reqMessage); + } + + /** + * + * @param roleInAppForUserList + * @param mapper + * @param applicationsRestClientService + * @param appId + * @param userId + * @return Set<EcompRole> + * @throws JsonProcessingException + * @throws HTTPException + */ + private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper, + ApplicationsRestClientService applicationsRestClientService, Long appId, String userId) + throws JsonProcessingException, HTTPException { + Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList); + return updatedUserRoles; + } + + /** + * It constructs and returns list of user app roles when the external API role approval system calls + * this method + * + * @param roleInAppForUserList + * @param appId + * @return list of user app roles + * @throws Exception + * throws exceptions if role id does not exits + */ + private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList, + Long appId, String appName) throws Exception { + List<RoleInAppForUser> existingUserRoles = new ArrayList<RoleInAppForUser>(); + EPRole existingAppRole = null; + for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) { + RoleInAppForUser ecompRole = new RoleInAppForUser(); + existingAppRole = epRoleService.getAppRole(roleInAppForUser.getRoleName(), appId); + if (existingAppRole == null) { + logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}", + roleInAppForUserList); + throw new Exception("'" +roleInAppForUser.getRoleName() + "'" +" role does not exist for" + appName + " application"); + } + if (!existingAppRole.getActive()) { + logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}", + roleInAppForUserList); + throw new Exception(roleInAppForUser.getRoleName() + " role is unavailable for "+ appName + " application"); + } else { + ecompRole.roleId = (appId == 1 || roleInAppForUser.getRoleName().equals(PortalConstants.ADMIN_ROLE)) ? existingAppRole.getId() : existingAppRole.getAppRoleId(); + ecompRole.roleName = roleInAppForUser.getRoleName(); + ecompRole.isApplied = true; + existingUserRoles.add(ecompRole); + } + } + return existingUserRoles; + } + + + + /** + * + * @param userId + * @param app + * @param applicationsRestClientService + * @return EPUser + * @throws HTTPException + */ + protected EPUser getUserFromApp(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) + throws HTTPException { + // local app + if (app.getId() == PortalConstants.PORTAL_APP_ID) { + // Map<String,String> params = new HashMap<String,String>(); + // params.put("sbcid",userId); + @SuppressWarnings("unchecked") + List<EPUser> userList = (List<EPUser>) dataAccessService + .executeQuery("from EPUser where orgUserId='" + userId + "'", null); + if (userList != null && !userList.isEmpty()) + return userList.get(0); + else + return null; + } + // remote app + + return getUser(userId, app, applicationsRestClientService); + } + + protected EPUser getUser(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) + throws HTTPException { + return applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", userId), true); + + } + + protected boolean isAppUpgradeVersion(EPApp app){ + return true; + } + + + public ExternalSystemAccess getExternalRequestAccess(){ + ExternalSystemAccess res = null; + try { + res = new ExternalSystemAccess(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE, + Boolean.parseBoolean(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_ACCESS_ENABLE))); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getExternalRequestAccess failed" + e.getMessage()); + } + return res; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.UserRolesService# + * getAppRolesForUser(java.lang.Long, java.lang.String) + */ + public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) { + + List<RoleInAppForUser> rolesInAppForUser = null; + try { + + // for ecomp portal app, no need to make a remote call + if (appId == PortalConstants.PORTAL_APP_ID) { + + List<Role> roleList = roleService.getAvailableRoles(); + List<Role> activeRoleList = new ArrayList<Role>(); + for(Role role: roleList) { + if(role.getActive()) { + if(role.getId() != 1){ // prevent portal admin from being added + activeRoleList.add(role); + } else if(extRequestValue){ + activeRoleList.add(role); + } + } + + } + + EPApp app = appsService.getApp(appId); + EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService); + Set<EPRole> roleSet = localUser.getAppEPRoles(app); + rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSet.toArray(new EPRole[0]), extRequestValue); + return rolesInAppForUser; + } + + EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles"); + + // Test this error case, for generating an internal Ecomp Portal + // error + // EcompRole[] appRoles = null; + // If there is an exception in the rest client api, then null will + // be returned. + if (appRoles != null) { + syncAppRoles(sessionFactory, appId, appRoles); + EcompRole[] userAppRoles = null; + try { + try { + userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId, + String.format("/user/%s/roles", userId)); + } catch (HTTPException e) { + // Some apps are returning 400 if user is not found. + if (e.getResponseCode() == 400) { + logger.debug(EELFLoggerDelegate.debugLogger, + "getAppRolesForUser caught exception with response code 400; continuing", e); + } else { + // Other response code, let it come thru. + throw e; + } + } + if (userAppRoles == null) { + if (EcompPortalUtils.getExternalAppResponseCode() == 400) { + EcompPortalUtils.setExternalAppResponseCode(200); + String message = String.format( + "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, " + + "assuming user doesn't exist, app is framework SDK based, and things are ok. " + + "Overriding to 200 until framework SDK returns a useful response.", + Long.toString(appId), userId); + logger.warn(EELFLoggerDelegate.applicationLogger, message); + } + } + + HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles); + ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>(); + for (int i = 0; i < userAppRoles.length; i++) { + if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) { + EcompRole role = new EcompRole(); + role.setId(userAppRoles[i].getId()); + role.setName(userAppRoles[i].getName()); + activeRoles.add(role); + } + } + EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]); + + // If the remote application isn't down we MUST sync user + // roles here in case we have this user here! + syncUserRoles(sessionFactory, userId, appId, userAppRolesActive, extRequestValue, null); + } catch (Exception e) { + // TODO: we may need to check if user exists, maybe remote + // app is down. + String message = String.format( + "getAppRolesForUser: user %s does not exist in remote application %s", userId, + Long.toString(appId)); + logger.error(EELFLoggerDelegate.errorLogger, message, e); + userAppRoles = new EcompRole[0]; + } + rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles); + } + } catch (Exception e) { + String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId, + Long.toString(appId)); + logger.error(EELFLoggerDelegate.errorLogger, message, e); + } + return rolesInAppForUser; + + } + + private boolean postUserRolesToMylogins(AppWithRolesForUser userAppRolesData, + ApplicationsRestClientService applicationsRestClientService, Long appId, Long userId) + throws JsonProcessingException, HTTPException { + boolean result = false; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String userRolesAsString = mapper.writeValueAsString(userAppRolesData); + logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, as the endpoint is not defined yet from the Mylogins"); + applicationsRestClientService.post(AppWithRolesForUser.class, appId, userRolesAsString, String.format("/user/%s/myLoginroles", userId)); + return result; + } + + public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) { + FieldsValidator fieldsValidator = new FieldsValidator(); + final Map<String, Long> params = new HashMap<>(); + EpUserAppRoles appRole= new EpUserAppRoles(); + try { + logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined"); + boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId()); + + params.put("appId", userAppRolesData.appId); + EPUserAppRolesRequest epAppRolesRequestData = new EPUserAppRolesRequest(); + epAppRolesRequestData.setCreatedDate(new Date()); + epAppRolesRequestData.setUpdatedDate(new Date()); + epAppRolesRequestData.setUserId(user.getId()); + epAppRolesRequestData.setAppId(userAppRolesData.appId); + epAppRolesRequestData.setRequestStatus("P"); + List<RoleInAppForUser> appRoleIdList = userAppRolesData.appRoles; + Set<EPUserAppRolesRequestDetail> appRoleDetails = new LinkedHashSet<EPUserAppRolesRequestDetail>(); + dataAccessService.saveDomainObject(epAppRolesRequestData, null); + for (RoleInAppForUser userAppRoles : appRoleIdList) { + Boolean isAppliedVal = userAppRoles.isApplied; + params.put("appRoleId", userAppRoles.roleId); + if (isAppliedVal) { + appRole = (EpUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0); + EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail(); + epAppRoleDetail.setReqRoleId(appRole.getRoleId()); + epAppRoleDetail.setReqType("P"); + epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData); + dataAccessService.saveDomainObject(epAppRoleDetail, null); + } + } + epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "putUserAppRolesRequest failed", e); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return fieldsValidator; + } + + public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser userid, String appName) { + Map<String, String> params = new HashMap<>(); + params.put("userid", userid.getId().toString()); + //params.put("appid", appid); + params.put("appName", appName); + + @SuppressWarnings("unchecked") + List<EPUserAppCatalogRoles> userAppRoles = (List<EPUserAppCatalogRoles>) dataAccessService + .executeNamedQuery("userAppCatalogRoles", params, null); + return userAppRoles; + } + + public String updateRemoteUserProfile(String orgUserId, Long appId) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + EPUser client = searchService.searchUserByUserId(orgUserId); + EPUser newUser = new EPUser(); + newUser.setActive(client.getActive()); + newUser.setFirstName(client.getFirstName()); + newUser.setLastName(client.getLastName()); + newUser.setLoginId(client.getLoginId()); + newUser.setLoginPwd(client.getLoginPwd()); + newUser.setMiddleInitial(client.getMiddleInitial()); + newUser.setEmail(client.getEmail()); + newUser.setOrgUserId(client.getLoginId()); + try { + String userAsString = mapper.writeValueAsString(newUser); + List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString()); + // applicationsRestClientService.post(EPUser.class, appId, + // userAsString, String.format("/user", orgUserId)); + for (EPApp eachApp : appList) { + try { + applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString, + String.format("/user/%s", orgUserId)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId() + + " in remote app. appId = " + eachApp.getId()); + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e); + return "failure"; + } + + return "success"; + } + + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalapp.portal.service.UserRolesService# + * getCachedAppRolesForUser(java.lang.Long, java.lang.Long) + */ + public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) { + // Find the records for this user-app combo, if any + String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId); + @SuppressWarnings("unchecked") + List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null); + logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size()); + return roleList; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java index 1b9dfd04..eebf3bf1 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java @@ -1,67 +1,91 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.apache.cxf.transport.http.HTTPException;
-import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser;
-import org.openecomp.portalapp.portal.domain.EPRole;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EPUserApp;
-import org.openecomp.portalapp.portal.domain.EPUserAppCatalogRoles;
-import org.openecomp.portalapp.portal.domain.ExternalSystemAccess;
-import org.openecomp.portalapp.portal.transport.AppWithRolesForUser;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.RoleInAppForUser;
-import org.openecomp.portalapp.portal.transport.UserApplicationRoles;
-
-public interface UserRolesService {
-
- public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId);
-
- public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser);
-
- public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException;
-
- public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException;
-
- /**
- * Gets entries from the local fn_user_role table for the specified user and
- * app.
- *
- * @param appId
- * ID of row in fn_app
- * @param userid
- * ID of row in fn_user
- * @return List of EPRole; empty if none found.
- */
- public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId);
-
- public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user);
-
- String setAppWithUserRoleStateForUser(ExternalSystemUser newAppRolesForUser);
-
- public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser user, String appName);
-
- public String updateRemoteUserProfile(String orgUserId, Long appId);
-
- public ExternalSystemAccess getExternalRequestAccess();
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ + +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.apache.cxf.transport.http.HTTPException; +import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.domain.EPUserAppCatalogRoles; +import org.openecomp.portalapp.portal.domain.ExternalSystemAccess; +import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; +import org.openecomp.portalapp.portal.transport.ExternalRequestFieldsValidator; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.RoleInAppForUser; +import org.openecomp.portalapp.portal.transport.UserApplicationRoles; + +public interface UserRolesService { + + /** + * Returns list of app roles of a single app + * + * @param appId + * ID of row in fn_app + * @param userId + * ID of row in fn_user + * @param extRequestValue + * set to false if request is from users page otherwise true + * @return List<RoleInAppForUser> + */ + public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId, Boolean extRequestValue); + + public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser); + + public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException; + + public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException; + + /** + * Gets entries from the local fn_user_role table for the specified user and + * app. + * + * @param appId + * ID of row in fn_app + * @param userId + * ID of row in fn_user + * @return List of EPRole; empty if none found. + */ + public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId); + + public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user); + + /** + * Save user app roles in the database from the external request + * + * @param newAppRolesForUser + * + * contains login id, app name, request id, and list of role + * names + * @param reqType + * @return if any exceptions, returns detail message and true or false + */ + ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser, String reqType); + + public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(EPUser user, String appName); + + public String updateRemoteUserProfile(String orgUserId, Long appId); + + public ExternalSystemAccess getExternalRequestAccess(); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserService.java index 2d8e9112..b08f9e8a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserService.java @@ -24,11 +24,13 @@ import java.util.List; import org.openecomp.portalapp.portal.domain.EPUser; public interface UserService { - + List<EPUser> getUserByUserId(String orgUserId); - + List<EPUser> getUserByFirstLastName(String firstName, String lastName); - + public String saveNewUser(EPUser newUser, String checkDuplicate) throws Exception; - + + public void saveUser(EPUser user) throws Exception; + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java index 4de2c497..88c482ba 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java @@ -113,7 +113,7 @@ public class UserServiceImpl implements UserService { in.close(); con.disconnect(); } catch (IOException e) { - logger.error(EELFLoggerDelegate.errorLogger,"getUserByUserId failed to close", e); + logger.error(EELFLoggerDelegate.errorLogger, "getUserByUserId failed to close", e); } } @@ -257,4 +257,9 @@ public class UserServiceImpl implements UserService { return "success"; }; + @Override + public void saveUser(EPUser user) throws Exception { + getDataAccessService().saveDomainObject(user, null); + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterService.java index df01fb96..d3c32596 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterService.java @@ -1,64 +1,64 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter;
-
-public interface WidgetParameterService {
-
- /**
- * Saves the specified user-defined widget parameters to the table ep_widget_parameters
- *
- * @param newParameter
- */
- void saveUserParameter(WidgetCatalogParameter newParameter);
-
- /**
- * Gets the specified user-defined widget parameter where paramId is used from all users
- *
- * @param paramId
- * @return
- * List of widget parameters
- */
- List<WidgetCatalogParameter> getUserParameterById(Long paramId);
-
-
- /**
- * Deletes the specified user-defined widget parameters from ep_widget_parameters table
- * where paramId is used
- *
- * @param paramId
- */
- void deleteUserParameterById(Long paramId);
-
-
- /**
- * Gets the specified user-defined widget parameter where paramId is used from the specified
- * user with userId
- * @param widgetId
- * @param userId
- * @param paramId
- * @return
- */
- WidgetCatalogParameter getUserParamById(Long widgetId, Long userId, Long paramId);
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter; + +public interface WidgetParameterService { + + /** + * Saves the specified user-defined widget parameters to the table ep_widget_parameters + * + * @param newParameter + */ + void saveUserParameter(WidgetCatalogParameter newParameter); + + /** + * Gets the specified user-defined widget parameter where paramId is used from all users + * + * @param paramId + * @return + * List of widget parameters + */ + List<WidgetCatalogParameter> getUserParameterById(Long paramId); + + + /** + * Deletes the specified user-defined widget parameters from ep_widget_parameters table + * where paramId is used + * + * @param paramId + */ + void deleteUserParameterById(Long paramId); + + + /** + * Gets the specified user-defined widget parameter where paramId is used from the specified + * user with userId + * @param widgetId + * @param userId + * @param paramId + * @return WidgetCatalogParameter + */ + WidgetCatalogParameter getUserParamById(Long widgetId, Long userId, Long paramId); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterServiceImpl.java index a3e9c61c..d7685627 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterServiceImpl.java @@ -1,92 +1,91 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.hibernate.SessionFactory;
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Restrictions;
-import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.stereotype.Service;
-
-@Service("widgetParameterService")
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class WidgetParameterServiceImpl implements WidgetParameterService{
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetParameterServiceImpl.class);
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @SuppressWarnings("unchecked")
- @Override
- public WidgetCatalogParameter getUserParamById(Long widgetId, Long userId, Long paramId) {
- List<Criterion> restrictionsList = new ArrayList<Criterion>();
- Criterion widgetIdCrit = Restrictions.eq("widgetId", widgetId);
- restrictionsList.add(widgetIdCrit);
- Criterion attIdCrit = Restrictions.eq("userId", userId);
- restrictionsList.add(attIdCrit);
- Criterion paramIdCrit = Restrictions.eq("paramId", paramId);
- restrictionsList.add(paramIdCrit);
-
-
- WidgetCatalogParameter widgetParam = null;
- List<WidgetCatalogParameter> list = (List<WidgetCatalogParameter>) dataAccessService
- .getList(WidgetCatalogParameter.class, null, restrictionsList, null);
- if(list.size() != 0)
- widgetParam = list.get(0);
- logger.debug(EELFLoggerDelegate.debugLogger,
- "getUserParamById: widget parameters: " + widgetParam);
- return widgetParam;
- }
-
- @Override
- public void saveUserParameter(WidgetCatalogParameter newParameter) {
- dataAccessService.saveDomainObject(newParameter, null);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<WidgetCatalogParameter> getUserParameterById(Long paramId) {
- List<Criterion> restrictionsList = new ArrayList<Criterion>();
- Criterion paramIdCrit = Restrictions.eq("paramId", paramId);
- restrictionsList.add(paramIdCrit);
- List<WidgetCatalogParameter> list = (List<WidgetCatalogParameter>) dataAccessService
- .getList(WidgetCatalogParameter.class, null, restrictionsList, null);
- return list;
- }
-
- @Override
- public void deleteUserParameterById(Long paramId) {
- Map<String, String> params = new HashMap<String, String>();
- params.put("paramId", Long.toString(paramId));
- dataAccessService.executeNamedQuery("deleteWidgetCatalogParameter", params, null);
- dataAccessService.executeNamedQuery("deleteMicroserviceParameterById", params, null);
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +@Service("widgetParameterService") +@EnableAspectJAutoProxy +@EPMetricsLog +public class WidgetParameterServiceImpl implements WidgetParameterService{ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetParameterServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + @SuppressWarnings("unchecked") + @Override + public WidgetCatalogParameter getUserParamById(Long widgetId, Long userId, Long paramId) { + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion widgetIdCrit = Restrictions.eq("widgetId", widgetId); + restrictionsList.add(widgetIdCrit); + Criterion attIdCrit = Restrictions.eq("userId", userId); + restrictionsList.add(attIdCrit); + Criterion paramIdCrit = Restrictions.eq("paramId", paramId); + restrictionsList.add(paramIdCrit); + + + WidgetCatalogParameter widgetParam = null; + List<WidgetCatalogParameter> list = (List<WidgetCatalogParameter>) dataAccessService + .getList(WidgetCatalogParameter.class, null, restrictionsList, null); + if(list.size() != 0) + widgetParam = list.get(0); + logger.debug(EELFLoggerDelegate.debugLogger, + "getUserParamById: widget parameters: " + widgetParam); + return widgetParam; + } + + @Override + public void saveUserParameter(WidgetCatalogParameter newParameter) { + dataAccessService.saveDomainObject(newParameter, null); + } + + @SuppressWarnings("unchecked") + @Override + public List<WidgetCatalogParameter> getUserParameterById(Long paramId) { + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion paramIdCrit = Restrictions.eq("paramId", paramId); + restrictionsList.add(paramIdCrit); + List<WidgetCatalogParameter> list = (List<WidgetCatalogParameter>) dataAccessService + .getList(WidgetCatalogParameter.class, null, restrictionsList, null); + return list; + } + + @Override + public void deleteUserParameterById(Long paramId) { + Map<String, String> params = new HashMap<String, String>(); + params.put("paramId", Long.toString(paramId)); + dataAccessService.executeNamedQuery("deleteWidgetCatalogParameter", params, null); + dataAccessService.executeNamedQuery("deleteMicroserviceParameterById", params, null); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetService.java index b44a19f3..5c3ea768 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetService.java @@ -1,36 +1,36 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.List;
-
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.OnboardingWidget;
-
-public interface WidgetService {
-
- List<OnboardingWidget> getOnboardingWidgets(EPUser user, boolean managed);
-
- FieldsValidator setOnboardingWidget(EPUser user, OnboardingWidget onboardingWidget);
-
- FieldsValidator deleteOnboardingWidget(EPUser user, Long onboardingWidgetId);
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.OnboardingWidget; + +public interface WidgetService { + + List<OnboardingWidget> getOnboardingWidgets(EPUser user, boolean managed); + + FieldsValidator setOnboardingWidget(EPUser user, OnboardingWidget onboardingWidget); + + FieldsValidator deleteOnboardingWidget(EPUser user, Long onboardingWidgetId); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetServiceImpl.java index 484bef4f..c19730e0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetServiceImpl.java @@ -1,276 +1,276 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.service;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.annotation.PostConstruct;
-import javax.servlet.http.HttpServletResponse;
-
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.Transaction;
-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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EPUserApp;
-import org.openecomp.portalapp.portal.domain.Widget;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.transport.FieldsValidator;
-import org.openecomp.portalapp.portal.transport.OnboardingWidget;
-import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-
-@Service("widgetService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class WidgetServiceImpl implements WidgetService {
-
- private static final String baseSqlToken = " widget.WIDGET_ID, widget.WDG_NAME, widget.APP_ID, app.APP_NAME, widget.WDG_WIDTH, widget.WDG_HEIGHT, widget.WDG_URL"
- + " from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID";
-
- private String validAppsFilter = "";
-
- private Long LONG_ECOMP_APP_ID = 1L;
- private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
- private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
-
- private static final String urlField = "url";
-
- private static final String nameField = "name";
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetServiceImpl.class);
-
- @Autowired
- AdminRolesService adminRolesService;
- @Autowired
- private SessionFactory sessionFactory;
- @Autowired
- private DataAccessService dataAccessService;
-
- @PostConstruct
- private void init() {
- try {
- validAppsFilter = " AND app.ENABLED = 'Y' AND app.APP_ID != " + SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
- ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
- LONG_ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID));
- } catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- }
- }
-
- private String sqlWidgetsForAllApps() {
- return "SELECT" + baseSqlToken + validAppsFilter;
- }
-
- private String sqlWidgetsForAllAppsWhereUserIsAdmin(Long userId) {
- return "SELECT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + userId
- + " AND FN_USER_ROLE.ROLE_ID = " + ACCOUNT_ADMIN_ROLE_ID + validAppsFilter;
- }
-
- private String sqlWidgetsForAllAppsWhereUserHasAnyRole(Long userId) {
- return "SELECT DISTINCT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = "
- + userId + validAppsFilter;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<OnboardingWidget> getOnboardingWidgets(EPUser user, boolean managed) {
- List<OnboardingWidget> onboardingWidgets = new ArrayList<OnboardingWidget>();
- String sql = null;
- if (adminRolesService.isSuperAdmin(user)) {
- sql = this.sqlWidgetsForAllApps();
- } else if (managed) {
- if (adminRolesService.isAccountAdmin(user)) {
- sql = this.sqlWidgetsForAllAppsWhereUserIsAdmin(user.getId());
- }
- } else if (adminRolesService.isAccountAdmin(user) || adminRolesService.isUser(user)) {
- sql = this.sqlWidgetsForAllAppsWhereUserHasAnyRole(user.getId());
- }
- if (sql != null) {
- onboardingWidgets = dataAccessService.executeSQLQuery(sql, OnboardingWidget.class, null);
- }
- return onboardingWidgets;
- }
-
- private static final Object syncRests = new Object();
-
- private boolean isUserAdminOfAppForWidget(boolean superAdmin, Long userId, Long appId) {
- if (!superAdmin) {
- @SuppressWarnings("unchecked")
- List<EPUserApp> userRoles = dataAccessService.getList(EPUserApp.class,
- " where userId = " + userId + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID + " and app.id = " + appId, null, null);
- return (userRoles.size() > 0);
- }
- return true;
- }
-
- private void validateOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
- @SuppressWarnings("unchecked")
- List<Widget> widgets = dataAccessService.getList(Widget.class,
- " where url = '" + onboardingWidget.url + "'" + " or name = '" + onboardingWidget.name + "'", null, null);
- boolean dublicatedUrl = false;
- boolean dublicatedName = false;
- for (Widget widget : widgets) {
- if (onboardingWidget.id != null && onboardingWidget.id.equals(widget.getId())) {
- // widget should not be compared with itself
- continue;
- }
- if (!dublicatedUrl && widget.getUrl().equals(onboardingWidget.url)) {
- dublicatedUrl = true;
- if (dublicatedName) {
- break;
- }
- }
- if (!dublicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.name) && widget.getAppId().equals(onboardingWidget.appId)) {
- dublicatedName = true;
- if (dublicatedUrl) {
- break;
- }
- }
- }
- if (dublicatedUrl || dublicatedName) {
- if (dublicatedUrl) {
- fieldsValidator.addProblematicFieldName(urlField);
- }
- if (dublicatedName) {
- fieldsValidator.addProblematicFieldName(nameField);
- }
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
- fieldsValidator.errorCode = DUBLICATED_FIELD_VALUE_ECOMP_ERROR;
- }
- }
-
- private void applyOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
- boolean result = false;
- Session localSession = null;
- Transaction transaction = null;
- try {
- localSession = sessionFactory.openSession();
- transaction = localSession.beginTransaction();
- Widget widget;
- if (onboardingWidget.id == null) {
- widget = new Widget();
- } else {
- widget = (Widget) localSession.get(Widget.class, onboardingWidget.id);
- }
- widget.setAppId(onboardingWidget.appId);
- widget.setName(onboardingWidget.name);
- widget.setWidth(onboardingWidget.width);
- widget.setHeight(onboardingWidget.height);
- widget.setUrl(onboardingWidget.url);
- localSession.saveOrUpdate(widget);
- transaction.commit();
- result = true;
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- EcompPortalUtils.rollbackTransaction(transaction, "applyOnboardingWidget rollback, exception = " + e);
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "applyOnboardingWidget");
- }
- if (!result) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- }
-
- private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- if (!this.isUserAdminOfAppForWidget(superAdmin, userId, onboardingWidget.appId)) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
- return fieldsValidator;
- }
- synchronized (syncRests) {
- // onboardingWidget.id is null for POST and not null for PUT
- if (onboardingWidget.id == null) {
- this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
- } else {
- Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidget.id, null);
- if (widget == null || widget.getId() == null) {
- // Widget not found
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
- return fieldsValidator;
- }
- this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
- }
- if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
- this.applyOnboardingWidget(onboardingWidget, fieldsValidator);
- }
- }
- return fieldsValidator;
- }
-
- @Override
- public FieldsValidator setOnboardingWidget(EPUser user, OnboardingWidget onboardingWidget) {
- if (onboardingWidget.name.length() == 0 || onboardingWidget.url.length() == 0 || onboardingWidget.appId == null
- || onboardingWidget.appId.equals(LONG_ECOMP_APP_ID) || onboardingWidget.width.intValue() <= 0 || onboardingWidget.height.intValue() <= 0) {
- if (onboardingWidget.appId.equals(LONG_ECOMP_APP_ID)) {
- // logger.error("Alarm!!! Security breach attempt on user " + user.getFullName() + ", userId = " + user.getUserId());
- }
- FieldsValidator fieldsValidator = new FieldsValidator();
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
- return fieldsValidator;
- }
- return this.updateOrSaveWidget(adminRolesService.isSuperAdmin(user), user.getId(), onboardingWidget);
- }
-
- @Override
- public FieldsValidator deleteOnboardingWidget(EPUser user, Long onboardingWidgetId) {
- FieldsValidator fieldsValidator = new FieldsValidator();
- synchronized (syncRests) {
- Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidgetId, null);
- if (widget != null && widget.getId() != null) { // widget exists
- if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user), user.getId(), widget.getAppId())) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
- } else {
- boolean result = false;
- Session localSession = null;
- Transaction transaction = null;
- try {
- localSession = sessionFactory.openSession();
- transaction = localSession.beginTransaction();
- localSession.delete(localSession.get(Widget.class, onboardingWidgetId));
- transaction.commit();
- result = true;
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
- EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingWidget rollback, exception = " + e);
- } finally {
- EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingWidget");
- }
- if (!result) {
- fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- }
- }
- }
- }
- return fieldsValidator;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +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 org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.domain.Widget; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.OnboardingWidget; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; + +@Service("widgetService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class WidgetServiceImpl implements WidgetService { + + private static final String baseSqlToken = " widget.WIDGET_ID, widget.WDG_NAME, widget.APP_ID, app.APP_NAME, widget.WDG_WIDTH, widget.WDG_HEIGHT, widget.WDG_URL" + + " from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID"; + + private String validAppsFilter = ""; + + private Long LONG_ECOMP_APP_ID = 1L; + private Long ACCOUNT_ADMIN_ROLE_ID = 999L; + private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR); + + private static final String urlField = "url"; + + private static final String nameField = "name"; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetServiceImpl.class); + + @Autowired + AdminRolesService adminRolesService; + @Autowired + private SessionFactory sessionFactory; + @Autowired + private DataAccessService dataAccessService; + + @PostConstruct + private void init() { + try { + validAppsFilter = " AND app.ENABLED = 'Y' AND app.APP_ID != " + SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID); + ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID)); + LONG_ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID)); + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + private String sqlWidgetsForAllApps() { + return "SELECT" + baseSqlToken + validAppsFilter; + } + + private String sqlWidgetsForAllAppsWhereUserIsAdmin(Long userId) { + return "SELECT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + userId + + " AND FN_USER_ROLE.ROLE_ID = " + ACCOUNT_ADMIN_ROLE_ID + validAppsFilter; + } + + private String sqlWidgetsForAllAppsWhereUserHasAnyRole(Long userId) { + return "SELECT DISTINCT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + + userId + validAppsFilter; + } + + @SuppressWarnings("unchecked") + @Override + public List<OnboardingWidget> getOnboardingWidgets(EPUser user, boolean managed) { + List<OnboardingWidget> onboardingWidgets = new ArrayList<OnboardingWidget>(); + String sql = null; + if (adminRolesService.isSuperAdmin(user)) { + sql = this.sqlWidgetsForAllApps(); + } else if (managed) { + if (adminRolesService.isAccountAdmin(user)) { + sql = this.sqlWidgetsForAllAppsWhereUserIsAdmin(user.getId()); + } + } else if (adminRolesService.isAccountAdmin(user) || adminRolesService.isUser(user)) { + sql = this.sqlWidgetsForAllAppsWhereUserHasAnyRole(user.getId()); + } + if (sql != null) { + onboardingWidgets = dataAccessService.executeSQLQuery(sql, OnboardingWidget.class, null); + } + return onboardingWidgets; + } + + private static final Object syncRests = new Object(); + + private boolean isUserAdminOfAppForWidget(boolean superAdmin, Long userId, Long appId) { + if (!superAdmin) { + @SuppressWarnings("unchecked") + List<EPUserApp> userRoles = dataAccessService.getList(EPUserApp.class, + " where userId = " + userId + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID + " and app.id = " + appId, null, null); + return (userRoles.size() > 0); + } + return true; + } + + private void validateOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) { + @SuppressWarnings("unchecked") + List<Widget> widgets = dataAccessService.getList(Widget.class, + " where url = '" + onboardingWidget.url + "'" + " or name = '" + onboardingWidget.name + "'", null, null); + boolean dublicatedUrl = false; + boolean dublicatedName = false; + for (Widget widget : widgets) { + if (onboardingWidget.id != null && onboardingWidget.id.equals(widget.getId())) { + // widget should not be compared with itself + continue; + } + if (!dublicatedUrl && widget.getUrl().equals(onboardingWidget.url)) { + dublicatedUrl = true; + if (dublicatedName) { + break; + } + } + if (!dublicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.name) && widget.getAppId().equals(onboardingWidget.appId)) { + dublicatedName = true; + if (dublicatedUrl) { + break; + } + } + } + if (dublicatedUrl || dublicatedName) { + if (dublicatedUrl) { + fieldsValidator.addProblematicFieldName(urlField); + } + if (dublicatedName) { + fieldsValidator.addProblematicFieldName(nameField); + } + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT); + fieldsValidator.errorCode = DUBLICATED_FIELD_VALUE_ECOMP_ERROR; + } + } + + private void applyOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) { + boolean result = false; + Session localSession = null; + Transaction transaction = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + Widget widget; + if (onboardingWidget.id == null) { + widget = new Widget(); + } else { + widget = (Widget) localSession.get(Widget.class, onboardingWidget.id); + } + widget.setAppId(onboardingWidget.appId); + widget.setName(onboardingWidget.name); + widget.setWidth(onboardingWidget.width); + widget.setHeight(onboardingWidget.height); + widget.setUrl(onboardingWidget.url); + localSession.saveOrUpdate(widget); + transaction.commit(); + result = true; + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + EcompPortalUtils.rollbackTransaction(transaction, "applyOnboardingWidget rollback, exception = " + e); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "applyOnboardingWidget"); + } + if (!result) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + + private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) { + FieldsValidator fieldsValidator = new FieldsValidator(); + if (!this.isUserAdminOfAppForWidget(superAdmin, userId, onboardingWidget.appId)) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN); + return fieldsValidator; + } + synchronized (syncRests) { + // onboardingWidget.id is null for POST and not null for PUT + if (onboardingWidget.id == null) { + this.validateOnboardingWidget(onboardingWidget, fieldsValidator); + } else { + Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidget.id, null); + if (widget == null || widget.getId() == null) { + // Widget not found + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND); + return fieldsValidator; + } + this.validateOnboardingWidget(onboardingWidget, fieldsValidator); + } + if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { + this.applyOnboardingWidget(onboardingWidget, fieldsValidator); + } + } + return fieldsValidator; + } + + @Override + public FieldsValidator setOnboardingWidget(EPUser user, OnboardingWidget onboardingWidget) { + if (onboardingWidget.name.length() == 0 || onboardingWidget.url.length() == 0 || onboardingWidget.appId == null + || onboardingWidget.appId.equals(LONG_ECOMP_APP_ID) || onboardingWidget.width.intValue() <= 0 || onboardingWidget.height.intValue() <= 0) { + if (onboardingWidget.appId.equals(LONG_ECOMP_APP_ID)) { + // logger.error("Alarm!!! Security breach attempt on user " + user.getFullName() + ", userId = " + user.getUserId()); + } + FieldsValidator fieldsValidator = new FieldsValidator(); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST); + return fieldsValidator; + } + return this.updateOrSaveWidget(adminRolesService.isSuperAdmin(user), user.getId(), onboardingWidget); + } + + @Override + public FieldsValidator deleteOnboardingWidget(EPUser user, Long onboardingWidgetId) { + FieldsValidator fieldsValidator = new FieldsValidator(); + synchronized (syncRests) { + Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidgetId, null); + if (widget != null && widget.getId() != null) { // widget exists + if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user), user.getId(), widget.getAppId())) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN); + } else { + boolean result = false; + Session localSession = null; + Transaction transaction = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + localSession.delete(localSession.get(Widget.class, onboardingWidgetId)); + transaction.commit(); + result = true; + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingWidget rollback, exception = " + e); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingWidget"); + } + if (!result) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + } + } + return fieldsValidator; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AllAppsWithRolesForUser.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AllAppsWithRolesForUser.java index da776ded..f56d6111 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AllAppsWithRolesForUser.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AllAppsWithRolesForUser.java @@ -1,40 +1,40 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.util.List;
-
-public class AllAppsWithRolesForUser {
-
- public String orgUserId;
-
- public List<AppWithUserRoles> apps;
-
- public static class AppWithUserRoles {
-
- public Long appId;
-
- public String appName;
-
- public List<RoleInAppForUser> appRoles;
-
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.util.List; + +public class AllAppsWithRolesForUser { + + public String orgUserId; + + public List<AppWithUserRoles> apps; + + public static class AppWithUserRoles { + + public Long appId; + + public String appName; + + public List<RoleInAppForUser> appRoles; + + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/Analytics.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/Analytics.java index adc5ad2b..059999a4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/Analytics.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/Analytics.java @@ -1,66 +1,66 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-@JsonInclude(JsonInclude.Include.NON_NULL)
-public class Analytics {
-
- private String action;
- private String page;
- private String function;
- private String userId;
- private String type;
-
- public String getType() {
- return type;
- }
- public void setType(String type) {
- this.type = type;
- }
- public String getAction() {
- return action;
- }
- public void setAction(String action) {
- this.action = action;
- }
- public String getPage() {
- return page;
- }
- public void setPage(String page) {
- this.page = page;
- }
- public String getFunction() {
- return function;
- }
- public void setFunction(String function) {
- this.function = function;
- }
- public String getUserId() {
- return userId;
- }
- public void setUserId(String userId) {
- this.userId = userId;
- }
-
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Analytics { + + private String action; + private String page; + private String function; + private String userId; + private String type; + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getAction() { + return action; + } + public void setAction(String action) { + this.action = action; + } + public String getPage() { + return page; + } + public void setPage(String page) { + this.page = page; + } + public String getFunction() { + return function; + } + public void setFunction(String function) { + this.function = function; + } + public String getUserId() { + return userId; + } + public void setUserId(String userId) { + this.userId = userId; + } + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppCatalogPersonalization.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppCatalogPersonalization.java index 7c24917b..f07ae6e1 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppCatalogPersonalization.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppCatalogPersonalization.java @@ -1,94 +1,94 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-/**
- * Model for the object PUT to the controller when the user takes an action on
- * an application in the catalog.
- */
-public class AppCatalogPersonalization {
-
- public Long appId;
- public Boolean select;
- public Boolean pending;
-
- public Long getAppId() {
- return appId;
- }
-
- public void setAppId(Long appId) {
- this.appId = appId;
- }
-
- public Boolean getSelect() {
- return select;
- }
-
- public void setSelect(Boolean select) {
- this.select = select;
- }
-
- public Boolean getPending() {
- return pending;
- }
-
- public void setPending(Boolean pending) {
- this.pending = pending;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((appId == null) ? 0 : appId.hashCode());
- result = prime * result + ((pending == null) ? 0 : pending.hashCode());
- result = prime * result + ((select == null) ? 0 : select.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- AppCatalogPersonalization other = (AppCatalogPersonalization) obj;
- if (appId == null) {
- if (other.appId != null)
- return false;
- } else if (!appId.equals(other.appId))
- return false;
- if (pending == null) {
- if (other.pending != null)
- return false;
- } else if (!pending.equals(other.pending))
- return false;
- if (select == null) {
- if (other.select != null)
- return false;
- } else if (!select.equals(other.select))
- return false;
- return true;
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +/** + * Model for the object PUT to the controller when the user takes an action on + * an application in the catalog. + */ +public class AppCatalogPersonalization { + + public Long appId; + public Boolean select; + public Boolean pending; + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public Boolean getSelect() { + return select; + } + + public void setSelect(Boolean select) { + this.select = select; + } + + public Boolean getPending() { + return pending; + } + + public void setPending(Boolean pending) { + this.pending = pending; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((appId == null) ? 0 : appId.hashCode()); + result = prime * result + ((pending == null) ? 0 : pending.hashCode()); + result = prime * result + ((select == null) ? 0 : select.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AppCatalogPersonalization other = (AppCatalogPersonalization) obj; + if (appId == null) { + if (other.appId != null) + return false; + } else if (!appId.equals(other.appId)) + return false; + if (pending == null) { + if (other.pending != null) + return false; + } else if (!pending.equals(other.pending)) + return false; + if (select == null) { + if (other.select != null) + return false; + } else if (!select.equals(other.select)) + return false; + return true; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppNameIdIsAdmin.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppNameIdIsAdmin.java index 484fffad..135b298c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppNameIdIsAdmin.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppNameIdIsAdmin.java @@ -1,114 +1,114 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-public class AppNameIdIsAdmin {
-
- public Long id;
-
- public String appName;
-
- public Boolean isAdmin;
-
- public Boolean restrictedApp;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getAppName() {
- return appName;
- }
-
- public void setAppName(String appName) {
- this.appName = appName;
- }
-
- public Boolean getIsAdmin() {
- return isAdmin;
- }
-
- public void setIsAdmin(Boolean isAdmin) {
- this.isAdmin = isAdmin;
- }
-
- public Boolean getRestrictedApp() {
- return restrictedApp;
- }
-
- public void setRestrictedApp(Boolean restrictedApp) {
- this.restrictedApp = restrictedApp;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((appName == null) ? 0 : appName.hashCode());
- result = prime * result + ((id == null) ? 0 : id.hashCode());
- result = prime * result + ((isAdmin == null) ? 0 : isAdmin.hashCode());
- result = prime * result + ((restrictedApp == null) ? 0 : restrictedApp.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- AppNameIdIsAdmin other = (AppNameIdIsAdmin) obj;
- if (appName == null) {
- if (other.appName != null)
- return false;
- } else if (!appName.equals(other.appName))
- return false;
- if (id == null) {
- if (other.id != null)
- return false;
- } else if (!id.equals(other.id))
- return false;
- if (isAdmin == null) {
- if (other.isAdmin != null)
- return false;
- } else if (!isAdmin.equals(other.isAdmin))
- return false;
- if (restrictedApp == null) {
- if (other.restrictedApp != null)
- return false;
- } else if (!restrictedApp.equals(other.restrictedApp))
- return false;
- return true;
- }
-
- @Override
- public String toString() {
- return "AppNameIdIsAdmin [id=" + id + ", appName=" + appName + ", isAdmin=" + isAdmin + ", restrictedApp="
- + restrictedApp + "]";
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +public class AppNameIdIsAdmin { + + public Long id; + + public String appName; + + public Boolean isAdmin; + + public Boolean restrictedApp; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public Boolean getIsAdmin() { + return isAdmin; + } + + public void setIsAdmin(Boolean isAdmin) { + this.isAdmin = isAdmin; + } + + public Boolean getRestrictedApp() { + return restrictedApp; + } + + public void setRestrictedApp(Boolean restrictedApp) { + this.restrictedApp = restrictedApp; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((appName == null) ? 0 : appName.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((isAdmin == null) ? 0 : isAdmin.hashCode()); + result = prime * result + ((restrictedApp == null) ? 0 : restrictedApp.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AppNameIdIsAdmin other = (AppNameIdIsAdmin) obj; + if (appName == null) { + if (other.appName != null) + return false; + } else if (!appName.equals(other.appName)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (isAdmin == null) { + if (other.isAdmin != null) + return false; + } else if (!isAdmin.equals(other.isAdmin)) + return false; + if (restrictedApp == null) { + if (other.restrictedApp != null) + return false; + } else if (!restrictedApp.equals(other.restrictedApp)) + return false; + return true; + } + + @Override + public String toString() { + return "AppNameIdIsAdmin [id=" + id + ", appName=" + appName + ", isAdmin=" + isAdmin + ", restrictedApp=" + + restrictedApp + "]"; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppWithRolesForUser.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppWithRolesForUser.java index 4e37ee00..16ba67b5 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppWithRolesForUser.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppWithRolesForUser.java @@ -1,73 +1,72 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.util.List;
-
-public class AppWithRolesForUser {
-
- public String orgUserId;
-
- public Long appId;
-
- public String appName;
-
- public List<RoleInAppForUser> appRoles;
-
- public String getOrgUserId() {
- return orgUserId;
- }
-
- public void setOrgUserId(String orgUserId) {
- this.orgUserId = orgUserId;
- }
-
- public Long getAppId() {
- return appId;
- }
-
- public void setAppId(Long appId) {
- this.appId = appId;
- }
-
- public String getAppName() {
- return appName;
- }
-
- public void setAppName(String appName) {
- this.appName = appName;
- }
-
- public List<RoleInAppForUser> getAppRoles() {
- return appRoles;
- }
-
- public void setAppRoles(List<RoleInAppForUser> appRoles) {
- this.appRoles = appRoles;
- }
-
- @Override
- public String toString() {
- return "AppWithRolesForUser [orgUserId=" + orgUserId + ", appId=" + appId + ", appName=" + appName
- + ", appRoles=" + appRoles + "]";
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.util.List; + +public class AppWithRolesForUser { + + public String orgUserId; + + public Long appId; + + public String appName; + + public List<RoleInAppForUser> appRoles; + + public String getOrgUserId() { + return orgUserId; + } + + public void setOrgUserId(String orgUserId) { + this.orgUserId = orgUserId; + } + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public List<RoleInAppForUser> getAppRoles() { + return appRoles; + } + + public void setAppRoles(List<RoleInAppForUser> appRoles) { + this.appRoles = appRoles; + } + + @Override + public String toString() { + return "AppWithRolesForUser [orgUserId=" + orgUserId + ", appId=" + appId + ", appName=" + appName + + ", appRoles=" + appRoles + "]"; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppsListWithAdminRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppsListWithAdminRole.java index 0000e2a7..fc9bc88c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppsListWithAdminRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/AppsListWithAdminRole.java @@ -1,86 +1,86 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.util.ArrayList;
-
-public class AppsListWithAdminRole {
-
- public String orgUserId;
-
- public ArrayList<AppNameIdIsAdmin> appsRoles;
-
- public AppsListWithAdminRole() {
- appsRoles = new ArrayList<AppNameIdIsAdmin>();
- }
-
- public String getOrgUserId() {
- return orgUserId;
- }
-
- public void setOrgUserId(String orgUserId) {
- this.orgUserId = orgUserId;
- }
-
- public ArrayList<AppNameIdIsAdmin> getAppsRoles() {
- return appsRoles;
- }
-
- public void setAppsRoles(ArrayList<AppNameIdIsAdmin> appsRoles) {
- this.appsRoles = appsRoles;
- }
-
- @Override
- public String toString() {
- return "AppsListWithAdminRole [orgUserId=" + orgUserId + ", appsRoles=" + appsRoles + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((appsRoles == null) ? 0 : appsRoles.hashCode());
- result = prime * result + ((orgUserId == null) ? 0 : orgUserId.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- AppsListWithAdminRole other = (AppsListWithAdminRole) obj;
- if (appsRoles == null) {
- if (other.appsRoles != null)
- return false;
- } else if (!appsRoles.equals(other.appsRoles))
- return false;
- if (orgUserId == null) {
- if (other.orgUserId != null)
- return false;
- } else if (!orgUserId.equals(other.orgUserId))
- return false;
- return true;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.util.ArrayList; + +public class AppsListWithAdminRole { + + public String orgUserId; + + public ArrayList<AppNameIdIsAdmin> appsRoles; + + public AppsListWithAdminRole() { + appsRoles = new ArrayList<AppNameIdIsAdmin>(); + } + + public String getOrgUserId() { + return orgUserId; + } + + public void setOrgUserId(String orgUserId) { + this.orgUserId = orgUserId; + } + + public ArrayList<AppNameIdIsAdmin> getAppsRoles() { + return appsRoles; + } + + public void setAppsRoles(ArrayList<AppNameIdIsAdmin> appsRoles) { + this.appsRoles = appsRoles; + } + + @Override + public String toString() { + return "AppsListWithAdminRole [orgUserId=" + orgUserId + ", appsRoles=" + appsRoles + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((appsRoles == null) ? 0 : appsRoles.hashCode()); + result = prime * result + ((orgUserId == null) ? 0 : orgUserId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AppsListWithAdminRole other = (AppsListWithAdminRole) obj; + if (appsRoles == null) { + if (other.appsRoles != null) + return false; + } else if (!appsRoles.equals(other.appsRoles)) + return false; + if (orgUserId == null) { + if (other.orgUserId != null) + return false; + } else if (!orgUserId.equals(other.orgUserId)) + return false; + return true; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRole.java index 47658786..5fb847f4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRole.java @@ -1,108 +1,108 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-@Entity
-@JsonInclude(JsonInclude.Include.NON_NULL)
-public class BusinessCardApplicationRole implements Serializable{
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
-
- public BusinessCardApplicationRole() {
- }
-
-
- @Id
- @Column(name="app_name")
- private String appName;
-
- @Id
- @Column(name="role_name")
- private String roleName;
-
-
- public String getAppName() {
- return appName;
- }
-
- public void setAppName(String appName) {
- this.appName = appName;
- }
-
-
-
- public String getRoleName() {
- return roleName;
- }
-
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
-
- @Override
- public String toString() {
- return "BusinessCardUserApplicationRoles [appName=" + appName + ", roleName=" + roleName + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((appName == null) ? 0 : appName.hashCode());
- result = prime * result + ((roleName == null) ? 0 : roleName.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- BusinessCardApplicationRole other = (BusinessCardApplicationRole) obj;
- if (appName == null) {
- if (other.appName != null)
- return false;
- } else if (!appName.equals(other.appName))
- return false;
- if (roleName == null) {
- if (other.roleName != null)
- return false;
- } else if (!roleName.equals(other.roleName))
- return false;
- return true;
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@Entity +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BusinessCardApplicationRole implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + + public BusinessCardApplicationRole() { + } + + + @Id + @Column(name="app_name") + private String appName; + + @Id + @Column(name="role_name") + private String roleName; + + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + @Override + public String toString() { + return "BusinessCardUserApplicationRoles [appName=" + appName + ", roleName=" + roleName + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((appName == null) ? 0 : appName.hashCode()); + result = prime * result + ((roleName == null) ? 0 : roleName.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BusinessCardApplicationRole other = (BusinessCardApplicationRole) obj; + if (appName == null) { + if (other.appName != null) + return false; + } else if (!appName.equals(other.appName)) + return false; + if (roleName == null) { + if (other.roleName != null) + return false; + } else if (!roleName.equals(other.roleName)) + return false; + return true; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRolesList.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRolesList.java index 15c3aff2..51feb115 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRolesList.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRolesList.java @@ -1,86 +1,86 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.util.List;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-@JsonInclude(JsonInclude.Include.NON_NULL)
-public class BusinessCardApplicationRolesList {
-
- public BusinessCardApplicationRolesList(){}
-
- private String appName;
- private List<String> roleNames;
-
-
- public String getAppName() {
- return appName;
- }
- public void setAppName(String appName) {
- this.appName = appName;
- }
- public List<String> getRoleNames() {
- return roleNames;
- }
- public void setRoleNames(List<String> roleNames) {
- this.roleNames = roleNames;
- }
- public BusinessCardApplicationRolesList(String appName, List<String> roleNames) {
- super();
- this.appName = appName;
- this.roleNames = roleNames;
- }
- @Override
- public String toString() {
- return "BusinessCardUserAppRoles [appName=" + appName + ", roleNames=" + roleNames + "]";
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((appName == null) ? 0 : appName.hashCode());
- result = prime * result + ((roleNames == null) ? 0 : roleNames.hashCode());
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- BusinessCardApplicationRolesList other = (BusinessCardApplicationRolesList) obj;
- if (appName == null) {
- if (other.appName != null)
- return false;
- } else if (!appName.equals(other.appName))
- return false;
- if (roleNames == null) {
- if (other.roleNames != null)
- return false;
- } else if (!roleNames.equals(other.roleNames))
- return false;
- return true;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BusinessCardApplicationRolesList { + + public BusinessCardApplicationRolesList(){} + + private String appName; + private List<String> roleNames; + + + public String getAppName() { + return appName; + } + public void setAppName(String appName) { + this.appName = appName; + } + public List<String> getRoleNames() { + return roleNames; + } + public void setRoleNames(List<String> roleNames) { + this.roleNames = roleNames; + } + public BusinessCardApplicationRolesList(String appName, List<String> roleNames) { + super(); + this.appName = appName; + this.roleNames = roleNames; + } + @Override + public String toString() { + return "BusinessCardUserAppRoles [appName=" + appName + ", roleNames=" + roleNames + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((appName == null) ? 0 : appName.hashCode()); + result = prime * result + ((roleNames == null) ? 0 : roleNames.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BusinessCardApplicationRolesList other = (BusinessCardApplicationRolesList) obj; + if (appName == null) { + if (other.appName != null) + return false; + } else if (!appName.equals(other.appName)) + return false; + if (roleNames == null) { + if (other.roleNames != null) + return false; + } else if (!roleNames.equals(other.roleNames)) + return false; + return true; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidget.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidget.java index da2ae4ea..ceb5d46d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidget.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidget.java @@ -1,139 +1,139 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-/**
- * This is to handle portal admins
- * @author aw3218
- */
-@Entity
-@Table(name="fn_common_widget_data")
-@JsonInclude(JsonInclude.Include.NON_NULL)
-public class CommonWidget extends DomainVo{
-
- private static final long serialVersionUID = 7897021982887364557L;
-
- @Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- @Column(name = "id")
- private Long id;
-
- @Column(name = "category")
- public String category;
-
- @Column(name = "href")
- public String href;
-
- @Column(name = "title")
- public String title;
-
- @Column(name = "content")
- public String content;
-
- @Column(name = "event_date")
- public String eventDate;
-
- @Column(name = "sort_order")
- public Integer sortOrder;
-
-
- public CommonWidget(){
-
- }
-
- public CommonWidget(String category, String href, String title, String content, String eventDate, Integer sortOrder){
- this.category = category;
- this.href = href;
- this.title = title;
- this.content = content;
- this.eventDate = eventDate;
- this.sortOrder = sortOrder;
- }
-
- public String getCategory() {
- return category;
- }
-
- public void setCategory(String category) {
- this.category = category;
- }
-
- public String getHref() {
- return href;
- }
-
- public void setHref(String href) {
- this.href = href;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public Integer getSortOrder() {
- return sortOrder;
- }
-
- public void setSortOrder(Integer sortOrder) {
- this.sortOrder = sortOrder;
- }
-
- public static long getSerialversionuid() {
- return serialVersionUID;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getContent() {
- return content;
- }
-
- public void setContent(String content) {
- this.content = content;
- }
-
- public String getEventDate() {
- return eventDate;
- }
-
- public void setEventDate(String eventDate) {
- this.eventDate = eventDate;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; +import com.fasterxml.jackson.annotation.JsonInclude; + +/** + * This is to handle portal admins + * @author aw3218 + */ +@Entity +@Table(name="fn_common_widget_data") +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CommonWidget extends DomainVo{ + + private static final long serialVersionUID = 7897021982887364557L; + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + @Column(name = "id") + private Long id; + + @Column(name = "category") + public String category; + + @Column(name = "href") + public String href; + + @Column(name = "title") + public String title; + + @Column(name = "content") + public String content; + + @Column(name = "event_date") + public String eventDate; + + @Column(name = "sort_order") + public Integer sortOrder; + + + public CommonWidget(){ + + } + + public CommonWidget(String category, String href, String title, String content, String eventDate, Integer sortOrder){ + this.category = category; + this.href = href; + this.title = title; + this.content = content; + this.eventDate = eventDate; + this.sortOrder = sortOrder; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getHref() { + return href; + } + + public void setHref(String href) { + this.href = href; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Integer getSortOrder() { + return sortOrder; + } + + public void setSortOrder(Integer sortOrder) { + this.sortOrder = sortOrder; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public String getEventDate() { + return eventDate; + } + + public void setEventDate(String eventDate) { + this.eventDate = eventDate; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidgetMeta.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidgetMeta.java index ad71b081..ebf2439b 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidgetMeta.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidgetMeta.java @@ -1,50 +1,50 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.util.List;
-
-public class CommonWidgetMeta {
-
- private String category;
- private List<CommonWidget> items;
-
- public CommonWidgetMeta(){
-
- }
-
- public CommonWidgetMeta(String category, List<CommonWidget> items){
- this.category = category;
- this.items = items;
- }
-
- public String getCategory() {
- return category;
- }
- public void setCategory(String category) {
- this.category = category;
- }
- public List<CommonWidget> getItems() {
- return items;
- }
- public void setItems(List<CommonWidget> items) {
- this.items = items;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.util.List; + +public class CommonWidgetMeta { + + private String category; + private List<CommonWidget> items; + + public CommonWidgetMeta(){ + + } + + public CommonWidgetMeta(String category, List<CommonWidget> items){ + this.category = category; + this.items = items; + } + + public String getCategory() { + return category; + } + public void setCategory(String category) { + this.category = category; + } + public List<CommonWidget> getItems() { + return items; + } + public void setItems(List<CommonWidget> items) { + this.items = items; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPAppsManualPreference.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPAppsManualPreference.java index 658ef51e..7d8b8cda 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPAppsManualPreference.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPAppsManualPreference.java @@ -1,114 +1,114 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-public class EPAppsManualPreference {
-
- private Long appid;
- private int col;
- private String headerText;
- private String imageLink;
- private int order;
- private boolean restrictedApp;
- private int row;
- private int sizeX;
- private int sizeY;
- private String subHeaderText;
- private String url;
- private boolean addRemoveApps;
-
-
- public boolean isAddRemoveApps() {
- return addRemoveApps;
- }
- public void setAddRemoveApps(boolean addRemoveApps) {
- this.addRemoveApps = addRemoveApps;
- }
- public Long getAppid() {
- return appid;
- }
- public void setAppid(Long appid) {
- this.appid = appid;
- }
- public int getCol() {
- return col;
- }
- public void setCol(int col) {
- this.col = col;
- }
- public String getHeaderText() {
- return headerText;
- }
- public void setHeaderText(String headerText) {
- this.headerText = headerText;
- }
- public String getImageLink() {
- return imageLink;
- }
- public void setImageLink(String imageLink) {
- this.imageLink = imageLink;
- }
- public int getOrder() {
- return order;
- }
- public void setOrder(int order) {
- this.order = order;
- }
- public boolean isRestrictedApp() {
- return restrictedApp;
- }
- public void setRestrictedApp(boolean restrictedApp) {
- this.restrictedApp = restrictedApp;
- }
- public int getRow() {
- return row;
- }
- public void setRow(int row) {
- this.row = row;
- }
- public int getSizeX() {
- return sizeX;
- }
- public void setSizeX(int sizeX) {
- this.sizeX = sizeX;
- }
- public int getSizeY() {
- return sizeY;
- }
- public void setSizeY(int sizeY) {
- this.sizeY = sizeY;
- }
- public String getSubHeaderText() {
- return subHeaderText;
- }
- public void setSubHeaderText(String subHeaderText) {
- this.subHeaderText = subHeaderText;
- }
- public String getUrl() {
- return url;
- }
- public void setUrl(String url) {
- this.url = url;
- }
-
- public boolean isValid(){
- return appid != null;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +public class EPAppsManualPreference { + + private Long appid; + private int col; + private String headerText; + private String imageLink; + private int order; + private boolean restrictedApp; + private int row; + private int sizeX; + private int sizeY; + private String subHeaderText; + private String url; + private boolean addRemoveApps; + + + public boolean isAddRemoveApps() { + return addRemoveApps; + } + public void setAddRemoveApps(boolean addRemoveApps) { + this.addRemoveApps = addRemoveApps; + } + public Long getAppid() { + return appid; + } + public void setAppid(Long appid) { + this.appid = appid; + } + public int getCol() { + return col; + } + public void setCol(int col) { + this.col = col; + } + public String getHeaderText() { + return headerText; + } + public void setHeaderText(String headerText) { + this.headerText = headerText; + } + public String getImageLink() { + return imageLink; + } + public void setImageLink(String imageLink) { + this.imageLink = imageLink; + } + public int getOrder() { + return order; + } + public void setOrder(int order) { + this.order = order; + } + public boolean isRestrictedApp() { + return restrictedApp; + } + public void setRestrictedApp(boolean restrictedApp) { + this.restrictedApp = restrictedApp; + } + public int getRow() { + return row; + } + public void setRow(int row) { + this.row = row; + } + public int getSizeX() { + return sizeX; + } + public void setSizeX(int sizeX) { + this.sizeX = sizeX; + } + public int getSizeY() { + return sizeY; + } + public void setSizeY(int sizeY) { + this.sizeY = sizeY; + } + public String getSubHeaderText() { + return subHeaderText; + } + public void setSubHeaderText(String subHeaderText) { + this.subHeaderText = subHeaderText; + } + public String getUrl() { + return url; + } + public void setUrl(String url) { + this.url = url; + } + + public boolean isValid(){ + return appid != null; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPAppsSortPreference.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPAppsSortPreference.java index 8aa0860c..5e337bb8 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPAppsSortPreference.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPAppsSortPreference.java @@ -1,47 +1,47 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-public class EPAppsSortPreference {
-
- private int index;
- private String value;
- private String title;
-
- public int getIndex() {
- return index;
- }
- public void setIndex(int index) {
- this.index = index;
- }
- public String getValue() {
- return value;
- }
- public void setValue(String value) {
- this.value = value;
- }
- public String getTitle() {
- return title;
- }
- public void setTitle(String title) {
- this.title = title;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +public class EPAppsSortPreference { + + private int index; + private String value; + private String title; + + public int getIndex() { + return index; + } + public void setIndex(int index) { + this.index = index; + } + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + public String getTitle() { + return title; + } + public void setTitle(String title) { + this.title = title; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPDeleteAppsManualSortPref.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPDeleteAppsManualSortPref.java index 700b74b1..73a12ee5 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPDeleteAppsManualSortPref.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPDeleteAppsManualSortPref.java @@ -1,51 +1,51 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-public class EPDeleteAppsManualSortPref {
- private Long appId;
- private boolean select;
- private boolean pending;
-
- public Long getAppId() {
- return appId;
- }
-
- public void setAppId(Long appId) {
- this.appId = appId;
- }
-
- public boolean isSelect() {
- return select;
- }
-
- public void setSelect(boolean select) {
- this.select = select;
- }
-
- public boolean isPending() {
- return pending;
- }
-
- public void setPending(boolean pending) {
- this.pending = pending;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +public class EPDeleteAppsManualSortPref { + private Long appId; + private boolean select; + private boolean pending; + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public boolean isSelect() { + return select; + } + + public void setSelect(boolean select) { + this.select = select; + } + + public boolean isPending() { + return pending; + } + + public void setPending(boolean pending) { + this.pending = pending; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPWidgetsSortPreference.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPWidgetsSortPreference.java index 3fadf1a4..bb29ef71 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPWidgetsSortPreference.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPWidgetsSortPreference.java @@ -1,92 +1,92 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.util.List;
-
-public class EPWidgetsSortPreference {
-
- private int SizeX;
- private int SizeY;
- private String headerText;
- private String url;
- private Long widgetid;
- private List<Object> attrb;
- private String widgetIdentifier;
- private int row;
- private int col;
-
- public String getWidgetIdentifier() {
- return widgetIdentifier;
- }
- public List<Object> getAttrb() {
- return attrb;
- }
- public void setAttrb(List<Object> attrb) {
- this.attrb = attrb;
- }
- public void setWidgetIdentifier(String widgetIdentifier) {
- this.widgetIdentifier = widgetIdentifier;
- }
- public int getSizeX() {
- return SizeX;
- }
- public void setSizeX(int sizeX) {
- SizeX = sizeX;
- }
- public int getSizeY() {
- return SizeY;
- }
- public void setSizeY(int sizeY) {
- SizeY = sizeY;
- }
- public String getHeaderText() {
- return headerText;
- }
- public void setHeaderText(String headerText) {
- this.headerText = headerText;
- }
- public String getUrl() {
- return url;
- }
- public void setUrl(String url) {
- this.url = url;
- }
- public Long getWidgetid() {
- return widgetid;
- }
- public void setWidgetid(Long widgetid) {
- this.widgetid = widgetid;
- }
- public int getRow() {
- return row;
- }
- public void setRow(int row) {
- this.row = row;
- }
- public int getCol() {
- return col;
- }
- public void setCol(int col) {
- this.col = col;
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.util.List; + +public class EPWidgetsSortPreference { + + private int SizeX; + private int SizeY; + private String headerText; + private String url; + private Long widgetid; + private List<Object> attrb; + private String widgetIdentifier; + private int row; + private int col; + + public String getWidgetIdentifier() { + return widgetIdentifier; + } + public List<Object> getAttrb() { + return attrb; + } + public void setAttrb(List<Object> attrb) { + this.attrb = attrb; + } + public void setWidgetIdentifier(String widgetIdentifier) { + this.widgetIdentifier = widgetIdentifier; + } + public int getSizeX() { + return SizeX; + } + public void setSizeX(int sizeX) { + SizeX = sizeX; + } + public int getSizeY() { + return SizeY; + } + public void setSizeY(int sizeY) { + SizeY = sizeY; + } + public String getHeaderText() { + return headerText; + } + public void setHeaderText(String headerText) { + this.headerText = headerText; + } + public String getUrl() { + return url; + } + public void setUrl(String url) { + this.url = url; + } + public Long getWidgetid() { + return widgetid; + } + public void setWidgetid(Long widgetid) { + this.widgetid = widgetid; + } + public int getRow() { + return row; + } + public void setRow(int row) { + this.row = row; + } + public int getCol() { + return col; + } + public void setCol(int col) { + this.col = col; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItem.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItem.java index 94fbe59a..00df522a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItem.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItem.java @@ -1,328 +1,328 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.util.Date;
-import java.util.List;
-import java.util.Set;
-
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
-import javax.persistence.Transient;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-
-/**
- * This is to handle notifications in notification PopUp
- */
-
-
-@Entity
-@Table(name = "ep_notification")
-public class EpNotificationItem extends DomainVo {
- public EpNotificationItem() {
- };
-
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column(name = "notification_ID")
- public Long notificationId;
-
- @Column(name = "is_for_online_users")
- public String isForOnlineUsers;
-
- @Column(name = "is_for_all_roles")
- public String isForAllRoles;
-
- @Column(name = "active_YN")
- public String activeYn;
-
- @Column(name = "msg_header")
- public String msgHeader;
-
- @Column(name = "msg_description")
- public String msgDescription;
-
- @Column(name = "msg_source")
- public String msgSource;
-
- @Column(name = "start_time")
- public Date startTime;
-
- @Column(name = "end_time")
- public Date endTime;
-
- @Column(name = "priority")
- public Long priority;
-
- @Column(name = "creator_ID")
- public Long creatorId;
-
- @Column(name = "created_date")
- public Date createdDate;
-
-
- @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}, orphanRemoval = true)
- @JoinColumn(name="notification_ID")
- private Set<EpRoleNotificationItem> roles;
-
- @Transient
- private List<Long> roleIds;
-
- public Long getNotificationId() {
- return notificationId;
- }
-
- public void setNotificationId(Long notificationId) {
- this.notificationId = notificationId;
- }
-
- public String getIsForOnlineUsers() {
- return isForOnlineUsers;
- }
-
- public void setIsForOnlineUsers(String isForOnlineUsers) {
- this.isForOnlineUsers = isForOnlineUsers;
- }
-
- public String getIsForAllRoles() {
- return isForAllRoles;
- }
-
- public void setIsForAllRoles(String isForAllRoles) {
- this.isForAllRoles = isForAllRoles;
- }
-
- public String getActiveYn() {
- return activeYn;
- }
-
- public void setActiveYn(String activeYn) {
- this.activeYn = activeYn;
- }
-
- public String getMsgHeader() {
- return msgHeader;
- }
-
- public void setMsgHeader(String msgHeader) {
- this.msgHeader = msgHeader;
- }
-
- public String getMsgDescription() {
- return msgDescription;
- }
-
- public void setMsgDescription(String msgDescription) {
- this.msgDescription = msgDescription;
- }
-
- public Date getStartTime() {
- return startTime;
- }
-
- public void setStartTime(Date startTime) {
- this.startTime = startTime;
- }
-
- public Date getEndTime() {
- return endTime;
- }
-
- public void setEndTime(Date endTime) {
- this.endTime = endTime;
- }
-
- public Long getPriority() {
- return priority;
- }
-
- public void setPriority(Long priority) {
- this.priority = priority;
- }
-
- public Long getCreatorId() {
- return creatorId;
- }
-
- public void setCreatorId(Long creatorId) {
- this.creatorId = creatorId;
- }
-
- public Date getCreatedDate() {
- return createdDate;
- }
-
- public void setCreatedDate(Date createdDate) {
- this.createdDate = createdDate;
- }
-
- public static long getSerialversionuid() {
- return serialVersionUID;
- }
-
- public Set<EpRoleNotificationItem> getRoles() {
- return roles;
- }
-
- public void setRoles(Set<EpRoleNotificationItem> roles) {
- this.roles = roles;
- }
-
- public List<Long> getRoleIds() {
- return roleIds;
- }
-
- public void setRoleIds(List<Long> roleIds) {
- this.roleIds = roleIds;
- }
-
- public String getMsgSource() {
- return msgSource;
- }
-
- public void setMsgSource(String msgSource) {
- this.msgSource = msgSource;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((activeYn == null) ? 0 : activeYn.hashCode());
- result = prime * result + ((createdDate == null) ? 0 : createdDate.hashCode());
- result = prime * result + ((creatorId == null) ? 0 : creatorId.hashCode());
- result = prime * result + ((endTime == null) ? 0 : endTime.hashCode());
- result = prime * result + ((isForAllRoles == null) ? 0 : isForAllRoles.hashCode());
- result = prime * result + ((isForOnlineUsers == null) ? 0 : isForOnlineUsers.hashCode());
- result = prime * result + ((msgDescription == null) ? 0 : msgDescription.hashCode());
- result = prime * result + ((msgHeader == null) ? 0 : msgHeader.hashCode());
- result = prime * result + ((msgSource == null) ? 0 : msgSource.hashCode());
- result = prime * result + ((notificationId == null) ? 0 : notificationId.hashCode());
- result = prime * result + ((priority == null) ? 0 : priority.hashCode());
- result = prime * result + ((roleIds == null) ? 0 : roleIds.hashCode());
- result = prime * result + ((roles == null) ? 0 : roles.hashCode());
- result = prime * result + ((startTime == null) ? 0 : startTime.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- EpNotificationItem other = (EpNotificationItem) obj;
- if (activeYn == null) {
- if (other.activeYn != null)
- return false;
- } else if (!activeYn.equals(other.activeYn))
- return false;
- if (createdDate == null) {
- if (other.createdDate != null)
- return false;
- } else if (!createdDate.equals(other.createdDate))
- return false;
- if (creatorId == null) {
- if (other.creatorId != null)
- return false;
- } else if (!creatorId.equals(other.creatorId))
- return false;
- if (endTime == null) {
- if (other.endTime != null)
- return false;
- } else if (!endTime.equals(other.endTime))
- return false;
- if (isForAllRoles == null) {
- if (other.isForAllRoles != null)
- return false;
- } else if (!isForAllRoles.equals(other.isForAllRoles))
- return false;
- if (isForOnlineUsers == null) {
- if (other.isForOnlineUsers != null)
- return false;
- } else if (!isForOnlineUsers.equals(other.isForOnlineUsers))
- return false;
- if (msgDescription == null) {
- if (other.msgDescription != null)
- return false;
- } else if (!msgDescription.equals(other.msgDescription))
- return false;
- if (msgHeader == null) {
- if (other.msgHeader != null)
- return false;
- } else if (!msgHeader.equals(other.msgHeader))
- return false;
- if (msgSource == null) {
- if (other.msgSource != null)
- return false;
- } else if (!msgSource.equals(other.msgSource))
- return false;
- if (notificationId == null) {
- if (other.notificationId != null)
- return false;
- } else if (!notificationId.equals(other.notificationId))
- return false;
- if (priority == null) {
- if (other.priority != null)
- return false;
- } else if (!priority.equals(other.priority))
- return false;
- if (roleIds == null) {
- if (other.roleIds != null)
- return false;
- } else if (!roleIds.equals(other.roleIds))
- return false;
- if (roles == null) {
- if (other.roles != null)
- return false;
- } else if (!roles.equals(other.roles))
- return false;
- if (startTime == null) {
- if (other.startTime != null)
- return false;
- } else if (!startTime.equals(other.startTime))
- return false;
- return true;
- }
-
- @Override
- public String toString() {
- return "EpNotificationItem [notificationId=" + notificationId + ", isForOnlineUsers=" + isForOnlineUsers
- + ", isForAllRoles=" + isForAllRoles + ", activeYn=" + activeYn + ", msgHeader=" + msgHeader
- + ", msgDescription=" + msgDescription + ", msgSource=" + msgSource + ", startTime=" + startTime
- + ", endTime=" + endTime + ", priority=" + priority + ", creatorId=" + creatorId + ", createdDate="
- + createdDate + ", roles=" + roles + ", roleIds=" + roleIds + "]";
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.util.Date; +import java.util.List; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.persistence.Transient; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + + +/** + * This is to handle notifications in notification PopUp + */ + + +@Entity +@Table(name = "ep_notification") +public class EpNotificationItem extends DomainVo { + public EpNotificationItem() { + }; + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "notification_ID") + public Long notificationId; + + @Column(name = "is_for_online_users") + public String isForOnlineUsers; + + @Column(name = "is_for_all_roles") + public String isForAllRoles; + + @Column(name = "active_YN") + public String activeYn; + + @Column(name = "msg_header") + public String msgHeader; + + @Column(name = "msg_description") + public String msgDescription; + + @Column(name = "msg_source") + public String msgSource; + + @Column(name = "start_time") + public Date startTime; + + @Column(name = "end_time") + public Date endTime; + + @Column(name = "priority") + public Long priority; + + @Column(name = "creator_ID") + public Long creatorId; + + @Column(name = "created_date") + public Date createdDate; + + + @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}, orphanRemoval = true) + @JoinColumn(name="notification_ID") + private Set<EpRoleNotificationItem> roles; + + @Transient + private List<Long> roleIds; + + public Long getNotificationId() { + return notificationId; + } + + public void setNotificationId(Long notificationId) { + this.notificationId = notificationId; + } + + public String getIsForOnlineUsers() { + return isForOnlineUsers; + } + + public void setIsForOnlineUsers(String isForOnlineUsers) { + this.isForOnlineUsers = isForOnlineUsers; + } + + public String getIsForAllRoles() { + return isForAllRoles; + } + + public void setIsForAllRoles(String isForAllRoles) { + this.isForAllRoles = isForAllRoles; + } + + public String getActiveYn() { + return activeYn; + } + + public void setActiveYn(String activeYn) { + this.activeYn = activeYn; + } + + public String getMsgHeader() { + return msgHeader; + } + + public void setMsgHeader(String msgHeader) { + this.msgHeader = msgHeader; + } + + public String getMsgDescription() { + return msgDescription; + } + + public void setMsgDescription(String msgDescription) { + this.msgDescription = msgDescription; + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } + + public Long getPriority() { + return priority; + } + + public void setPriority(Long priority) { + this.priority = priority; + } + + public Long getCreatorId() { + return creatorId; + } + + public void setCreatorId(Long creatorId) { + this.creatorId = creatorId; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } + + public Set<EpRoleNotificationItem> getRoles() { + return roles; + } + + public void setRoles(Set<EpRoleNotificationItem> roles) { + this.roles = roles; + } + + public List<Long> getRoleIds() { + return roleIds; + } + + public void setRoleIds(List<Long> roleIds) { + this.roleIds = roleIds; + } + + public String getMsgSource() { + return msgSource; + } + + public void setMsgSource(String msgSource) { + this.msgSource = msgSource; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((activeYn == null) ? 0 : activeYn.hashCode()); + result = prime * result + ((createdDate == null) ? 0 : createdDate.hashCode()); + result = prime * result + ((creatorId == null) ? 0 : creatorId.hashCode()); + result = prime * result + ((endTime == null) ? 0 : endTime.hashCode()); + result = prime * result + ((isForAllRoles == null) ? 0 : isForAllRoles.hashCode()); + result = prime * result + ((isForOnlineUsers == null) ? 0 : isForOnlineUsers.hashCode()); + result = prime * result + ((msgDescription == null) ? 0 : msgDescription.hashCode()); + result = prime * result + ((msgHeader == null) ? 0 : msgHeader.hashCode()); + result = prime * result + ((msgSource == null) ? 0 : msgSource.hashCode()); + result = prime * result + ((notificationId == null) ? 0 : notificationId.hashCode()); + result = prime * result + ((priority == null) ? 0 : priority.hashCode()); + result = prime * result + ((roleIds == null) ? 0 : roleIds.hashCode()); + result = prime * result + ((roles == null) ? 0 : roles.hashCode()); + result = prime * result + ((startTime == null) ? 0 : startTime.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + EpNotificationItem other = (EpNotificationItem) obj; + if (activeYn == null) { + if (other.activeYn != null) + return false; + } else if (!activeYn.equals(other.activeYn)) + return false; + if (createdDate == null) { + if (other.createdDate != null) + return false; + } else if (!createdDate.equals(other.createdDate)) + return false; + if (creatorId == null) { + if (other.creatorId != null) + return false; + } else if (!creatorId.equals(other.creatorId)) + return false; + if (endTime == null) { + if (other.endTime != null) + return false; + } else if (!endTime.equals(other.endTime)) + return false; + if (isForAllRoles == null) { + if (other.isForAllRoles != null) + return false; + } else if (!isForAllRoles.equals(other.isForAllRoles)) + return false; + if (isForOnlineUsers == null) { + if (other.isForOnlineUsers != null) + return false; + } else if (!isForOnlineUsers.equals(other.isForOnlineUsers)) + return false; + if (msgDescription == null) { + if (other.msgDescription != null) + return false; + } else if (!msgDescription.equals(other.msgDescription)) + return false; + if (msgHeader == null) { + if (other.msgHeader != null) + return false; + } else if (!msgHeader.equals(other.msgHeader)) + return false; + if (msgSource == null) { + if (other.msgSource != null) + return false; + } else if (!msgSource.equals(other.msgSource)) + return false; + if (notificationId == null) { + if (other.notificationId != null) + return false; + } else if (!notificationId.equals(other.notificationId)) + return false; + if (priority == null) { + if (other.priority != null) + return false; + } else if (!priority.equals(other.priority)) + return false; + if (roleIds == null) { + if (other.roleIds != null) + return false; + } else if (!roleIds.equals(other.roleIds)) + return false; + if (roles == null) { + if (other.roles != null) + return false; + } else if (!roles.equals(other.roles)) + return false; + if (startTime == null) { + if (other.startTime != null) + return false; + } else if (!startTime.equals(other.startTime)) + return false; + return true; + } + + @Override + public String toString() { + return "EpNotificationItem [notificationId=" + notificationId + ", isForOnlineUsers=" + isForOnlineUsers + + ", isForAllRoles=" + isForAllRoles + ", activeYn=" + activeYn + ", msgHeader=" + msgHeader + + ", msgDescription=" + msgDescription + ", msgSource=" + msgSource + ", startTime=" + startTime + + ", endTime=" + endTime + ", priority=" + priority + ", creatorId=" + creatorId + ", createdDate=" + + createdDate + ", roles=" + roles + ", roleIds=" + roleIds + "]"; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItemExtVO.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItemExtVO.java index 4a3dc80d..c8c466ee 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItemExtVO.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItemExtVO.java @@ -1,119 +1,119 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.util.Date;
-
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-@JsonInclude(JsonInclude.Include.NON_NULL)
-public class EpNotificationItemExtVO {
-
- private Character activeYn;
-
- private String msgHeader;
-
- private String msgDescription;
-
- private Date startTime;
-
- private Date endTime;
-
- private Integer priority;
-
- private Integer creatorId;
-
- private Date createdDate;
-
- private String loginId;
-
- public Character getActiveYn() {
- return activeYn;
- }
-
- public void setActiveYn(Character activeYn) {
- this.activeYn = activeYn;
- }
-
- public String getMsgHeader() {
- return msgHeader;
- }
-
- public void setMsgHeader(String msgHeader) {
- this.msgHeader = msgHeader;
- }
-
- public String getMsgDescription() {
- return msgDescription;
- }
-
- public void setMsgDescription(String msgDescription) {
- this.msgDescription = msgDescription;
- }
-
- public Date getStartTime() {
- return startTime;
- }
-
- public void setStartTime(Date startTime) {
- this.startTime = startTime;
- }
-
- public Date getEndTime() {
- return endTime;
- }
-
- public void setEndTime(Date endTime) {
- this.endTime = endTime;
- }
-
- public Integer getPriority() {
- return priority;
- }
-
- public void setPriority(Integer priority) {
- this.priority = priority;
- }
-
- public Integer getCreatorId() {
- return creatorId;
- }
-
- public void setCreatorId(Integer creatorId) {
- this.creatorId = creatorId;
- }
-
- public Date getCreatedDate() {
- return createdDate;
- }
-
- public void setCreatedDate(Date createdDate) {
- this.createdDate = createdDate;
- }
-
- public String getLoginId() {
- return loginId;
- }
-
- public void setLoginId(String loginId) {
- this.loginId = loginId;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.util.Date; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EpNotificationItemExtVO { + + private Character activeYn; + + private String msgHeader; + + private String msgDescription; + + private Date startTime; + + private Date endTime; + + private Integer priority; + + private Integer creatorId; + + private Date createdDate; + + private String loginId; + + public Character getActiveYn() { + return activeYn; + } + + public void setActiveYn(Character activeYn) { + this.activeYn = activeYn; + } + + public String getMsgHeader() { + return msgHeader; + } + + public void setMsgHeader(String msgHeader) { + this.msgHeader = msgHeader; + } + + public String getMsgDescription() { + return msgDescription; + } + + public void setMsgDescription(String msgDescription) { + this.msgDescription = msgDescription; + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } + + public Integer getPriority() { + return priority; + } + + public void setPriority(Integer priority) { + this.priority = priority; + } + + public Integer getCreatorId() { + return creatorId; + } + + public void setCreatorId(Integer creatorId) { + this.creatorId = creatorId; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getLoginId() { + return loginId; + } + + public void setLoginId(String loginId) { + this.loginId = loginId; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItemVO.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItemVO.java index d22a4b79..3cb0f3a6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItemVO.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItemVO.java @@ -1,191 +1,191 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.util.Date;
-
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-/**
- * This is to handle notifications in user notifications and in notification history
- */
-
-/**
- * POJO that models a single notification with the org user ID (not integer
- * user_id).
- */
-@Entity
-public class EpNotificationItemVO extends DomainVo {
-
- private static final long serialVersionUID = 9095479701352339201L;
-
- @Id
- private Integer notificationId;
-
- private Character isForOnlineUsers;
-
- private Character isForAllRoles;
-
- private Character activeYn;
-
- private String msgHeader;
-
- private String msgDescription;
-
- private String msgSource;
-
- private Date startTime;
-
- private Date endTime;
-
- private Integer priority;
-
- private Integer creatorId;
-
- private Date createdDate;
-
- private String loginId;
-
- /**
- * Answers whether the notification is expired.
- *
- * @return true if the end time is past the current time, else false.
- */
- public boolean isExpired() {
- boolean result = false;
- if (endTime != null) {
- int expired = endTime.compareTo(new Date());
- result = (expired == -1) ? true : false;
- }
- return result;
- }
-
- public String getLoginId() {
- return loginId;
- }
-
- public void setLoginId(String loginId) {
- this.loginId = loginId;
- }
-
- public Integer getNotificationId() {
- return notificationId;
- }
-
- public void setNotificationId(Integer notificationId) {
- this.notificationId = notificationId;
- }
-
- public Character getIsForOnlineUsers() {
- return isForOnlineUsers;
- }
-
- public void setIsForOnlineUsers(Character isForOnlineUsers) {
- this.isForOnlineUsers = isForOnlineUsers;
- }
-
- public Character getIsForAllRoles() {
- return isForAllRoles;
- }
-
- public void setIsForAllRoles(Character isForAllRoles) {
- this.isForAllRoles = isForAllRoles;
- }
-
- public Character getActiveYn() {
- return activeYn;
- }
-
- public void setActiveYn(Character activeYn) {
- this.activeYn = activeYn;
- }
-
- public String getMsgHeader() {
- return msgHeader;
- }
-
- public void setMsgHeader(String msgHeader) {
- this.msgHeader = msgHeader;
- }
-
- public String getMsgDescription() {
- return msgDescription;
- }
-
- public void setMsgDescription(String msgDescription) {
- this.msgDescription = msgDescription;
- }
-
- public Date getStartTime() {
- return startTime;
- }
-
- public void setStartTime(Date startTime) {
- this.startTime = startTime;
- }
-
- public Date getEndTime() {
- return endTime;
- }
-
- public void setEndTime(Date endTime) {
- this.endTime = endTime;
- }
-
- public Integer getPriority() {
- return priority;
- }
-
- public void setPriority(Integer priority) {
- this.priority = priority;
- }
-
- public Integer getCreatorId() {
- return creatorId;
- }
-
- public void setCreatorId(Integer creatorId) {
- this.creatorId = creatorId;
- }
-
- public Date getCreatedDate() {
- return createdDate;
- }
-
- public void setCreatedDate(Date createdDate) {
- this.createdDate = createdDate;
- }
-
- public static long getSerialversionuid() {
- return serialVersionUID;
- }
-
-
- public String getMsgSource() {
- return msgSource;
- }
-
- public void setMsgSource(String msgSource) {
- this.msgSource = msgSource;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +/** + * This is to handle notifications in user notifications and in notification history + */ + +/** + * POJO that models a single notification with the org user ID (not integer + * user_id). + */ +@Entity +public class EpNotificationItemVO extends DomainVo { + + private static final long serialVersionUID = 9095479701352339201L; + + @Id + private Integer notificationId; + + private Character isForOnlineUsers; + + private Character isForAllRoles; + + private Character activeYn; + + private String msgHeader; + + private String msgDescription; + + private String msgSource; + + private Date startTime; + + private Date endTime; + + private Integer priority; + + private Integer creatorId; + + private Date createdDate; + + private String loginId; + + /** + * Answers whether the notification is expired. + * + * @return true if the end time is past the current time, else false. + */ + public boolean isExpired() { + boolean result = false; + if (endTime != null) { + int expired = endTime.compareTo(new Date()); + result = (expired == -1) ? true : false; + } + return result; + } + + public String getLoginId() { + return loginId; + } + + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + public Integer getNotificationId() { + return notificationId; + } + + public void setNotificationId(Integer notificationId) { + this.notificationId = notificationId; + } + + public Character getIsForOnlineUsers() { + return isForOnlineUsers; + } + + public void setIsForOnlineUsers(Character isForOnlineUsers) { + this.isForOnlineUsers = isForOnlineUsers; + } + + public Character getIsForAllRoles() { + return isForAllRoles; + } + + public void setIsForAllRoles(Character isForAllRoles) { + this.isForAllRoles = isForAllRoles; + } + + public Character getActiveYn() { + return activeYn; + } + + public void setActiveYn(Character activeYn) { + this.activeYn = activeYn; + } + + public String getMsgHeader() { + return msgHeader; + } + + public void setMsgHeader(String msgHeader) { + this.msgHeader = msgHeader; + } + + public String getMsgDescription() { + return msgDescription; + } + + public void setMsgDescription(String msgDescription) { + this.msgDescription = msgDescription; + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + public Date getEndTime() { + return endTime; + } + + public void setEndTime(Date endTime) { + this.endTime = endTime; + } + + public Integer getPriority() { + return priority; + } + + public void setPriority(Integer priority) { + this.priority = priority; + } + + public Integer getCreatorId() { + return creatorId; + } + + public void setCreatorId(Integer creatorId) { + this.creatorId = creatorId; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } + + + public String getMsgSource() { + return msgSource; + } + + public void setMsgSource(String msgSource) { + this.msgSource = msgSource; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpRoleNotificationItem.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpRoleNotificationItem.java index 66840ed7..26cf5484 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpRoleNotificationItem.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpRoleNotificationItem.java @@ -1,90 +1,90 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-
-@Entity
-@Table(name="ep_role_notification")
-public class EpRoleNotificationItem extends DomainVo {
- public EpRoleNotificationItem(){};
-
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- @Column(name = "ID")
- public Long id;
-
- @Column(name = "notification_ID")
- public Long notificationId;
-
- @Column(name = "role_ID")
- public Integer roleId;
-
- @Column(name = "recv_user_id")
- public Integer RecvUserId;
-
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Long getNotificationId() {
- return notificationId;
- }
-
- public void setNotificationId(Long notificationId) {
- this.notificationId = notificationId;
- }
-
- public Integer getRoleId() {
- return roleId;
- }
-
- public void setRoleId(Integer roleId) {
- this.roleId = roleId;
- }
-
- public static long getSerialversionuid() {
- return serialVersionUID;
- }
-
- public Integer getRecvUserId() {
- return RecvUserId;
- }
-
- public void setRecvUserId(Integer recvUserId) {
- RecvUserId = recvUserId;
- }
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +@Entity +@Table(name="ep_role_notification") +public class EpRoleNotificationItem extends DomainVo { + public EpRoleNotificationItem(){}; + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name = "ID") + public Long id; + + @Column(name = "notification_ID") + public Long notificationId; + + @Column(name = "role_ID") + public Integer roleId; + + @Column(name = "recv_user_id") + public Integer RecvUserId; + + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getNotificationId() { + return notificationId; + } + + public void setNotificationId(Long notificationId) { + this.notificationId = notificationId; + } + + public Integer getRoleId() { + return roleId; + } + + public void setRoleId(Integer roleId) { + this.roleId = roleId; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } + + public Integer getRecvUserId() { + return RecvUserId; + } + + public void setRecvUserId(Integer recvUserId) { + RecvUserId = recvUserId; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EventWidget.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EventWidget.java index 569dc138..4922b03e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EventWidget.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EventWidget.java @@ -1,138 +1,138 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-/*package org.openecomp.portalapp.portal.transport;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-import org.openecomp.portalsdk.core.domain.support.DomainVo;
-import com.fasterxml.jackson.annotation.JsonInclude;
-
-*//**
- * This is to handle portal admins
- * @author aw3218
- *//*
-@Entity
-@Table(name="fn_event_widget_data")
-@JsonInclude(JsonInclude.Include.NON_NULL)
-public class EventWidget extends DomainVo{
-
- *//**
- *
- *//*
- private static final long serialVersionUID = -2784849102886421352L;
-
-
- @Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- @Column(name = "id")
- private Long id;
-
- @Column(name = "category")
- private String category;
-
- @Column(name = "title")
- private String title;
-
- @Column(name = "href")
- private String href;
-
- @Column(name = "content")
- private String content;
-
- @Column(name = "month_val")
- private String mon;
-
- @Column(name = "day_val")
- private Integer day;
-
- @Column(name = "year_val")
- private Integer year;
-
- @Column(name = "sort_order")
- private Integer sortOrder;
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getHref() {
- return href;
- }
-
- public void setHref(String href) {
- this.href = href;
- }
-
- public String getContent() {
- return content;
- }
-
- public void setContent(String content) {
- this.content = content;
- }
-
- public String getMon() {
- return mon;
- }
-
- public void setMonth(String mon) {
- this.mon = mon;
- }
-
- public Integer getDay() {
- return day;
- }
-
- public void setDay(Integer day) {
- this.day = day;
- }
-
- public Integer getYear() {
- return year;
- }
-
- public void setYear(Integer year) {
- this.year = year;
- }
-
- public Integer getSortOrder() {
- return sortOrder;
- }
-
- public String getCategory() {
- return category;
- }
-
- public void setCategory(String category) {
- this.category = category;
- }
-
-
-}
-*/
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +/*package org.openecomp.portalapp.portal.transport; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; +import com.fasterxml.jackson.annotation.JsonInclude; + +*//** + * This is to handle portal admins + * @author aw3218 + *//* +@Entity +@Table(name="fn_event_widget_data") +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EventWidget extends DomainVo{ + + *//** + * + *//* + private static final long serialVersionUID = -2784849102886421352L; + + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + @Column(name = "id") + private Long id; + + @Column(name = "category") + private String category; + + @Column(name = "title") + private String title; + + @Column(name = "href") + private String href; + + @Column(name = "content") + private String content; + + @Column(name = "month_val") + private String mon; + + @Column(name = "day_val") + private Integer day; + + @Column(name = "year_val") + private Integer year; + + @Column(name = "sort_order") + private Integer sortOrder; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getHref() { + return href; + } + + public void setHref(String href) { + this.href = href; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public String getMon() { + return mon; + } + + public void setMonth(String mon) { + this.mon = mon; + } + + public Integer getDay() { + return day; + } + + public void setDay(Integer day) { + this.day = day; + } + + public Integer getYear() { + return year; + } + + public void setYear(Integer year) { + this.year = year; + } + + public Integer getSortOrder() { + return sortOrder; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + +} +*/ diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EventWidgetMeta.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EventWidgetMeta.java index 2182d7b3..39488a21 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EventWidgetMeta.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EventWidgetMeta.java @@ -1,51 +1,51 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-/*package org.openecomp.portalapp.portal.transport;
-
-import java.util.List;
-
-public class EventWidgetMeta {
-
- private String category;
- private List<EventWidget> items;
-
- public EventWidgetMeta(){
-
- }
-
- public EventWidgetMeta(String category, List<EventWidget> items){
- this.category = category;
- this.items = items;
- }
-
- public String getCategory() {
- return category;
- }
- public void setCategory(String category) {
- this.category = category;
- }
- public List<EventWidget> getItems() {
- return items;
- }
- public void setItems(List<EventWidget> items) {
- this.items = items;
- }
-}
-*/
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +/*package org.openecomp.portalapp.portal.transport; + +import java.util.List; + +public class EventWidgetMeta { + + private String category; + private List<EventWidget> items; + + public EventWidgetMeta(){ + + } + + public EventWidgetMeta(String category, List<EventWidget> items){ + this.category = category; + this.items = items; + } + + public String getCategory() { + return category; + } + public void setCategory(String category) { + this.category = category; + } + public List<EventWidget> getItems() { + return items; + } + public void setItems(List<EventWidget> items) { + this.items = items; + } +} +*/ diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalRequestFieldsValidator.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalRequestFieldsValidator.java new file mode 100644 index 00000000..d5122ea5 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalRequestFieldsValidator.java @@ -0,0 +1,28 @@ +package org.openecomp.portalapp.portal.transport; + +public class ExternalRequestFieldsValidator { + + private boolean result; + private String detailMessage; + + public ExternalRequestFieldsValidator(boolean result, String detailMessage) { + super(); + this.result = result; + this.detailMessage = detailMessage; + } + public boolean isResult() { + return result; + } + public void setResult(boolean result) { + this.result = result; + } + public String getDetailMessage() { + return detailMessage; + } + public void setDetailMessage(String detailMessage) { + this.detailMessage = detailMessage; + } + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItem.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItem.java index d90dfc1e..606cd67e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItem.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItem.java @@ -1,45 +1,45 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-
-/**
- * This is to handle functional menu favorites
- */
-@Entity
-@Table(name="fn_menu_favorites")
-public class FavoritesFunctionalMenuItem implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @Column(name = "user_id")
- public Long userId;
-
- @Id
- @Column(name = "menu_id")
- public Long menuId;
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + + +/** + * This is to handle functional menu favorites + */ +@Entity +@Table(name="fn_menu_favorites") +public class FavoritesFunctionalMenuItem implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @Column(name = "user_id") + public Long userId; + + @Id + @Column(name = "menu_id") + public Long menuId; +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItemJson.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItemJson.java index e469e0f9..7826e6c7 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItemJson.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItemJson.java @@ -1,57 +1,57 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Table;
-import javax.persistence.Transient;
-
-
-
-/**
- * This is to handle functional menu favorites
- */
-@Entity
-@Table(name="fn_menu_favorites")
-public class FavoritesFunctionalMenuItemJson implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- @Id
- @Column(name = "user_id")
- public Long userId;
-
- @Id
- @Column(name = "menu_id")
- public Long menuId;
-
- @Column(name = "text")
- public String text;
-
- @Column(name = "url")
- public String url;
-
- @Transient
- public Boolean restrictedApp;
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Transient; + + + +/** + * This is to handle functional menu favorites + */ +@Entity +@Table(name="fn_menu_favorites") +public class FavoritesFunctionalMenuItemJson implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @Column(name = "user_id") + public Long userId; + + @Id + @Column(name = "menu_id") + public Long menuId; + + @Column(name = "text") + public String text; + + @Column(name = "url") + public String url; + + @Transient + public Boolean restrictedApp; +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FieldsValidator.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FieldsValidator.java index ab51b7b1..fee83b2f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FieldsValidator.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FieldsValidator.java @@ -1,125 +1,125 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.http.HttpServletResponse;
-
-public class FieldsValidator {
-
- public Long httpStatusCode = new Long(HttpServletResponse.SC_OK);
-
- public Long errorCode;
-
- public class FieldName {
-
- public String name;
-
- public FieldName(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- }
-
-
- public List<FieldName> fields = new ArrayList<FieldName>();
-
- public void addProblematicFieldName(String name) {
- fields.add(new FieldName(name));
- }
-
- public Long getHttpStatusCode() {
- return httpStatusCode;
- }
-
- public void setHttpStatusCode(Long httpStatusCode) {
- this.httpStatusCode = httpStatusCode;
- }
-
- public Long getErrorCode() {
- return errorCode;
- }
-
- public void setErrorCode(Long errorCode) {
- this.errorCode = errorCode;
- }
-
- public List<FieldName> getFields() {
- return fields;
- }
-
- public void setFields(List<FieldName> fields) {
- this.fields = fields;
- }
-
- @Override
- public String toString() {
- return "FieldsValidator [httpStatusCode=" + httpStatusCode + ", errorCode=" + errorCode + ", fields=" + fields
- + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((errorCode == null) ? 0 : errorCode.hashCode());
- result = prime * result + ((fields == null) ? 0 : fields.hashCode());
- result = prime * result + ((httpStatusCode == null) ? 0 : httpStatusCode.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- FieldsValidator other = (FieldsValidator) obj;
- if (errorCode == null) {
- if (other.errorCode != null)
- return false;
- } else if (!errorCode.equals(other.errorCode))
- return false;
- if (fields == null) {
- if (other.fields != null)
- return false;
- } else if (!fields.equals(other.fields))
- return false;
- if (httpStatusCode == null) {
- if (other.httpStatusCode != null)
- return false;
- } else if (!httpStatusCode.equals(other.httpStatusCode))
- return false;
- return true;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletResponse; + +public class FieldsValidator { + + public Long httpStatusCode = new Long(HttpServletResponse.SC_OK); + + public Long errorCode; + + public class FieldName { + + public String name; + + public FieldName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + } + + + public List<FieldName> fields = new ArrayList<FieldName>(); + + public void addProblematicFieldName(String name) { + fields.add(new FieldName(name)); + } + + public Long getHttpStatusCode() { + return httpStatusCode; + } + + public void setHttpStatusCode(Long httpStatusCode) { + this.httpStatusCode = httpStatusCode; + } + + public Long getErrorCode() { + return errorCode; + } + + public void setErrorCode(Long errorCode) { + this.errorCode = errorCode; + } + + public List<FieldName> getFields() { + return fields; + } + + public void setFields(List<FieldName> fields) { + this.fields = fields; + } + + @Override + public String toString() { + return "FieldsValidator [httpStatusCode=" + httpStatusCode + ", errorCode=" + errorCode + ", fields=" + fields + + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((errorCode == null) ? 0 : errorCode.hashCode()); + result = prime * result + ((fields == null) ? 0 : fields.hashCode()); + result = prime * result + ((httpStatusCode == null) ? 0 : httpStatusCode.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + FieldsValidator other = (FieldsValidator) obj; + if (errorCode == null) { + if (other.errorCode != null) + return false; + } else if (!errorCode.equals(other.errorCode)) + return false; + if (fields == null) { + if (other.fields != null) + return false; + } else if (!fields.equals(other.fields)) + return false; + if (httpStatusCode == null) { + if (other.httpStatusCode != null) + return false; + } else if (!httpStatusCode.equals(other.httpStatusCode)) + return false; + return true; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItem.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItem.java index 707b08bc..93d53d04 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItem.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItem.java @@ -1,100 +1,100 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.io.Serializable;
-import java.util.List;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
-import javax.persistence.Transient;
-
-@Entity
-@Table(name="fn_menu_functional")
-public class FunctionalMenuItem implements Serializable {
- public FunctionalMenuItem(){};
-
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- @Column(name = "MENU_ID")
- public Long menuId;
-
- @Column(name = "COLUMN_NUM")
- public Integer column;
-
- @Column(name = "TEXT")
- public String text;
-
- @Column(name = "PARENT_MENU_ID")
- public Integer parentMenuId;
-
- @Column(name = "URL")
- public String url;
-
- @Column(name="ACTIVE_YN")
- public String active_yn;
-
- @Transient
- public Integer appid;
-
- public List<Integer> getRoles() {
- return roles;
- }
-
- public void setRoles(List<Integer> roles) {
- this.roles = roles;
- }
-
- @Transient
- private List<Integer> roles;
-
- @Transient
- public Boolean restrictedApp;
-
- public void normalize() {
- if (this.column == null)
- this.column = new Integer(1);
- this.text = (this.text == null) ? "" : this.text.trim();
- if (this.parentMenuId == null)
- this.parentMenuId = new Integer(-1);
- this.url = (this.url == null) ? "" : this.url.trim();
- }
-
- @Override
- public String toString() {
- return "FunctionalMenuItem [menuId=" + menuId + ", column=" + column + ", text=" + text + ", parentMenuId="
- + parentMenuId + ", url=" + url + ", active_yn=" + active_yn + ", appid=" + appid + ", roles=" + roles
- + ", restrictedApp=" + restrictedApp + "]";
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public void setRestrictedApp(Boolean restrictedApp) {
- this.restrictedApp = restrictedApp;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Transient; + +@Entity +@Table(name="fn_menu_functional") +public class FunctionalMenuItem implements Serializable { + public FunctionalMenuItem(){}; + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name = "MENU_ID") + public Long menuId; + + @Column(name = "COLUMN_NUM") + public Integer column; + + @Column(name = "TEXT") + public String text; + + @Column(name = "PARENT_MENU_ID") + public Integer parentMenuId; + + @Column(name = "URL") + public String url; + + @Column(name="ACTIVE_YN") + public String active_yn; + + @Transient + public Integer appid; + + public List<Integer> getRoles() { + return roles; + } + + public void setRoles(List<Integer> roles) { + this.roles = roles; + } + + @Transient + private List<Integer> roles; + + @Transient + public Boolean restrictedApp; + + public void normalize() { + if (this.column == null) + this.column = new Integer(1); + this.text = (this.text == null) ? "" : this.text.trim(); + if (this.parentMenuId == null) + this.parentMenuId = new Integer(-1); + this.url = (this.url == null) ? "" : this.url.trim(); + } + + @Override + public String toString() { + return "FunctionalMenuItem [menuId=" + menuId + ", column=" + column + ", text=" + text + ", parentMenuId=" + + parentMenuId + ", url=" + url + ", active_yn=" + active_yn + ", appid=" + appid + ", roles=" + roles + + ", restrictedApp=" + restrictedApp + "]"; + } + + public void setUrl(String url) { + this.url = url; + } + + public void setRestrictedApp(Boolean restrictedApp) { + this.restrictedApp = restrictedApp; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItemWithRoles.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItemWithRoles.java index 8e33a5f7..e74f0844 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItemWithRoles.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItemWithRoles.java @@ -1,60 +1,60 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.io.Serializable;
-import java.util.List;
-
-// This type is used to read the Json in from the API call from the Front End
-public class FunctionalMenuItemWithRoles implements Serializable {
- private static final long serialVersionUID = 1L;
-
- public Long menuId;
-
- public Integer column;
-
- public String text;
-
- public Integer parentMenuId;
-
- public String url;
-
- public Integer appid;
-
- private List<Integer> roles;
-
- public List<Integer> getRoles() {
- return roles;
- }
-
- public void setRoles(List<Integer> roles) {
- this.roles = roles;
- }
-
- public void normalize() {
- if (this.column == null)
- this.column = new Integer(1);
- this.text = (this.text == null) ? "" : this.text.trim();
- if (this.parentMenuId == null)
- this.parentMenuId = new Integer(-1);
- this.url = (this.url == null) ? "" : this.url.trim();
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; +import java.util.List; + +// This type is used to read the Json in from the API call from the Front End +public class FunctionalMenuItemWithRoles implements Serializable { + private static final long serialVersionUID = 1L; + + public Long menuId; + + public Integer column; + + public String text; + + public Integer parentMenuId; + + public String url; + + public Integer appid; + + private List<Integer> roles; + + public List<Integer> getRoles() { + return roles; + } + + public void setRoles(List<Integer> roles) { + this.roles = roles; + } + + public void normalize() { + if (this.column == null) + this.column = new Integer(1); + this.text = (this.text == null) ? "" : this.text.trim(); + if (this.parentMenuId == null) + this.parentMenuId = new Integer(-1); + this.url = (this.url == null) ? "" : this.url.trim(); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuRole.java index 0033b62a..2c2124f0 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuRole.java @@ -1,115 +1,115 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-@Entity
-@Table(name="fn_menu_functional_roles")
-public class FunctionalMenuRole implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- @Column(name = "ID")
- public Integer id;
-
- @Column(name = "MENU_ID")
- public Long menuId;
-
- @Column(name = "APP_ID")
- public Integer appId;
-
- @Column(name = "ROLE_ID")
- public Integer roleId;
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public Long getMenuId() {
- return menuId;
- }
-
- public void setMenuId(Long menuId) {
- this.menuId = menuId;
- }
-
- public Integer getAppId() {
- return appId;
- }
-
- public void setAppId(Integer appId) {
- this.appId = appId;
- }
-
- public Integer getRoleId() {
- return roleId;
- }
-
- public void setRoleId(Integer roleId) {
- this.roleId = roleId;
- }
-
- @Override
- public String toString() {
- return "FunctionalMenuRole [id=" + id + ", menuId=" + menuId + ", appId=" + appId + ", roleId=" + roleId + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((appId == null) ? 0 : appId.hashCode());
- result = prime * result + ((id == null) ? 0 : id.hashCode());
- result = prime * result + ((menuId == null) ? 0 : menuId.hashCode());
- result = prime * result + ((roleId == null) ? 0 : roleId.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object o) {
-
- if (o == this) return true;
- if (!(o instanceof FunctionalMenuRole)) {
- return false;
- }
- FunctionalMenuRole functionalMenuRole = (FunctionalMenuRole) o;
- System.out.println("test");
- return id.equals(functionalMenuRole.getId()) &&
- menuId.equals(functionalMenuRole.menuId) &&
- appId.equals(functionalMenuRole.appId) &&
- roleId.equals(functionalMenuRole.roleId) ;
- }
-
-
-
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="fn_menu_functional_roles") +public class FunctionalMenuRole implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name = "ID") + public Integer id; + + @Column(name = "MENU_ID") + public Long menuId; + + @Column(name = "APP_ID") + public Integer appId; + + @Column(name = "ROLE_ID") + public Integer roleId; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Long getMenuId() { + return menuId; + } + + public void setMenuId(Long menuId) { + this.menuId = menuId; + } + + public Integer getAppId() { + return appId; + } + + public void setAppId(Integer appId) { + this.appId = appId; + } + + public Integer getRoleId() { + return roleId; + } + + public void setRoleId(Integer roleId) { + this.roleId = roleId; + } + + @Override + public String toString() { + return "FunctionalMenuRole [id=" + id + ", menuId=" + menuId + ", appId=" + appId + ", roleId=" + roleId + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((appId == null) ? 0 : appId.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((menuId == null) ? 0 : menuId.hashCode()); + result = prime * result + ((roleId == null) ? 0 : roleId.hashCode()); + return result; + } + + @Override + public boolean equals(Object o) { + + if (o == this) return true; + if (!(o instanceof FunctionalMenuRole)) { + return false; + } + FunctionalMenuRole functionalMenuRole = (FunctionalMenuRole) o; + System.out.println("test"); + return id.equals(functionalMenuRole.getId()) && + menuId.equals(functionalMenuRole.menuId) && + appId.equals(functionalMenuRole.appId) && + roleId.equals(functionalMenuRole.roleId) ; + } + + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/LocalRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/LocalRole.java index 06fd6aec..4ec22281 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/LocalRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/LocalRole.java @@ -1,42 +1,59 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-@Entity
-public class LocalRole implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @Id
- @Column(name = "ROLE_ID")
- public Integer roleId;
-
- @Column(name = "ROLE_NAME")
- public String rolename;
-
- public void normalize() {
- this.rolename = (this.rolename == null) ? "" : this.rolename.trim();
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class LocalRole implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @Column(name = "ROLE_ID") + public Integer roleId; + + @Column(name = "ROLE_NAME") + public String rolename; + + public void normalize() { + this.rolename = (this.rolename == null) ? "" : this.rolename.trim(); + } + + public Integer getRoleId() { + return roleId; + } + + public void setRoleId(Integer roleId) { + this.roleId = roleId; + } + + public String getRolename() { + return rolename; + } + + public void setRolename(String rolename) { + this.rolename = rolename; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java index 977269d2..a4198d1d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java @@ -1,99 +1,101 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-/**
- * Model of rows in the fn_app table; serialized as a message add or update an
- * on-boarded application.
- */
-public class OnboardingApp {
-
- public Long id;
-
- public String name;
-
- public String imageUrl;
-
- public String description;
-
- public String notes;
-
- public String url;
-
- public String alternateUrl;
-
- public String restUrl;
-
- public Boolean isOpen;
-
- public Boolean isEnabled;
-
- public Long motsId;
-
- public String myLoginsAppName;
-
- public String myLoginsAppOwner;
-
- public String username;
-
- public String appPassword;
-
- public String thumbnail;
-
- public String uebTopicName;
-
- public String uebKey;
-
- public String uebSecret;
-
- public Boolean restrictedApp;
-
- /**
- * Sets the name, myLoginsAppName, myLoginsAppOwner, username and
- * appPassword fields to the empty string OR trims leading/trailing space,
- * as appropriate.
- */
- public void normalize() {
- this.name = (this.name == null) ? "" : this.name.trim();
- this.myLoginsAppName = (this.myLoginsAppName == null) ? "" : this.myLoginsAppName.trim();
- this.myLoginsAppOwner = (this.myLoginsAppOwner == null) ? "" : this.myLoginsAppOwner.trim();
- this.username = (this.username == null) ? "" : this.username.trim();
- this.appPassword = (this.appPassword == null) ? "" : this.appPassword.trim();
- }
-
- public void setUebTopicName(String topicName) {
- this.uebTopicName = topicName;
- }
-
- public void setUebKey(String key) {
- this.uebKey = key;
- }
-
- public void setUebSecret(String secret) {
- this.uebSecret = secret;
- }
-
- // Hide the implementation of restricted and normal app from the front end.
- // The json sent and received will include restrictedApp but not appType.
-
- public void setRestrictedApp(Boolean restrictedApp) {
- this.restrictedApp = restrictedApp;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +/** + * Model of rows in the fn_app table; serialized as a message add or update an + * on-boarded application. + */ +public class OnboardingApp { + + public Long id; + + public String name; + + public String imageUrl; + + public String imageLink; + + public String description; + + public String notes; + + public String url; + + public String alternateUrl; + + public String restUrl; + + public Boolean isOpen; + + public Boolean isEnabled; + + public Long motsId; + + public String myLoginsAppName; + + public String myLoginsAppOwner; + + public String username; + + public String appPassword; + + public String thumbnail; + + public String uebTopicName; + + public String uebKey; + + public String uebSecret; + + public Boolean restrictedApp; + + /** + * Sets the name, myLoginsAppName, myLoginsAppOwner, username and + * appPassword fields to the empty string OR trims leading/trailing space, + * as appropriate. + */ + public void normalize() { + this.name = (this.name == null) ? "" : this.name.trim(); + this.myLoginsAppName = (this.myLoginsAppName == null) ? "" : this.myLoginsAppName.trim(); + this.myLoginsAppOwner = (this.myLoginsAppOwner == null) ? "" : this.myLoginsAppOwner.trim(); + this.username = (this.username == null) ? "" : this.username.trim(); + this.appPassword = (this.appPassword == null) ? "" : this.appPassword.trim(); + } + + public void setUebTopicName(String topicName) { + this.uebTopicName = topicName; + } + + public void setUebKey(String key) { + this.uebKey = key; + } + + public void setUebSecret(String secret) { + this.uebSecret = secret; + } + + // Hide the implementation of restricted and normal app from the front end. + // The json sent and received will include restrictedApp but not appType. + + public void setRestrictedApp(Boolean restrictedApp) { + this.restrictedApp = restrictedApp; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingWidget.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingWidget.java index 09471d7f..9c812994 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingWidget.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingWidget.java @@ -1,65 +1,65 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-@Entity
-public class OnboardingWidget implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- @Id
- @Column(name = "WIDGET_ID")
- public Long id;
-
- @Column(name = "WDG_NAME")
- public String name;
-
- @Column(name = "APP_ID")
- public Long appId;
-
- @Column(name = "APP_NAME")
- public String appName;
-
- @Column(name = "WDG_WIDTH")
- public Integer width;
-
- @Column(name = "WDG_HEIGHT")
- public Integer height;
-
- @Column(name = "WDG_URL")
- public String url;
-
- public void normalize() {
- this.name = (this.name == null) ? "" : this.name.trim();
- this.appName = (this.appName == null) ? "" : this.appName.trim();
- if (this.width == null)
- this.width = new Integer(0);
- if (this.height == null)
- this.height = new Integer(0);
- this.url = (this.url == null) ? "" : this.url.trim();
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class OnboardingWidget implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @Column(name = "WIDGET_ID") + public Long id; + + @Column(name = "WDG_NAME") + public String name; + + @Column(name = "APP_ID") + public Long appId; + + @Column(name = "APP_NAME") + public String appName; + + @Column(name = "WDG_WIDTH") + public Integer width; + + @Column(name = "WDG_HEIGHT") + public Integer height; + + @Column(name = "WDG_URL") + public String url; + + public void normalize() { + this.name = (this.name == null) ? "" : this.name.trim(); + this.appName = (this.appName == null) ? "" : this.appName.trim(); + if (this.width == null) + this.width = new Integer(0); + if (this.height == null) + this.height = new Integer(0); + this.url = (this.url == null) ? "" : this.url.trim(); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdmin.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdmin.java index 0481eb61..294b859d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdmin.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdmin.java @@ -1,53 +1,85 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-/**
- * This is to handle portal admins
- */
-@Entity
-@Table(name="fn_user")
-public class PortalAdmin implements Serializable{
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- @Column(name = "user_id")
- public Long userId;
-
- @Column(name = "login_id")
- public String loginId;
-
- @Column(name = "first_name")
- public String firstName;
-
- @Column(name = "last_name")
- public String lastName;
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +/** + * This is to handle portal admins + */ +@Entity +@Table(name = "fn_user") +public class PortalAdmin implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "user_id") + public Long userId; + + @Column(name = "login_id") + public String loginId; + + @Column(name = "first_name") + public String firstName; + + @Column(name = "last_name") + public String lastName; + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getLoginId() { + return loginId; + } + + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdminUserRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdminUserRole.java index 06229fc1..17306adc 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdminUserRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdminUserRole.java @@ -1,48 +1,48 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.io.Serializable;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Table;
-
-/**
- * This is to handle portal admins
- */
-@Entity
-@Table(name="fn_user_role")
-public class PortalAdminUserRole implements Serializable{
- private static final long serialVersionUID = 1L;
-
- @Id
- @Column(name = "user_id")
- public Long userId;
-
- @Id
- @Column(name = "role_id")
- public Long roleId;
-
- @Column(name = "app_id")
- public Long appId;
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +/** + * This is to handle portal admins + */ +@Entity +@Table(name="fn_user_role") +public class PortalAdminUserRole implements Serializable{ + private static final long serialVersionUID = 1L; + + @Id + @Column(name = "user_id") + public Long userId; + + @Id + @Column(name = "role_id") + public Long roleId; + + @Column(name = "app_id") + public Long appId; + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ProfileDetail.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ProfileDetail.java new file mode 100644 index 00000000..11c0bada --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ProfileDetail.java @@ -0,0 +1,60 @@ +package org.openecomp.portalapp.portal.transport; + +public class ProfileDetail { + + private String firstName; + private String lastName; + private String middleName; + private String email; + private String loginId; + private String loginPassword; + + public ProfileDetail(){} + public ProfileDetail(String firstName, String lastName, String middleName, String email, String loginId, String loginPassword) { + this.firstName = firstName; + this.lastName = lastName; + this.middleName = middleName; + this.email = email; + this.loginId = loginId; + this.loginPassword = loginPassword; + } + + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + public String getMiddleName() { + return middleName; + } + public void setMiddleName(String middleName) { + this.middleName = middleName; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + public String getLoginId() { + return loginId; + } + public void setLoginId(String loginId) { + this.loginId = loginId; + } + public String getLoginPassword() { + return loginPassword; + } + public void setLoginPassword(String loginPassword) { + this.loginPassword = loginPassword; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RemoteRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RemoteRole.java index 0f152772..8a2d6232 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RemoteRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RemoteRole.java @@ -1,44 +1,44 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-public class RemoteRole {
-
- private Long id;
- private String name;
-
- public Long getId() {
- return id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return "RemoteRole [id=" + id + ", name=" + name + "]";
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +public class RemoteRole { + + private Long id; + private String name; + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "RemoteRole [id=" + id + ", name=" + name + "]"; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RoleInAppForUser.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RoleInAppForUser.java index dad1c98b..27a34619 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RoleInAppForUser.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RoleInAppForUser.java @@ -1,105 +1,105 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-public class RoleInAppForUser {
-
-
- public RoleInAppForUser() {
- }
-
- public RoleInAppForUser(Long id, String name) {
- this.roleId = id;
- this.roleName = name;
- }
-
- public Long roleId;
-
- public String roleName;
-
- public Boolean isApplied;
-
- public Long getRoleId() {
- return roleId;
- }
-
- public void setRoleId(Long roleId) {
- this.roleId = roleId;
- }
-
- public String getRoleName() {
- return roleName;
- }
-
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
-
- public Boolean getIsApplied() {
- return isApplied;
- }
-
- public void setIsApplied(Boolean isApplied) {
- this.isApplied = isApplied;
- }
-
- @Override
- public String toString() {
- return "RoleInAppForUser [roleId=" + roleId + ", roleName=" + roleName + ", isApplied=" + isApplied + "]";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((isApplied == null) ? 0 : isApplied.hashCode());
- result = prime * result + ((roleId == null) ? 0 : roleId.hashCode());
- result = prime * result + ((roleName == null) ? 0 : roleName.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- RoleInAppForUser other = (RoleInAppForUser) obj;
- if (isApplied == null) {
- if (other.isApplied != null)
- return false;
- } else if (!isApplied.equals(other.isApplied))
- return false;
- if (roleId == null) {
- if (other.roleId != null)
- return false;
- } else if (!roleId.equals(other.roleId))
- return false;
- if (roleName == null) {
- if (other.roleName != null)
- return false;
- } else if (!roleName.equals(other.roleName))
- return false;
- return true;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +public class RoleInAppForUser { + + + public RoleInAppForUser() { + } + + public RoleInAppForUser(Long id, String name) { + this.roleId = id; + this.roleName = name; + } + + public Long roleId; + + public String roleName; + + public Boolean isApplied; + + public Long getRoleId() { + return roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + public Boolean getIsApplied() { + return isApplied; + } + + public void setIsApplied(Boolean isApplied) { + this.isApplied = isApplied; + } + + @Override + public String toString() { + return "RoleInAppForUser [roleId=" + roleId + ", roleName=" + roleName + ", isApplied=" + isApplied + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((isApplied == null) ? 0 : isApplied.hashCode()); + result = prime * result + ((roleId == null) ? 0 : roleId.hashCode()); + result = prime * result + ((roleName == null) ? 0 : roleName.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + RoleInAppForUser other = (RoleInAppForUser) obj; + if (isApplied == null) { + if (other.isApplied != null) + return false; + } else if (!isApplied.equals(other.isApplied)) + return false; + if (roleId == null) { + if (other.roleId != null) + return false; + } else if (!roleId.equals(other.roleId)) + return false; + if (roleName == null) { + if (other.roleName != null) + return false; + } else if (!roleName.equals(other.roleName)) + return false; + return true; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RolesInAppForUser.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RolesInAppForUser.java index 8720304d..2b3b451a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RolesInAppForUser.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RolesInAppForUser.java @@ -1,33 +1,33 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class RolesInAppForUser {
-
- public String orgUserId;
-
- public Long appId;
-
- public List<RoleInAppForUser> roles = new ArrayList<RoleInAppForUser>();
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +import java.util.ArrayList; +import java.util.List; + +public class RolesInAppForUser { + + public String orgUserId; + + public Long appId; + + public List<RoleInAppForUser> roles = new ArrayList<RoleInAppForUser>(); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/WidgetCatalogPersonalization.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/WidgetCatalogPersonalization.java index 5117e8f2..0674e446 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/WidgetCatalogPersonalization.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/WidgetCatalogPersonalization.java @@ -1,57 +1,57 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.transport;
-
-/**
- * Model for the object PUT to the controller when the user takes an action on
- * a widget in the catalog.
- */
-
-public class WidgetCatalogPersonalization {
-
- public Long widgetId;
- public Boolean select;
- // not needed as only 'SHOW' and 'HIDE' status_cd is expected from the micro service now
- //public Boolean pending;
-
- public Long getWidgetId() {
- return widgetId;
- }
-
- public void setWidgetId(Long widgetId) {
- this.widgetId = widgetId;
- }
-
- public Boolean getSelect() {
- return select;
- }
-
- public void setSelect(Boolean select) {
- this.select = select;
- }
-
- /*public Boolean getPending() {
- return pending;
- }
-
- public void setPending(Boolean pending) {
- this.pending = pending;
- }*/
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +/** + * Model for the object PUT to the controller when the user takes an action on + * a widget in the catalog. + */ + +public class WidgetCatalogPersonalization { + + public Long widgetId; + public Boolean select; + // not needed as only 'SHOW' and 'HIDE' status_cd is expected from the micro service now + //public Boolean pending; + + public Long getWidgetId() { + return widgetId; + } + + public void setWidgetId(Long widgetId) { + this.widgetId = widgetId; + } + + public Boolean getSelect() { + return select; + } + + public void setSelect(Boolean select) { + this.select = select; + } + + /*public Boolean getPending() { + return pending; + } + + public void setPending(Boolean pending) { + this.pending = pending; + }*/ +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java index 3c447e2a..34be46e3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java @@ -1,217 +1,217 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.ueb;
-
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.util.LinkedList;
-import java.util.List;
-
-import javax.annotation.PostConstruct;
-
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.EnableAspectJAutoProxy;
-import org.springframework.stereotype.Component;
-import org.springframework.transaction.annotation.Transactional;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
-import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
-import org.openecomp.portalsdk.core.onboarding.ueb.Helper;
-import org.openecomp.portalsdk.core.onboarding.ueb.Publisher;
-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.portalapp.portal.domain.EPApp;
-import org.openecomp.portalapp.portal.domain.EcompApp;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalapp.portal.service.EPAppService;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-
-@Component
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-public class EPUebHelper {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUebHelper.class);
-
- @Autowired
- EPAppService appsService;
-
-
- @Autowired
- private SessionFactory sessionFactory;
-
- @SuppressWarnings("unused")
- private Publisher epPublisher;
-
- public EPUebHelper() {
-
- }
- //
- // This should only be called by the ECOMP Portal App, other Apps have just one publisher and use appPublisher
- //
- @SuppressWarnings("unused")
- @EPMetricsLog
- public void refreshPublisherList()
- {
- Session localSession = null;
- boolean addedPublisher = false;
-
- try {
- localSession = sessionFactory.openSession();
-
- List<EcompApp> apps = appsService.getEcompAppAppsFullList();
- for (int i = 0; i < apps.size(); i++)
- {
- if ((apps.get(i).isEnabled()) &&
- (apps.get(i).getUebTopicName() != null) &&
- !(apps.get(i).getUebTopicName().toUpperCase().contains("ECOMP-PORTAL-INBOX")))
- {
- logger.debug(EELFLoggerDelegate.debugLogger, "UEBManager adding publisher for " + apps.get(i).getUebTopicName());
- UebManager.getInstance().addPublisher(apps.get(i).getUebTopicName());
- addedPublisher = true;
- }
- else if ((apps.get(i).getId() != 1) && // App may have been disabled, remove the publisher
- !(apps.get(i).isEnabled()))
- {
- if(apps.get(i).getUebTopicName()!=null){
- UebManager.getInstance().removePublisher(apps.get(i).getUebTopicName());
- }
- }
- }
- }
- catch (Exception e)
- {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebSystemError, e, "add/remove Publisher");
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while refreshing the publisher list", e);
- }
-
- //publisherList.print();
-
- if (addedPublisher == true) // Give publishers time to initialize
- {
- Helper.sleep(400);
- }
- }
-
- @PostConstruct
- @EPMetricsLog
- public void initUeb() {
- try {
- epPublisher = new Publisher(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
- PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
- PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e);
- String stackTrace = EcompPortalUtils.getStackTrace(e);
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while initializing the publisher. Details: " + stackTrace);
- }
-
- Thread thread = new Thread("EPUebManager: postConstructMethod - refreshPublisherList") {
- public void run(){
- refreshPublisherList();
- }
- };
- if (thread != null) {
- thread.start();
- }
- }
-
- @EPMetricsLog
- public void addPublisher(EPApp app) {
- // TODO Auto-generated method stub
- try {
- UebManager.getInstance().addPublisher(app.getUebTopicName());
- } catch (UebException e) {
- String stackTrace = EcompPortalUtils.getStackTrace(e);
- logger.error(EELFLoggerDelegate.errorLogger, "Exception while adding a publisher. Details: " + stackTrace);
- }
- }
-
- public boolean checkAvailability() {
-
- //
- // Test existence of topic at UEB url
- //
- // (ie http://uebsb91kcdc.it.att.com:3904/topics/ECOMP-PORTAL-INBOX)
- //
- boolean available = true;
- LinkedList<String> urlList = Helper.uebUrlList();
- if (!urlList.isEmpty()) {
- String url = "http://" + urlList.getFirst() + ":3904/topics/" + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME);
- if (!url.isEmpty()) {
- try {
- URL siteURL = new URL(url);
- HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection();
- connection.setRequestMethod("GET");
- connection.connect();
-
- int code = connection.getResponseCode();
- if (code == 200) {
- available = true;
- }
- else {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, url);
- available = false;
- logger.warn(EELFLoggerDelegate.errorLogger, "Warning! UEB topic existence check failed, topic = " + url );
- logger.debug(EELFLoggerDelegate.debugLogger, "Warning! UEB topic existence check failed, topic = " + url );
- }
- }
- catch (Exception e) {
- available = false;
- String stackTrace = EcompPortalUtils.getStackTrace(e);
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the UEB Healthcheck. Details: " + stackTrace);
- }
- }
- }
- return available;
- }
-
- public boolean MessageCanBeSentToTopic() {
-
- boolean sentMsgSuccessfully = false;
-
- UebMsg msg = new UebMsg();
- msg.putSourceTopicName(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
- msg.putPayload("Pinging topic for health check");
- msg.putMsgType(EPUebMsgTypes.UEB_MSG_TYPE_HEALTH_CHECK);
-
- try {
- // epPublisher.send(msg);
- sentMsgSuccessfully = true;
- }
- catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHealthCheckUebClusterError, e);
- sentMsgSuccessfully = false;
- logger.warn(EELFLoggerDelegate.errorLogger, "Warning! could not successfully publish a UEB msg to "
- + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME), e);
- }
-
- return sentMsgSuccessfully;
- }
-
-}
-
-
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ueb; + +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.LinkedList; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; +import org.openecomp.portalsdk.core.onboarding.ueb.Helper; +import org.openecomp.portalsdk.core.onboarding.ueb.Publisher; +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.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EcompApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.service.EPAppService; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; + +@Component +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +public class EPUebHelper { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUebHelper.class); + + @Autowired + EPAppService appsService; + + + @Autowired + private SessionFactory sessionFactory; + + @SuppressWarnings("unused") + private Publisher epPublisher; + + public EPUebHelper() { + + } + // + // This should only be called by the ECOMP Portal App, other Apps have just one publisher and use appPublisher + // + @SuppressWarnings("unused") + @EPMetricsLog + public void refreshPublisherList() + { + Session localSession = null; + boolean addedPublisher = false; + + try { + localSession = sessionFactory.openSession(); + + List<EcompApp> apps = appsService.getEcompAppAppsFullList(); + for (int i = 0; i < apps.size(); i++) + { + if ((apps.get(i).isEnabled()) && + (apps.get(i).getUebTopicName() != null) && + !(apps.get(i).getUebTopicName().toUpperCase().contains("ECOMP-PORTAL-INBOX"))) + { + logger.debug(EELFLoggerDelegate.debugLogger, "UEBManager adding publisher for " + apps.get(i).getUebTopicName()); + UebManager.getInstance().addPublisher(apps.get(i).getUebTopicName()); + addedPublisher = true; + } + else if ((apps.get(i).getId() != 1) && // App may have been disabled, remove the publisher + !(apps.get(i).isEnabled())) + { + if(apps.get(i).getUebTopicName()!=null){ + UebManager.getInstance().removePublisher(apps.get(i).getUebTopicName()); + } + } + } + } + catch (Exception e) + { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebSystemError, e, "add/remove Publisher"); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while refreshing the publisher list", e); + } + + //publisherList.print(); + + if (addedPublisher == true) // Give publishers time to initialize + { + Helper.sleep(400); + } + } + + @PostConstruct + @EPMetricsLog + public void initUeb() { + try { + epPublisher = new Publisher(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME)); + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e); + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while initializing the publisher. Details: " + stackTrace); + } + + Thread thread = new Thread("EPUebManager: postConstructMethod - refreshPublisherList") { + public void run(){ + refreshPublisherList(); + } + }; + if (thread != null) { + thread.start(); + } + } + + @EPMetricsLog + public void addPublisher(EPApp app) { + // TODO Auto-generated method stub + try { + UebManager.getInstance().addPublisher(app.getUebTopicName()); + } catch (UebException e) { + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception while adding a publisher. Details: " + stackTrace); + } + } + + public boolean checkAvailability() { + + // + // Test existence of topic at UEB url + // + // (ie http://uebsb91kcdc.it.att.com:3904/topics/ECOMP-PORTAL-INBOX) + // + boolean available = true; + LinkedList<String> urlList = Helper.uebUrlList(); + if (!urlList.isEmpty()) { + String url = "http://" + urlList.getFirst() + ":3904/topics/" + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME); + if (!url.isEmpty()) { + try { + URL siteURL = new URL(url); + HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection(); + connection.setRequestMethod("GET"); + connection.connect(); + + int code = connection.getResponseCode(); + if (code == 200) { + available = true; + } + else { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, url); + available = false; + logger.warn(EELFLoggerDelegate.errorLogger, "Warning! UEB topic existence check failed, topic = " + url ); + logger.debug(EELFLoggerDelegate.debugLogger, "Warning! UEB topic existence check failed, topic = " + url ); + } + } + catch (Exception e) { + available = false; + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the UEB Healthcheck. Details: " + stackTrace); + } + } + } + return available; + } + + public boolean MessageCanBeSentToTopic() { + + boolean sentMsgSuccessfully = false; + + UebMsg msg = new UebMsg(); + msg.putSourceTopicName(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME)); + msg.putPayload("Pinging topic for health check"); + msg.putMsgType(EPUebMsgTypes.UEB_MSG_TYPE_HEALTH_CHECK); + + try { + // epPublisher.send(msg); + sentMsgSuccessfully = true; + } + catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHealthCheckUebClusterError, e); + sentMsgSuccessfully = false; + logger.warn(EELFLoggerDelegate.errorLogger, "Warning! could not successfully publish a UEB msg to " + + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME), e); + } + + return sentMsgSuccessfully; + } + +} + + diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java index aef02545..d6eb9eb9 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java @@ -1,27 +1,27 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.ueb;
-
-import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes;
-
-public interface EPUebMsgTypes extends UebMsgTypes {
-
- public static final String UEB_MSG_TYPE_HEALTH_CHECK = "uebHealthCheckPing";
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ueb; + +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes; + +public interface EPUebMsgTypes extends UebMsgTypes { + + public static final String UEB_MSG_TYPE_HEALTH_CHECK = "uebHealthCheckPing"; +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/CustomLoggingFilter.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/CustomLoggingFilter.java index a43f5177..ac019d5f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/CustomLoggingFilter.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/CustomLoggingFilter.java @@ -1,54 +1,54 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.utils;
-
-import ch.qos.logback.classic.Level;
-import ch.qos.logback.classic.spi.ILoggingEvent;
-import ch.qos.logback.core.filter.Filter;
-import ch.qos.logback.core.spi.FilterReply;
-
-/**
- * Custom Filter class bind with logback.xml
- * configuration file to strip out certain log messages
- * coming out of special packages or classes.
- *
- */
-public class CustomLoggingFilter extends Filter<ILoggingEvent> {
-
- /**
- * Custom Filter is added to strip out the continuous U-EB logging messages
- * But make sure we log the ERROR & WARNING Level messages.
- */
- @Override
- public FilterReply decide(ILoggingEvent event) {
- try {
- if ((event.getLevel() != Level.ERROR || event.getLevel() != Level.WARN) &&
- (event.getThreadName().equalsIgnoreCase("UEBConsumerThread")) &&
- (event.getLoggerName().contains("org.openecomp.nsa") || event.getLoggerName().contains("org.apache.http"))
- ) {
- return FilterReply.DENY;
- } else {
- return FilterReply.NEUTRAL;
- }
- } catch(Exception e) {
- return FilterReply.NEUTRAL;
- }
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.utils; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.filter.Filter; +import ch.qos.logback.core.spi.FilterReply; + +/** + * Custom Filter class bind with logback.xml + * configuration file to strip out certain log messages + * coming out of special packages or classes. + * + */ +public class CustomLoggingFilter extends Filter<ILoggingEvent> { + + /** + * Custom Filter is added to strip out the continuous U-EB logging messages + * But make sure we log the ERROR & WARNING Level messages. + */ + @Override + public FilterReply decide(ILoggingEvent event) { + try { + if ((event.getLevel() != Level.ERROR || event.getLevel() != Level.WARN) && + (event.getThreadName().equalsIgnoreCase("UEBConsumerThread")) && + (event.getLoggerName().contains("org.openecomp.nsa") || event.getLoggerName().contains("org.apache.http")) + ) { + return FilterReply.DENY; + } else { + return FilterReply.NEUTRAL; + } + } catch(Exception e) { + return FilterReply.NEUTRAL; + } + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EPCommonSystemProperties.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EPCommonSystemProperties.java index 38b6608a..8ef4593f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EPCommonSystemProperties.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EPCommonSystemProperties.java @@ -61,4 +61,5 @@ public class EPCommonSystemProperties extends SystemProperties { public static final String AUTH_USER_SERVER = "auth_user_server"; public static final String EXTERNAL_ACCESS_ENABLE = "external_access_enable"; + }
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java index adf36b2b..48c2dbe8 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java @@ -1,331 +1,344 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.utils;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.hibernate.Session;
-import org.hibernate.Transaction;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
-import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.slf4j.MDC;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-public class EcompPortalUtils {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
-
- /**
- * @param orgUserId
- * @return true if orgUserId is not empty and contains only alphanumeric,
- * false otherwise
- */
- public static boolean legitimateUserId(String orgUserId) {
- return orgUserId.matches("^[a-zA-Z0-9]+$");
- }
-
- /**
- * Splits the string into a list of tokens using the specified regular
- * expression
- *
- * @param source
- * @param regex
- * @return List of tokens split from the source
- */
- public static List<String> parsingByRegularExpression(String source, String regex) {
- List<String> tokens = new ArrayList<String>();
- if (source != null && source.length() > 0) {
- String[] parsed = source.split(regex);
- for (String token : parsed) {
- if (token.length() > 0) {
- tokens.add(token);
- }
- }
- }
- return tokens;
- }
-
- /**
- * Builds a JSON object with error code and message information.
- *
- * @param errorCode
- * @param errorMessage
- * @return JSON object as a String
- */
- public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
- return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
- }
-
- /**
- * Builds a JSON object with the specified message
- *
- * @param message
- * @return JSON object as a String
- */
- public static String jsonMessageResponse(String message) {
- return String.format("{\"message\":\"%s\"}", message);
- }
-
- /**
- * Serializes the specified object as JSON and writes the result to the
- * debug log. If serialization fails, logs a message to the error logger.
- *
- * @param logger
- * Logger for the class where the object was built; the logger
- * carries the class name.
- * @param source
- * First portion of the log message
- * @param msg
- * Second portion of the log message
- * @param obj
- * Object to serialize as JSON
- */
- public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) {
- try {
- String objectAsJson = new ObjectMapper().writeValueAsString(obj);
- logger.debug(EELFLoggerDelegate.debugLogger,
- String.format("source= [%s]; %s [%s];", source, msg, objectAsJson));
- } catch (JsonProcessingException e) {
- logger.warn(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed to serialize", e);
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed", e);
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
- }
- }
-
- /**
- * Serializes the specified object as JSON and writes the result to the
- * debug log. If serialization fails, logs a message to the error logger.
- *
- * @param source
- * First portion of the log message
- * @param msg
- * Second portion of the log message
- * @param obj
- * Object to serialize as JSON
- */
- public static void logAndSerializeObject(String source, String msg, Object obj) {
- logAndSerializeObject(logger, source, msg, obj);
- }
-
- public static void rollbackTransaction(Transaction transaction, String errorMessage) {
- logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
- try {
- if (transaction != null) {
- transaction.rollback();
- }
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
- logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction",
- e);
- }
- }
-
- public static void closeLocalSession(Session localSession, String errorMessage) {
- logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
- try {
- if (localSession != null) {
- localSession.close();
- }
- } catch (Exception e) {
- EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
- logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e);
- }
- }
-
- // TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor.
- // It should be defined in SystemProperties.
- private static final String GLOBAL_LOGIN_URL = "global-login-url";
-
- /**
- * Set response status to Unauthorized if user == null and to Forbidden in
- * all (!) other cases. Logging is not performed if invocator == null
- *
- * @param user
- * @param response
- * @param invocator
- * - may be null
- */
- public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
- if (user == null) {
- String loginUrl = SystemProperties.getProperty(EPCommonSystemProperties.LOGIN_URL_NO_RET_VAL);
- response.setHeader(GLOBAL_LOGIN_URL, loginUrl);
- response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
- MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
- } else {
- response.setStatus(HttpServletResponse.SC_FORBIDDEN);
- MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
- }
- if (invocator != null) {
- logger.warn(EELFLoggerDelegate.errorLogger,
- invocator + ", permissions problem, response status = " + response.getStatus());
- }
- }
-
- public static int getExternalAppResponseCode() {
- String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
- int responseCodeInt = 0;
- try {
- if (responseCode != null && responseCode != "") {
- responseCodeInt = Integer.valueOf(responseCode);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred in getResponseCode(). Details: " + EcompPortalUtils.getStackTrace(e));
- }
- return responseCodeInt;
- }
-
- // This method might be just for testing purposes.
- public static void setExternalAppResponseCode(int responseCode) {
- try {
- String responseCodeString = String.valueOf(responseCode);
- MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, responseCodeString);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred in setResponseCode(). Details: " + EcompPortalUtils.getStackTrace(e));
- }
- }
-
- public static String getHTTPStatusString(int httpStatusCode) {
- String httpStatusString = "unknown_error";
- try {
- httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
- if (httpStatusString != null) {
- httpStatusString = httpStatusString.toLowerCase();
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred in getHTTPStatusString(). Details: " + EcompPortalUtils.getStackTrace(e));
- }
- return httpStatusString;
- }
-
- public static String getFEErrorString(Boolean internal, int responseCode) {
- // Return a String like the following:
- // "Internal Ecomp Error: 500 internal_server_error" or
- // "External App Error: 404 not_found"
- // TODO: create our own Ecomp error codes, starting with 1000 and up.
- String responseString = "";
- String internalExternalString = internal ? "Ecomp Error: " : "App Error: ";
- String httpStatusString = "unknown_error";
- try {
- if (responseCode < 1000) {
- httpStatusString = getHTTPStatusString(responseCode);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
- "Exception occurred in getFEErrorString(). Details: " + EcompPortalUtils.getStackTrace(e));
- }
- responseString = internalExternalString + responseCode + " " + httpStatusString;
- return responseString;
- }
-
- public static boolean isProductionBuild() {
- boolean productionBuild = true;
- String epVersion = EcompVersion.buildNumber;
- if (epVersion != null) {
- int buildNum = epVersion.lastIndexOf('.');
- if (buildNum > 0) {
- int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1));
- if (buildNumber < 3000) // Production versions are 3000+, (ie
- // 1.0.3003)
- {
- productionBuild = false;
- }
- }
- }
- return productionBuild;
- }
-
- private static final Object stackTraceLock = new Object();
-
- public static String getStackTrace(Throwable t) {
- synchronized (stackTraceLock) {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- t.printStackTrace(pw);
- return sw.toString();
- }
- }
-
- public static String getMyIpAdddress() {
- InetAddress ip;
- String localIp;
- try {
- ip = InetAddress.getLocalHost();
- localIp = ip.getHostAddress();
- } catch (UnknownHostException e) {
- localIp = "unknown";
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- }
- return localIp;
- }
-
- public static String getMyHostName() {
- InetAddress ip;
- String hostName;
- try {
- ip = InetAddress.getLocalHost();
- hostName = ip.getHostName();
- } catch (UnknownHostException e) {
- hostName = "unknown";
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- }
- return hostName;
- }
-
- /* return a default property if the expected one is not available */
- public static String getPropertyOrDefault(String property, String defaultValue) {
- return ((null == SystemProperties.getProperty(property) || SystemProperties.getProperty(property).equals(""))
- ? defaultValue : SystemProperties.getProperty(property));
- }
-
- public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) {
- if (beginDateTime != null && endDateTime != null) {
- try {
- SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
-
- Date beginDate = ecompLogDateFormat.parse(beginDateTime);
- Date endDate = ecompLogDateFormat.parse(endDateTime);
- String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
- MDC.put(SystemProperties.MDC_TIMER, timeDifference);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- }
- }
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.utils; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class EcompPortalUtils { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class); + + /** + * @param orgUserId + * @return true if orgUserId is not empty and contains only alphanumeric, + * false otherwise + */ + public static boolean legitimateUserId(String orgUserId) { + return orgUserId.matches("^[a-zA-Z0-9]+$"); + } + + /** + * Splits the string into a list of tokens using the specified regular + * expression + * + * @param source + * @param regex + * @return List of tokens split from the source + */ + public static List<String> parsingByRegularExpression(String source, String regex) { + List<String> tokens = new ArrayList<String>(); + if (source != null && source.length() > 0) { + String[] parsed = source.split(regex); + for (String token : parsed) { + if (token.length() > 0) { + tokens.add(token); + } + } + } + return tokens; + } + + /** + * Builds a JSON object with error code and message information. + * + * @param errorCode + * @param errorMessage + * @return JSON object as a String + */ + public static String jsonErrorMessageResponse(int errorCode, String errorMessage) { + return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}"; + } + + /** + * Builds a JSON object with the specified message + * + * @param message + * @return JSON object as a String + */ + public static String jsonMessageResponse(String message) { + return String.format("{\"message\":\"%s\"}", message); + } + + /** + * Serializes the specified object as JSON and writes the result to the + * debug log. If serialization fails, logs a message to the error logger. + * + * @param logger + * Logger for the class where the object was built; the logger + * carries the class name. + * @param source + * First portion of the log message + * @param msg + * Second portion of the log message + * @param obj + * Object to serialize as JSON + */ + public static void logAndSerializeObject(EELFLoggerDelegate logger, String source, String msg, Object obj) { + try { + String objectAsJson = new ObjectMapper().writeValueAsString(obj); + logger.debug(EELFLoggerDelegate.debugLogger, + String.format("source= [%s]; %s [%s];", source, msg, objectAsJson)); + } catch (JsonProcessingException e) { + logger.warn(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed to serialize", e); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "logAndSerializedObject failed", e); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); + } + } + + /** + * Serializes the specified object as JSON and writes the result to the + * debug log. If serialization fails, logs a message to the error logger. + * + * @param source + * First portion of the log message + * @param msg + * Second portion of the log message + * @param obj + * Object to serialize as JSON + */ + public static void logAndSerializeObject(String source, String msg, Object obj) { + logAndSerializeObject(logger, source, msg, obj); + } + + public static void rollbackTransaction(Transaction transaction, String errorMessage) { + logger.error(EELFLoggerDelegate.errorLogger, errorMessage); + try { + if (transaction != null) { + transaction.rollback(); + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction", + e); + } + } + + public static void closeLocalSession(Session localSession, String errorMessage) { + logger.error(EELFLoggerDelegate.errorLogger, errorMessage); + try { + if (localSession != null) { + localSession.close(); + } + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e); + logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception", e); + } + } + + // TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor. + // It should be defined in SystemProperties. + private static final String GLOBAL_LOGIN_URL = "global-login-url"; + + /** + * Set response status to Unauthorized if user == null and to Forbidden in + * all (!) other cases. Logging is not performed if invocator == null + * + * @param user + * @param response + * @param invocator + * - may be null + */ + public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) { + if (user == null) { + String loginUrl = SystemProperties.getProperty(EPCommonSystemProperties.LOGIN_URL_NO_RET_VAL); + response.setHeader(GLOBAL_LOGIN_URL, loginUrl); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)); + } else { + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + MDC.put(EPCommonSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN)); + } + if (invocator != null) { + logger.warn(EELFLoggerDelegate.errorLogger, + invocator + ", permissions problem, response status = " + response.getStatus()); + } + } + + public static int getExternalAppResponseCode() { + String responseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE); + int responseCodeInt = 0; + try { + if (responseCode != null && responseCode != "") { + responseCodeInt = Integer.valueOf(responseCode); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred in getResponseCode(). Details: " + EcompPortalUtils.getStackTrace(e)); + } + return responseCodeInt; + } + + // This method might be just for testing purposes. + public static void setExternalAppResponseCode(int responseCode) { + try { + String responseCodeString = String.valueOf(responseCode); + MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, responseCodeString); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred in setResponseCode(). Details: " + EcompPortalUtils.getStackTrace(e)); + } + } + + public static String getHTTPStatusString(int httpStatusCode) { + String httpStatusString = "unknown_error"; + try { + httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name(); + if (httpStatusString != null) { + httpStatusString = httpStatusString.toLowerCase(); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred in getHTTPStatusString(). Details: " + EcompPortalUtils.getStackTrace(e)); + } + return httpStatusString; + } + + public static String getFEErrorString(Boolean internal, int responseCode) { + // Return a String like the following: + // "Internal Ecomp Error: 500 internal_server_error" or + // "External App Error: 404 not_found" + // TODO: create our own Ecomp error codes, starting with 1000 and up. + String responseString = ""; + String internalExternalString = internal ? "Ecomp Error: " : "App Error: "; + String httpStatusString = "unknown_error"; + try { + if (responseCode < 1000) { + httpStatusString = getHTTPStatusString(responseCode); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred in getFEErrorString(). Details: " + EcompPortalUtils.getStackTrace(e)); + } + responseString = internalExternalString + responseCode + " " + httpStatusString; + return responseString; + } + + public static boolean isProductionBuild() { + boolean productionBuild = true; + String epVersion = EcompVersion.buildNumber; + if (epVersion != null) { + int buildNum = epVersion.lastIndexOf('.'); + if (buildNum > 0) { + int buildNumber = Integer.parseInt(epVersion.substring(buildNum + 1)); + if (buildNumber < 3000) // Production versions are 3000+, (ie + // 1.0.3003) + { + productionBuild = false; + } + } + } + return productionBuild; + } + + private static final Object stackTraceLock = new Object(); + + public static String getStackTrace(Throwable t) { + synchronized (stackTraceLock) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + t.printStackTrace(pw); + return sw.toString(); + } + } + + public static String getMyIpAdddress() { + InetAddress ip; + String localIp; + try { + ip = InetAddress.getLocalHost(); + localIp = ip.getHostAddress(); + } catch (UnknownHostException e) { + localIp = "unknown"; + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + return localIp; + } + + public static String getMyHostName() { + InetAddress ip; + String hostName; + try { + ip = InetAddress.getLocalHost(); + hostName = ip.getHostName(); + } catch (UnknownHostException e) { + hostName = "unknown"; + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + return hostName; + } + + /* return a default property if the expected one is not available */ + public static String getPropertyOrDefault(String property, String defaultValue) { + return ((null == SystemProperties.getProperty(property) || SystemProperties.getProperty(property).equals("")) + ? defaultValue : SystemProperties.getProperty(property)); + } + + /** + * Calculates the time duration of a function call for logging purpose. It + * stores the result by using "MDC.put(SystemProperties.MDC_TIMER, + * timeDifference);" It is important to call + * "MDC.remove(SystemProperties.MDC_TIMER);" after this method call to clean + * up the record in MDC + * + * @param beginDateTime + * the given begin time for the call + * @param endDateTime + * the given end time for the call + * + */ + public static void calculateDateTimeDifferenceForLog(String beginDateTime, String endDateTime) { + if (beginDateTime != null && endDateTime != null) { + try { + SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + Date beginDate = ecompLogDateFormat.parse(beginDateTime); + Date endDate = ecompLogDateFormat.parse(endDateTime); + String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime()); + MDC.put(SystemProperties.MDC_TIMER, timeDifference); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompVersion.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompVersion.java index a4d5e0c1..8afde4ef 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompVersion.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompVersion.java @@ -1,33 +1,33 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.utils;
-
-//
-// Hardcoded for now, wanted to use maven and resource file. Possibly just read
-// pom.properties file with version added, but spent several hours already running
-// into issues with that and other ideas not working. So, for 1604 deadlines I
-// am just putting the version in the code here... for now.
-//
-public final class EcompVersion {
-
- // TODO - not used - manifest service reads from manifest
- public static final String buildNumber="1610.1.999";
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.utils; + +// +// Hardcoded for now, wanted to use maven and resource file. Possibly just read +// pom.properties file with version added, but spent several hours already running +// into issues with that and other ideas not working. So, for 1604 deadlines I +// am just putting the version in the code here... for now. +// +public final class EcompVersion { + + // TODO - not used - manifest service reads from manifest + public static final String buildNumber="1610.1.999"; + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/HashMapFromList.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/HashMapFromList.java index 3a781af9..a953bf1e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/HashMapFromList.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/HashMapFromList.java @@ -1,99 +1,99 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.utils;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.List;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
-/**
- *
- * @author Vladimir Turovets This class is used to create HashMap<String, T>
- * from the list of T objects. We suppose that
- * 1) T object contains field 'parmName' or getter 'getParmName()'.
- * The value of object.parmName or object.getParmName() is used as
- * a key in created hashMap.
- * 2) for all objects in the list 'parmName' or getter
- * 'getParmName().toString' has to be unique and not null.
- * This class has one function only:
- * HashMap<String, T> hashMap(List<T> list, String name) and returns
- * hash map created from list.
- *
- * @param <T>
- */
-public class HashMapFromList<T> {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HashMapFromList.class);
-
- public HashMap<String, T> hashMap(List<T> list, String name) {
- HashMap<String, T> result = new HashMap<String, T>();
- if (list == null || list.size() == 0 || name == null) {
- return result;
- }
- name = name.trim();
- if (name.length() > 0) {
- T object = list.get(0);
- try {
- String parmName = name;
- Field field = object.getClass().getField(parmName);
- for (T obj : list) {
- try {
- Object o = field.get(obj);
- if (o != null)
- result.put(o.toString(), obj);
- } catch (Exception e1) {
- String stackTrace = EcompPortalUtils.getStackTrace(e1);
- logger.error(EELFLoggerDelegate.errorLogger, "Object of class " + object.getClass().getName() + ", field " + parmName + ". Details: ", stackTrace);
- return new HashMap<String, T>();
- }
- }
- } catch (Exception e) {
- String getterName = "get" + (name.length() == 1 ? name.toUpperCase() : (name.substring(0, 1).toUpperCase() + name.substring(1)));
- try {
- Class<?>[] parmClasses = null;
- Method method = object.getClass().getMethod(getterName, parmClasses);
- Object[] parmValues = new Object[0];
- for (T obj : list) {
- try {
- Object o = method.invoke(obj, parmValues);
- if (o != null)
- result.put(o.toString(), obj);
- } catch (Exception e2) {
- String stackTrace = EcompPortalUtils.getStackTrace(e2);
- logger.error(EELFLoggerDelegate.errorLogger, "Object of class " + object.getClass().getName() + ", method " + getterName + ". Details: ", stackTrace);
- return new HashMap<String, T>();
- }
- }
- } catch (Exception e3) {
- String stackTrace = EcompPortalUtils.getStackTrace(e3);
- logger.error(EELFLoggerDelegate.errorLogger, "Object of class " + object.getClass().getName() + ", bad field '" + name + "' or method '" + getterName + "()'. Details: " + stackTrace);
- return new HashMap<String, T>();
- }
- }
- }
- if (list.size() != result.size()) {
- logger.warn(EELFLoggerDelegate.errorLogger, "Duplicated or empty keys were found!!!");
- }
- return result;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.utils; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +/** + * + * @author Vladimir Turovets This class is used to create HashMap<String, T> + * from the list of T objects. We suppose that + * 1) T object contains field 'parmName' or getter 'getParmName()'. + * The value of object.parmName or object.getParmName() is used as + * a key in created hashMap. + * 2) for all objects in the list 'parmName' or getter + * 'getParmName().toString' has to be unique and not null. + * This class has one function only: + * HashMap<String, T> hashMap(List<T> list, String name) and returns + * hash map created from list. + * + * @param <T> + */ +public class HashMapFromList<T> { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HashMapFromList.class); + + public HashMap<String, T> hashMap(List<T> list, String name) { + HashMap<String, T> result = new HashMap<String, T>(); + if (list == null || list.size() == 0 || name == null) { + return result; + } + name = name.trim(); + if (name.length() > 0) { + T object = list.get(0); + try { + String parmName = name; + Field field = object.getClass().getField(parmName); + for (T obj : list) { + try { + Object o = field.get(obj); + if (o != null) + result.put(o.toString(), obj); + } catch (Exception e1) { + String stackTrace = EcompPortalUtils.getStackTrace(e1); + logger.error(EELFLoggerDelegate.errorLogger, "Object of class " + object.getClass().getName() + ", field " + parmName + ". Details: ", stackTrace); + return new HashMap<String, T>(); + } + } + } catch (Exception e) { + String getterName = "get" + (name.length() == 1 ? name.toUpperCase() : (name.substring(0, 1).toUpperCase() + name.substring(1))); + try { + Class<?>[] parmClasses = null; + Method method = object.getClass().getMethod(getterName, parmClasses); + Object[] parmValues = new Object[0]; + for (T obj : list) { + try { + Object o = method.invoke(obj, parmValues); + if (o != null) + result.put(o.toString(), obj); + } catch (Exception e2) { + String stackTrace = EcompPortalUtils.getStackTrace(e2); + logger.error(EELFLoggerDelegate.errorLogger, "Object of class " + object.getClass().getName() + ", method " + getterName + ". Details: ", stackTrace); + return new HashMap<String, T>(); + } + } + } catch (Exception e3) { + String stackTrace = EcompPortalUtils.getStackTrace(e3); + logger.error(EELFLoggerDelegate.errorLogger, "Object of class " + object.getClass().getName() + ", bad field '" + name + "' or method '" + getterName + "()'. Details: " + stackTrace); + return new HashMap<String, T>(); + } + } + } + if (list.size() != result.size()) { + logger.warn(EELFLoggerDelegate.errorLogger, "Duplicated or empty keys were found!!!"); + } + return result; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/ParallelExecutor.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/ParallelExecutor.java index 1ddb550d..0354798c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/ParallelExecutor.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/ParallelExecutor.java @@ -1,83 +1,83 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.utils;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
-public abstract class ParallelExecutor<T> {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ParallelExecutor.class);
-
- protected static abstract class ThreadOperation<T> {
- public abstract T execute(List<Object> parms);
- }
-
- protected abstract ThreadOperation<T> getThreadOperation();
-
- private static class CallableOperationThread<T> implements Callable<T> {
-
- List<Object> parms;
-
- private ThreadOperation<T> operation;
-
- public CallableOperationThread(ThreadOperation<T> operation, List<Object> parms) {
- this.parms = parms;
- this.operation = operation;
- }
-
- @Override
- public T call() throws Exception {
- return this.operation.execute(this.parms);
- }
-
- }
-
- public List<T> performAllOperations(int ThreadPoolSize, List<List<Object>> listOfParms) {
- List<T> result = new ArrayList<T>();
- if (ThreadPoolSize > 0 && listOfParms != null) {
- ExecutorService executor = Executors.newFixedThreadPool(ThreadPoolSize);
- List<Future<T>> list = new ArrayList<Future<T>>();
- for (List<Object> parms : listOfParms) {
- CallableOperationThread<T> getter = new CallableOperationThread<T>(this.getThreadOperation(), parms);
- Future<T> submit = executor.submit(getter);
- list.add(submit);
- }
- for (Future<T> future : list) {
- try {
- if (future != null) {
- result.add(future.get());
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
- }
- }
- executor.shutdown();
- }
- return result;
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +public abstract class ParallelExecutor<T> { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ParallelExecutor.class); + + protected static abstract class ThreadOperation<T> { + public abstract T execute(List<Object> parms); + } + + protected abstract ThreadOperation<T> getThreadOperation(); + + private static class CallableOperationThread<T> implements Callable<T> { + + List<Object> parms; + + private ThreadOperation<T> operation; + + public CallableOperationThread(ThreadOperation<T> operation, List<Object> parms) { + this.parms = parms; + this.operation = operation; + } + + @Override + public T call() throws Exception { + return this.operation.execute(this.parms); + } + + } + + public List<T> performAllOperations(int ThreadPoolSize, List<List<Object>> listOfParms) { + List<T> result = new ArrayList<T>(); + if (ThreadPoolSize > 0 && listOfParms != null) { + ExecutorService executor = Executors.newFixedThreadPool(ThreadPoolSize); + List<Future<T>> list = new ArrayList<Future<T>>(); + for (List<Object> parms : listOfParms) { + CallableOperationThread<T> getter = new CallableOperationThread<T>(this.getThreadOperation(), parms); + Future<T> submit = executor.submit(getter); + list.add(submit); + } + for (Future<T> future : list) { + try { + if (future != null) { + result.add(future.get()); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + executor.shutdown(); + } + return result; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/PortalConstants.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/PortalConstants.java index a0dc7d68..485a80f5 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/PortalConstants.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/PortalConstants.java @@ -1,26 +1,29 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.portal.utils;
-
-public interface PortalConstants {
- public static final Long PORTAL_APP_ID = 1L;
- public static final Long DEFAULT_NOTIFICATION_CREATOR = 1L;
- public static final String REST_AUX_API = "/auxapi";
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.utils; + +public interface PortalConstants { + public static final Long PORTAL_APP_ID = 1L; + public static final Long DEFAULT_NOTIFICATION_CREATOR = 1L; + public static final String REST_AUX_API = "/auxapi"; + public static final Long ACCOUNT_ADMIN_ROLE_ID = 999L; + public static final int SYS_ADMIN_ROLE_ID = 1; + public static final String ADMIN_ROLE = "Account Administrator"; +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java index 3585f3a4..7ceca0e9 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java @@ -1,36 +1,36 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.service;
-
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-
-import org.openecomp.portalapp.portal.domain.EPUser;
-
-
-@Service("adminAuthExtension")
-@Transactional
-public class AdminAuthExtension {
-
- public void saveUserExtension(EPUser user){
- //app's developer implement their own logic here, like updating app's related tables
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.service; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import org.openecomp.portalapp.portal.domain.EPUser; + + +@Service("adminAuthExtension") +@Transactional +public class AdminAuthExtension { + + public void saveUserExtension(EPUser user){ + //app's developer implement their own logic here, like updating app's related tables + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/EPProfileService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/EPProfileService.java index 0adde120..2ea5b582 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/EPProfileService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/EPProfileService.java @@ -1,36 +1,36 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.service;
-
-import java.util.List;
-
-import org.openecomp.portalsdk.core.domain.Profile;
-import org.openecomp.portalapp.portal.domain.EPUser;
-
-
-public interface EPProfileService {
- List<Profile> findAll();
-
- Profile getProfile(int id);
-
- EPUser getUser(String id);
-
- void saveUser(EPUser user);
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.service; + +import java.util.List; + +import org.openecomp.portalsdk.core.domain.Profile; +import org.openecomp.portalapp.portal.domain.EPUser; + + +public interface EPProfileService { + List<Profile> findAll(); + + Profile getProfile(int id); + + EPUser getUser(String id); + + void saveUser(EPUser user); +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/EPProfileServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/EPProfileServiceImpl.java index 27975971..ecd6a13c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/EPProfileServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/EPProfileServiceImpl.java @@ -1,77 +1,77 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.service;
-
-import java.util.List;
-
-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 org.openecomp.portalsdk.core.dao.ProfileDao;
-import org.openecomp.portalsdk.core.domain.Profile;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
-
-@Service("epProfileService")
-@Transactional
-@org.springframework.context.annotation.Configuration
-@EnableAspectJAutoProxy
-@EPMetricsLog
-public class EPProfileServiceImpl implements EPProfileService {
-
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPProfileServiceImpl.class);
-
- @Autowired
- private ProfileDao profileDao;
-
- @Autowired
- private DataAccessService dataAccessService;
-
- @SuppressWarnings("unchecked")
- public List<Profile> findAll() {
- // List msgDB = getDataAccessService().getList(Profile.class, null);
- return getDataAccessService().getList(Profile.class, null);
- }
-
- public EPUser getUser(String userId) {
- return (EPUser) getDataAccessService().getDomainObject(EPUser.class, Long.parseLong(userId), null);
- }
-
- public void saveUser(EPUser user) {
-
- getDataAccessService().saveDomainObject(user, null);
- }
-
- public Profile getProfile(int id) {
- return profileDao.getProfile(id);
- }
-
- public DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- public void setDataAccessService(DataAccessService dataAccessService) {
- this.dataAccessService = dataAccessService;
- }
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.service; + +import java.util.List; + +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 org.openecomp.portalsdk.core.dao.ProfileDao; +import org.openecomp.portalsdk.core.domain.Profile; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; + +@Service("epProfileService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class EPProfileServiceImpl implements EPProfileService { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPProfileServiceImpl.class); + + @Autowired + private ProfileDao profileDao; + + @Autowired + private DataAccessService dataAccessService; + + @SuppressWarnings("unchecked") + public List<Profile> findAll() { + // List msgDB = getDataAccessService().getList(Profile.class, null); + return getDataAccessService().getList(Profile.class, null); + } + + public EPUser getUser(String userId) { + return (EPUser) getDataAccessService().getDomainObject(EPUser.class, Long.parseLong(userId), null); + } + + public void saveUser(EPUser user) { + + getDataAccessService().saveDomainObject(user, null); + } + + public Profile getProfile(int id) { + return profileDao.getProfile(id); + } + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/RemoteWebServiceCallService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/RemoteWebServiceCallService.java index 71d9dd12..1fd36aee 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/RemoteWebServiceCallService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/RemoteWebServiceCallService.java @@ -1,48 +1,54 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.service;
-
-public interface RemoteWebServiceCallService {
-
- /**
- * Answers whether the specified credentials match application information
- * in the database.
- *
- * @param secretKey
- * Key used to decrypt passwords; ignored if null.
- * @param requestUebKey
- * UEB key that identifies the application
- * @param requesUserName
- * User name for the application
- * @param requestPassword
- * Password for the application
- * @return True if the UEB key and the credentials match the database
- * entries; else false.
- * @throws Exception
- * If decryption fails.
- */
- public boolean verifyRESTCredential(String secretKey, String requestUebKey, String requestUserName,
- String requestPassword) throws Exception;
-
-
-
- public boolean verifyAppKeyCredential(String requestUebKey) throws Exception;
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.service; + +public interface RemoteWebServiceCallService { + + /** + * Answers whether the specified credentials match application information + * in the database. + * + * @param secretKey + * Key used to decrypt passwords; ignored if null. + * @param requestUebKey + * UEB key that identifies the application + * @param requestUserName + * User name for the application + * @param requestPassword + * Password for the application + * @return True if the UEB key and the credentials match the database + * entries; else false. + * @throws Exception + * If decryption fails. + */ + public boolean verifyRESTCredential(String secretKey, String requestUebKey, String requestUserName, + String requestPassword) throws Exception; + + /** + * + * @param requestUebKey + * UEB key + * @return boolean + * @throws Exception + * on error + */ + public boolean verifyAppKeyCredential(String requestUebKey) throws Exception; + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/EPUserUtils.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/EPUserUtils.java index a14bbe81..7dcf0e95 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/EPUserUtils.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/EPUserUtils.java @@ -1,407 +1,407 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.util;
-
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
-import org.openecomp.portalapp.portal.domain.EPRole;
-import org.openecomp.portalapp.portal.domain.EPUser;
-import org.openecomp.portalapp.portal.domain.EPUserApp;
-import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
-import org.openecomp.portalsdk.core.domain.RoleFunction;
-import org.openecomp.portalsdk.core.exception.SessionExpiredException;
-import org.openecomp.portalsdk.core.lm.FusionLicenseManager;
-import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
-import org.openecomp.portalsdk.core.menu.MenuBuilder;
-import org.openecomp.portalsdk.core.service.DataAccessService;
-import org.openecomp.portalsdk.core.util.SystemProperties;
-import org.openecomp.portalsdk.core.web.support.AppUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-
-public class EPUserUtils {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class);
-
- private final static Long ACCOUNT_ADMIN_ROLE_ID = 999L;
-
- public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions";
-
- private static DataAccessService dataAccessService;
-
- /**
- * Gets the EPUser object from the session.
- *
- * @param request
- * HttpServletRequest
- * @return EPUser object that was created upon login
- * @throws SessionExpiredException
- * if no session exists.
- */
- public static EPUser getUserSession(HttpServletRequest request) {
- HttpSession session = AppUtils.getSession(request);
- if (session == null)
- throw new SessionExpiredException();
- return (EPUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
- }
-
- /**
- * Establishes the user's portal session
- *
- * @param request
- * HttpServletRequest
- * @param user
- * EPUser
- * @param applicationMenuData
- * Menu data
- * @param businessDirectMenuData
- * Menu data
- * @param loginMethod_ignored
- * How the user authenticated; ignored
- * @param allRoleFunctions
- * Set of user's roles
- */
- @SuppressWarnings("rawtypes")
- public static void setUserSession(HttpServletRequest request, EPUser user, Set applicationMenuData,
- Set businessDirectMenuData, String loginMethod_ignored, List<RoleFunction> allRoleFunctions) {
- HttpSession session = request.getSession(true);
-
- // clear the current user session to avoid any conflicts
- EPUserUtils.clearUserSession(request);
- session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
-
- getAllRoleFunctions(allRoleFunctions, session);
-
- getRoleFunctions(request);
-
- // truncate the role (and therefore the role function) data to save
- // memory in the session
- user.setEPRoles(null);
- session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
-
- ServletContext context = session.getServletContext();
- int licenseVerificationFlag = 3;
- try {
- licenseVerificationFlag = (Integer) context.getAttribute("licenseVerification");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "setUserSession failed to get licenseVerification attribute",
- e);
- }
- switch (licenseVerificationFlag) {
- case FusionLicenseManager.DEVELOPER_LICENSE:
- session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME),
- "My Portal [Development Version]");
- break;
- case FusionLicenseManager.EXPIRED_LICENSE:
- session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME),
- "My Portal [LICENSE EXPIRED]");
- break;
- case FusionLicenseManager.VALID_LICENSE:
- session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), "My Portal");
- break;
- default:
- session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME),
- "My Portal [INVALID LICENSE]");
- break;
- }
-
- session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME),
- MenuBuilder.filterMenu(applicationMenuData, request));
- session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME),
- MenuBuilder.filterMenu(businessDirectMenuData, request));
- }
-
- /**
- * Creates a set of role function names and stores the set as a session
- * attribute.
- *
- * @param allRoleFunctions
- * List of role functions.
- * @param session
- * HttpSession
- */
- private static void getAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session) {
- if (allRoleFunctions == null)
- return;
- Set<String> roleFnSet = new HashSet<String>();
- for (RoleFunction roleFn : allRoleFunctions)
- roleFnSet.add(roleFn.getCode());
- session.setAttribute(ALL_ROLE_FUNCTIONS, roleFnSet);
- }
-
- /**
- * Removes all stored attributes from the user's session
- *
- * @param request
- * HttpServletRequest
- * @throws SessionExpiredException
- * if no session exists
- */
- private static void clearUserSession(HttpServletRequest request) {
- HttpSession session = AppUtils.getSession(request);
- if (session == null)
- throw new SessionExpiredException();
-
- // removes all stored attributes from the current user's session
- session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
- session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
- session.removeAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME));
- session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
- session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
- }
-
- /**
- * Builds a set of role functions and sets a session attribute with it.
- *
- * @param request
- * HttpServletRequest
- * @return Set of role functions that was built.
- */
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private static Set getRoleFunctions(HttpServletRequest request) {
- HashSet roleFunctions = null;
-
- HttpSession session = request.getSession();
- roleFunctions = (HashSet) session
- .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
-
- if (roleFunctions == null) {
- HashMap roles = getRoles(request);
- roleFunctions = new HashSet();
-
- Iterator i = roles.keySet().iterator();
-
- while (i.hasNext()) {
- Long roleKey = (Long) i.next();
- EPRole role = (EPRole) roles.get(roleKey);
-
- Iterator j = role.getRoleFunctions().iterator();
-
- while (j.hasNext()) {
- RoleFunction function = (RoleFunction) j.next();
- roleFunctions.add(function.getCode());
- }
- }
-
- session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME),
- roleFunctions);
- }
-
- return roleFunctions;
- }
-
- /**
- * Gets role information from the user session, in the cached user object.
- * As a side effect sets a session variable with the roles.
- *
- * @param request
- * HttpServletRequest
- * @return Map of role ID to role object
- */
- @SuppressWarnings("rawtypes")
- private static HashMap getRoles(HttpServletRequest request) {
- HashMap roles = null;
-
- HttpSession session = AppUtils.getSession(request);
- roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
-
- // if roles are not already cached, let's grab them from the user
- // session
- if (roles == null) {
- EPUser user = getUserSession(request);
-
- // get all user roles (including the tree of child roles)
- roles = getAllUserRoles(user);
-
- session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME), roles);
- }
-
- return roles;
- }
-
- /**
- * Builds a map of role ID to role object.
- *
- * @param user
- * EPUser
- * @return Map of role ID to role object
- */
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private static HashMap getAllUserRoles(EPUser user) {
- HashMap roles = new HashMap();
- Iterator i = user.getEPRoles().iterator();
-
- while (i.hasNext()) {
- EPRole role = (EPRole) i.next();
-
- if (role.getActive()) {
- roles.put(role.getId(), role);
-
- // let's take a recursive trip down the tree to add all child
- // roles
- addChildRoles(role, roles);
- }
- }
-
- // Additionally; the account admin role is overloaded between ecomp
- // portal and partners; lets also include that
- Iterator<EPUserApp> appRolesIterator = user.getEPUserApps().iterator();
- while (appRolesIterator.hasNext()) {
- EPRole role = (EPRole) appRolesIterator.next().getRole();
-
- if (role.getActive() && role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
- roles.put(role.getId(), role);
-
- // let's take a recursive trip down the tree to add all child
- // roles
- addChildRoles(role, roles);
- }
- }
-
- return roles;
- }
-
- /**
- * Adds all child roles of the specified role to the map of roles.
- *
- * @param role
- * EPRole
- * @param roles
- * Maps role id to role object
- */
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private static void addChildRoles(EPRole role, HashMap roles) {
- Set childRoles = role.getChildRoles();
-
- if (childRoles != null && childRoles.size() > 0) {
- Iterator j = childRoles.iterator();
- while (j.hasNext()) {
- EPRole childRole = (EPRole) j.next();
-
- if (childRole.getActive()) {
- roles.put(childRole.getId(), childRole);
-
- addChildRoles(childRole, roles);
- }
- }
- }
-
- }
-
- public static boolean hasRole(EPUser user, String roleKey) {
- return getAllUserRoles(user).keySet().contains(new Long(roleKey));
- }
-
- public static DataAccessService getDataAccessService() {
- return dataAccessService;
- }
-
- @Autowired
- public void setDataAccessService(DataAccessService dataAccessService) {
- EPUserUtils.dataAccessService = dataAccessService;
- }
-
- /**
- * Gets the user's ID from the user object in the session
- *
- * @param request
- * HttpServletRequest
- * @return Integer ID of current user
- */
- public static int getUserId(HttpServletRequest request) {
- return getUserIdAsLong(request).intValue();
- }
-
- /**
- * Gets the user's ID from the user object in the session
- *
- * @param request
- * HttpServletREquest
- * @return Long ID of current user
- */
- public static Long getUserIdAsLong(HttpServletRequest request) {
- Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
- if (request != null) {
- if (getUserSession(request) != null) {
- userId = getUserSession(request).getId();
- }
- }
- return userId;
- }
-
- /**
- * Gets the request ID from the request.
- *
- * @param request
- * HttpServletRequest
- * @return Request ID
- */
- public static String getRequestId(HttpServletRequest request) {
- Enumeration<String> headerNames = request.getHeaderNames();
-
- String requestId = "";
- try {
- while (headerNames.hasMoreElements()) {
- String headerName = (String) headerNames.nextElement();
- logger.debug(EELFLoggerDelegate.debugLogger,
- "One header is " + headerName + " : " + request.getHeader(headerName));
- if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
- requestId = request.getHeader(headerName);
- break;
- }
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "HEADER!!!! Exception : " + EcompPortalUtils.getStackTrace(e));
- }
-
- return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
- }
-
- /**
- * Gets the full URL from the request.
- *
- * @param request
- * HttpServletRequest
- * @return Full URL
- */
- public static String getFullURL(HttpServletRequest request) {
- if (request != null) {
- StringBuffer requestURL = request.getRequestURL();
- String queryString = request.getQueryString();
-
- if (queryString == null) {
- return requestURL.toString();
- } else {
- return requestURL.append('?').append(queryString).toString();
- }
- }
- return "";
- }
-
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.util; + +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.exception.SessionExpiredException; +import org.openecomp.portalsdk.core.lm.FusionLicenseManager; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.menu.MenuBuilder; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.springframework.beans.factory.annotation.Autowired; + +public class EPUserUtils { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class); + + private final static Long ACCOUNT_ADMIN_ROLE_ID = 999L; + + public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions"; + + private static DataAccessService dataAccessService; + + /** + * Gets the EPUser object from the session. + * + * @param request + * HttpServletRequest + * @return EPUser object that was created upon login + * @throws SessionExpiredException + * if no session exists. + */ + public static EPUser getUserSession(HttpServletRequest request) { + HttpSession session = AppUtils.getSession(request); + if (session == null) + throw new SessionExpiredException(); + return (EPUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); + } + + /** + * Establishes the user's portal session + * + * @param request + * HttpServletRequest + * @param user + * EPUser + * @param applicationMenuData + * Menu data + * @param businessDirectMenuData + * Menu data + * @param loginMethod_ignored + * How the user authenticated; ignored + * @param allRoleFunctions + * Set of user's roles + */ + @SuppressWarnings("rawtypes") + public static void setUserSession(HttpServletRequest request, EPUser user, Set applicationMenuData, + Set businessDirectMenuData, String loginMethod_ignored, List<RoleFunction> allRoleFunctions) { + HttpSession session = request.getSession(true); + + // clear the current user session to avoid any conflicts + EPUserUtils.clearUserSession(request); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); + + getAllRoleFunctions(allRoleFunctions, session); + + getRoleFunctions(request); + + // truncate the role (and therefore the role function) data to save + // memory in the session + user.setEPRoles(null); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName()); + + ServletContext context = session.getServletContext(); + int licenseVerificationFlag = 3; + try { + licenseVerificationFlag = (Integer) context.getAttribute("licenseVerification"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "setUserSession failed to get licenseVerification attribute", + e); + } + switch (licenseVerificationFlag) { + case FusionLicenseManager.DEVELOPER_LICENSE: + session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), + "My Portal [Development Version]"); + break; + case FusionLicenseManager.EXPIRED_LICENSE: + session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), + "My Portal [LICENSE EXPIRED]"); + break; + case FusionLicenseManager.VALID_LICENSE: + session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), "My Portal"); + break; + default: + session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), + "My Portal [INVALID LICENSE]"); + break; + } + + session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME), + MenuBuilder.filterMenu(applicationMenuData, request)); + session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME), + MenuBuilder.filterMenu(businessDirectMenuData, request)); + } + + /** + * Creates a set of role function names and stores the set as a session + * attribute. + * + * @param allRoleFunctions + * List of role functions. + * @param session + * HttpSession + */ + private static void getAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session) { + if (allRoleFunctions == null) + return; + Set<String> roleFnSet = new HashSet<String>(); + for (RoleFunction roleFn : allRoleFunctions) + roleFnSet.add(roleFn.getCode()); + session.setAttribute(ALL_ROLE_FUNCTIONS, roleFnSet); + } + + /** + * Removes all stored attributes from the user's session + * + * @param request + * HttpServletRequest + * @throws SessionExpiredException + * if no session exists + */ + private static void clearUserSession(HttpServletRequest request) { + HttpSession session = AppUtils.getSession(request); + if (session == null) + throw new SessionExpiredException(); + + // removes all stored attributes from the current user's session + session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); + session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)); + session.removeAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME)); + session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME)); + session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)); + } + + /** + * Builds a set of role functions and sets a session attribute with it. + * + * @param request + * HttpServletRequest + * @return Set of role functions that was built. + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private static Set getRoleFunctions(HttpServletRequest request) { + HashSet roleFunctions = null; + + HttpSession session = request.getSession(); + roleFunctions = (HashSet) session + .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)); + + if (roleFunctions == null) { + HashMap roles = getRoles(request); + roleFunctions = new HashSet(); + + Iterator i = roles.keySet().iterator(); + + while (i.hasNext()) { + Long roleKey = (Long) i.next(); + EPRole role = (EPRole) roles.get(roleKey); + + Iterator j = role.getRoleFunctions().iterator(); + + while (j.hasNext()) { + RoleFunction function = (RoleFunction) j.next(); + roleFunctions.add(function.getCode()); + } + } + + session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME), + roleFunctions); + } + + return roleFunctions; + } + + /** + * Gets role information from the user session, in the cached user object. + * As a side effect sets a session variable with the roles. + * + * @param request + * HttpServletRequest + * @return Map of role ID to role object + */ + @SuppressWarnings("rawtypes") + private static HashMap getRoles(HttpServletRequest request) { + HashMap roles = null; + + HttpSession session = AppUtils.getSession(request); + roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME)); + + // if roles are not already cached, let's grab them from the user + // session + if (roles == null) { + EPUser user = getUserSession(request); + + // get all user roles (including the tree of child roles) + roles = getAllUserRoles(user); + + session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME), roles); + } + + return roles; + } + + /** + * Builds a map of role ID to role object. + * + * @param user + * EPUser + * @return Map of role ID to role object + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private static HashMap getAllUserRoles(EPUser user) { + HashMap roles = new HashMap(); + Iterator i = user.getEPRoles().iterator(); + + while (i.hasNext()) { + EPRole role = (EPRole) i.next(); + + if (role.getActive()) { + roles.put(role.getId(), role); + + // let's take a recursive trip down the tree to add all child + // roles + addChildRoles(role, roles); + } + } + + // Additionally; the account admin role is overloaded between ecomp + // portal and partners; lets also include that + Iterator<EPUserApp> appRolesIterator = user.getEPUserApps().iterator(); + while (appRolesIterator.hasNext()) { + EPRole role = (EPRole) appRolesIterator.next().getRole(); + + if (role.getActive() && role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) { + roles.put(role.getId(), role); + + // let's take a recursive trip down the tree to add all child + // roles + addChildRoles(role, roles); + } + } + + return roles; + } + + /** + * Adds all child roles of the specified role to the map of roles. + * + * @param role + * EPRole + * @param roles + * Maps role id to role object + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private static void addChildRoles(EPRole role, HashMap roles) { + Set childRoles = role.getChildRoles(); + + if (childRoles != null && childRoles.size() > 0) { + Iterator j = childRoles.iterator(); + while (j.hasNext()) { + EPRole childRole = (EPRole) j.next(); + + if (childRole.getActive()) { + roles.put(childRole.getId(), childRole); + + addChildRoles(childRole, roles); + } + } + } + + } + + public static boolean hasRole(EPUser user, String roleKey) { + return getAllUserRoles(user).keySet().contains(new Long(roleKey)); + } + + public static DataAccessService getDataAccessService() { + return dataAccessService; + } + + @Autowired + public void setDataAccessService(DataAccessService dataAccessService) { + EPUserUtils.dataAccessService = dataAccessService; + } + + /** + * Gets the user's ID from the user object in the session + * + * @param request + * HttpServletRequest + * @return Integer ID of current user + */ + public static int getUserId(HttpServletRequest request) { + return getUserIdAsLong(request).intValue(); + } + + /** + * Gets the user's ID from the user object in the session + * + * @param request + * HttpServletREquest + * @return Long ID of current user + */ + public static Long getUserIdAsLong(HttpServletRequest request) { + Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID)); + if (request != null) { + if (getUserSession(request) != null) { + userId = getUserSession(request).getId(); + } + } + return userId; + } + + /** + * Gets the request ID from the request. + * + * @param request + * HttpServletRequest + * @return Request ID + */ + public static String getRequestId(HttpServletRequest request) { + Enumeration<String> headerNames = request.getHeaderNames(); + + String requestId = ""; + try { + while (headerNames.hasMoreElements()) { + String headerName = (String) headerNames.nextElement(); + logger.debug(EELFLoggerDelegate.debugLogger, + "One header is " + headerName + " : " + request.getHeader(headerName)); + if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) { + requestId = request.getHeader(headerName); + break; + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "HEADER!!!! Exception : " + EcompPortalUtils.getStackTrace(e)); + } + + return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId); + } + + /** + * Gets the full URL from the request. + * + * @param request + * HttpServletRequest + * @return Full URL + */ + public static String getFullURL(HttpServletRequest request) { + if (request != null) { + StringBuffer requestURL = request.getRequestURL(); + String queryString = request.getQueryString(); + + if (queryString == null) { + return requestURL.toString(); + } else { + return requestURL.append('?').append(queryString).toString(); + } + } + return ""; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/SessionCookieUtil.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/SessionCookieUtil.java deleted file mode 100644 index 1ef44a44..00000000 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/SessionCookieUtil.java +++ /dev/null @@ -1,129 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ================================================================================ - */ -package org.openecomp.portalapp.util; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; -import org.openecomp.portalapp.portal.utils.EcompPortalUtils; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; -import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler; -import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.AppUtils; - -public class SessionCookieUtil { - - //private static final String JSESSIONID = "JSESSIONID"; - private static final String EP_SERVICE = "EPService"; - private static final String USER_ID = "UserId"; - private static Integer cookieMaxAge = -1; - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionCookieUtil.class); - - public static void preSetUp(HttpServletRequest request, - HttpServletResponse response) { - initateSessionMgtHandler(request); - //set up EPService cookie - setUpEPServiceCookie(request, response); - } - - public static void setUpEPServiceCookie(HttpServletRequest request, - HttpServletResponse response) { - String jSessionId = getJessionId(request); - Cookie cookie1 = new Cookie(EP_SERVICE, jSessionId); - cookie1.setMaxAge(cookieMaxAge); - cookie1.setDomain(EPCommonSystemProperties.getProperty(EPCommonSystemProperties.COOKIE_DOMAIN)); - cookie1.setPath("/"); - response.addCookie(cookie1); - } - - public static void setUpUserIdCookie(HttpServletRequest request, - HttpServletResponse response,String userId) throws Exception { - logger.info("************** session cookie util set up UserId cookie begins"); - userId = CipherUtil.encrypt(userId, - SystemProperties.getProperty(SystemProperties.Decryption_Key)); - Cookie cookie1 = new Cookie(USER_ID, userId); - cookie1.setMaxAge(cookieMaxAge); - cookie1.setDomain(EPCommonSystemProperties.getProperty(EPCommonSystemProperties.COOKIE_DOMAIN)); - cookie1.setPath("/"); - response.addCookie(cookie1); - logger.info("************** session cookie util set up EP cookie completed"); - } - - public static String getUserIdFromCookie(HttpServletRequest request, - HttpServletResponse response) 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)); - } - - logger.info("************** session cookie util set up EP cookie completed"); - return userId; - } - - public static String getJessionId(HttpServletRequest request){ - - return request.getSession().getId(); - /* - Cookie ep = WebUtils.getCookie(request, JSESSIONID); - if(ep==null){ - return request.getSession().getId(); - } - return ep.getValue(); - */ - } - - protected static void initateSessionMgtHandler(HttpServletRequest request) { - String jSessionId = getJessionId(request); - storeMaxInactiveTime(request); - PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request)); - } - - protected static void storeMaxInactiveTime(HttpServletRequest request) { - HttpSession session = AppUtils.getSession(request); - if(session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME) == null) - session.setAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME,session.getMaxInactiveInterval()); - } - - public static void resetSessionMaxIdleTimeOut(HttpServletRequest request) { - try { - HttpSession session = AppUtils.getSession(request); - final Object maxIdleAttribute = session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME); - if(session != null && maxIdleAttribute != null) { - session.setMaxInactiveInterval(Integer.parseInt(maxIdleAttribute.toString())); - } - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "Could not reset the session timeout. Details: " + EcompPortalUtils.getStackTrace(e)); - } - - } - -} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/SystemType.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/SystemType.java index fb0e35fc..44b8d40b 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/SystemType.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/SystemType.java @@ -1,26 +1,26 @@ -/*-
- * ================================================================================
- * ECOMP Portal
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ================================================================================
- */
-package org.openecomp.portalapp.util;
-
-public enum SystemType {
-
- APPLICATION,
-// SYSTEM
-}
+/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.util; + +public enum SystemType { + + APPLICATION, +// SYSTEM +} diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/defs/definitions.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/defs/definitions.xml index 18445f20..0fa84a9c 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/defs/definitions.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/defs/definitions.xml @@ -1,38 +1,38 @@ -<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ================================================================================
- ECOMP Portal
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ================================================================================
- -->
-
-<!DOCTYPE tiles-definitions PUBLIC
- "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
- "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
-<tiles-definitions>
-
- <definition extends="ebz_template" name="leafletMap">
- <put-attribute name="body" value="/WEB-INF/jsp/leafletMap.jsp"></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="callflow">
- <put-attribute name="body" value="/WEB-INF/fusion/jsp/sequence/details.jsp"></put-attribute>
- </definition>
-
-
- <definition name="net_map_int" template="/WEB-INF/jsp/net_map.jsp"/>
-
-</tiles-definitions>
+<?xml version="1.0" encoding="UTF-8"?> +<!-- + ================================================================================ + ECOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ================================================================================ + --> + +<!DOCTYPE tiles-definitions PUBLIC + "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN" + "http://tiles.apache.org/dtds/tiles-config_3_0.dtd"> +<tiles-definitions> + + <definition extends="ebz_template" name="leafletMap"> + <put-attribute name="body" value="/WEB-INF/jsp/leafletMap.jsp"></put-attribute> + </definition> + + <definition extends="ebz_template" name="callflow"> + <put-attribute name="body" value="/WEB-INF/fusion/jsp/sequence/details.jsp"></put-attribute> + </definition> + + + <definition name="net_map_int" template="/WEB-INF/jsp/net_map.jsp"/> + +</tiles-definitions> diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/defs/definitions.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/defs/definitions.xml index 433fec8a..4749dbb3 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/defs/definitions.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/defs/definitions.xml @@ -1,203 +1,189 @@ -<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ================================================================================
- ECOMP Portal
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ================================================================================
- -->
-
-<!DOCTYPE tiles-definitions PUBLIC
- "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
- "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
-<tiles-definitions>
-
- <definition name="ebz_template" template="/WEB-INF/fusion/jsp/ebz_template.jsp">
- <put-attribute name="title" value=""></put-attribute>
- <put-attribute name="header" value="/WEB-INF/fusion/jsp/ebz/ebz_header.jsp"></put-attribute>
- <put-attribute name="body" value=""></put-attribute>
- <put-attribute name="footer" value="/WEB-INF/fusion/jsp/ebz/ebz_footer.jsp"></put-attribute>
- </definition>
-
- <definition name="ebz_template_raptor" template="/WEB-INF/fusion/jsp/ebz_template_raptor.jsp">
- <put-attribute name="title" value=""></put-attribute>
- <put-attribute name="header" value="/WEB-INF/fusion/jsp/ebz/ebz_header_raptor.jsp"></put-attribute>
- <put-attribute name="body" value=""></put-attribute>
- <put-attribute name="footer" value="/WEB-INF/fusion/jsp/ebz/ebz_footer_raptor.jsp"></put-attribute>
- </definition>
-
- <definition name="ebz_template_noheader_nofooter" template="/WEB-INF/fusion/jsp/ebz_template_noheader_nofooter.jsp">
- <put-attribute name="body" value=""></put-attribute>
- </definition>
-
- <definition name="ebz_template_report_embedded"
- template="/WEB-INF/fusion/jsp/ebz/ebz_template_report_embedded.jsp">
- <put-attribute name="body" value=""></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="user_profile">
- <put-attribute name="body" value="/WEB-INF/jsp/user_profile.jsp"></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="profile_search">
- <put-attribute name="body" value="/WEB-INF/fusion/jsp/profile_search.jsp"></put-attribute>
- <put-attribute name="viewName" value="profile_search"></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="profile">
- <put-attribute name="body" value="/WEB-INF/fusion/jsp/profile.jsp"></put-attribute>
- <put-attribute name="viewName" value="profile"></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="menu">
- <put-attribute name="body" value="/WEB-INF/jsp/menu.jsp"></put-attribute>
- <put-attribute name="viewName" value="menu"></put-attribute>
- </definition>
-
-
- <definition extends="ebz_template" name="welcome">
- <put-attribute name="body" value="/WEB-INF/jsp/welcome.jsp"></put-attribute>
- <put-attribute name="viewName" value="welcome"></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="role_list">
- <put-attribute name="body" value="/WEB-INF/fusion/jsp/role_list.jsp"></put-attribute>
- <put-attribute name="viewName" value="role_list"></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="role">
- <put-attribute name="body" value="/WEB-INF/fusion/jsp/role.jsp"></put-attribute>
- <put-attribute name="viewName" value="role"></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="role_function_list">
- <put-attribute name="body" value="/WEB-INF/fusion/jsp/role_function_list.jsp"></put-attribute>
- <put-attribute name="viewName" value="role_function_list"></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="post_search">
- <put-attribute name="body" value="/WEB-INF/fusion/jsp/post_search.jsp"></put-attribute>
- <put-attribute name="viewName" value="post_search"></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="error">
- <put-attribute name="body" value="/WEB-INF/jsp/error.jsp"></put-attribute>
- <put-attribute name="viewName" value="error"></put-attribute>
- </definition>
-
- <definition extends="ebz_template_raptor" name="report">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/report_ebz.jsp"></put-attribute>
- <put-attribute name="viewName"
- value="report"></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="report_wizard">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/report_wizard.jsp"></put-attribute>
- <put-attribute name="viewName" value="report_wizard"></put-attribute>
- </definition>
-
- <definition extends="ebz_template_report_embedded" name="report_embedded">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/report_ebz_embedded.jsp"></put-attribute>
- </definition>
- <definition extends="ebz_template" name="report_sample">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/report_sample.jsp"></put-attribute>
- </definition>
- <definition extends="ebz_template_noheader_nofooter" name="test_run_sql">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/test_run_sql.jsp"></put-attribute>
- </definition>
- <definition extends="ebz_template_noheader_nofooter" name="date_start_field_run_sql">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/date_start_field_run_sql.jsp"></put-attribute>
- </definition>
- <definition extends="ebz_template_noheader_nofooter" name="date_end_field_run_sql">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/date_end_field_run_sql.jsp"></put-attribute>
- </definition>
- <definition extends="ebz_template_noheader_nofooter" name="test_field_run_sql">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/test_field_run_sql.jsp"></put-attribute>
- </definition>
- <definition extends="ebz_template_noheader_nofooter" name="default_field_run_sql">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/default_field_run_sql.jsp"></put-attribute>
- </definition>
- <definition extends="ebz_template_noheader_nofooter" name="popup_testrun_sql">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/popup_testrun_sql.jsp"></put-attribute>
- </definition>
- <definition extends="ebz_template_noheader_nofooter" name="popup_semaphore">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/popup_semaphore.jsp"></put-attribute>
- </definition>
- <definition extends="ebz_template_noheader_nofooter" name="popup_import_semaphore">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/popup_import_semaphore.jsp"></put-attribute>
- </definition>
- <definition extends="ebz_template_noheader_nofooter" name="popup_table_cols">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/popup_table_cols.jsp"></put-attribute>
- </definition>
- <definition extends="ebz_template_noheader_nofooter" name="popup_drill_down_report">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/popup_drill_down_report.jsp"></put-attribute>
- </definition>
- <definition extends="ebz_template_noheader_nofooter" name="popup_sql">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/popup_sql.jsp"></put-attribute>
- </definition>
-
- <definition name="raptor/error_page.jsp" template="/WEB-INF/fusion/raptor/error_page.jsp"/>
-
- <definition extends="ebz_template_raptor" name="wizard_schedule_only">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/wizard_schedule_only.jsp"></put-attribute>
- <put-attribute name="viewName" value="wizard_schedule_only"></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="report_import">
- <put-attribute name="body"
- value="/WEB-INF/fusion/raptor/report_import.jsp"></put-attribute>
- <put-attribute name="viewName" value="report_import"></put-attribute>
- </definition>
-
- <definition name="data_out" template="/WEB-INF/fusion/jsp/data_out.jsp" />
- <definition extends="ebz_template" name="collaborate_list">
- <put-attribute name="body" value="/WEB-INF/fusion/jsp/collaborateList.jsp"></put-attribute>
- </definition>
-
-
- <definition extends="ebz_template" name="jcs_admin">
- <put-attribute name="body" value="/WEB-INF/fusion/jsp/jcs_admin.jsp"></put-attribute>
- <put-attribute name="viewName" value="jcs_admin"></put-attribute>
- </definition>
-
- <definition extends="ebz_template" name="usage_list">
- <put-attribute name="body" value="/WEB-INF/fusion/jsp/usage_list.jsp"></put-attribute>
- <put-attribute name="viewName" value="usage_list"></put-attribute>
- </definition>
- <!--
- <definition extends="ebz_template_noheader_nofooter" name="collaboration">
- <put-attribute name="body" value="/WEB-INF/fusion/jsp/webrtc/collaboration.jsp"></put-attribute>
- </definition>
- -->
- <definition name="collaboration" template="/WEB-INF/fusion/jsp/webrtc/collaboration.jsp"/>
-
-
-</tiles-definitions>
+<?xml version="1.0" encoding="UTF-8"?> +<!-- + ================================================================================ + ECOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ================================================================================ + --> + +<!DOCTYPE tiles-definitions PUBLIC + "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN" + "http://tiles.apache.org/dtds/tiles-config_3_0.dtd"> +<tiles-definitions> + + <definition name="ebz_template" template="/WEB-INF/fusion/jsp/ebz_template.jsp"> + <put-attribute name="title" value=""></put-attribute> + <put-attribute name="header" value="/WEB-INF/fusion/jsp/ebz/ebz_header.jsp"></put-attribute> + <put-attribute name="body" value=""></put-attribute> + <put-attribute name="footer" value="/WEB-INF/fusion/jsp/ebz/ebz_footer.jsp"></put-attribute> + </definition> + + <definition name="ebz_template_raptor" template="/WEB-INF/fusion/jsp/ebz_template_raptor.jsp"> + <put-attribute name="title" value=""></put-attribute> + <put-attribute name="header" value="/WEB-INF/fusion/jsp/ebz/ebz_header_raptor.jsp"></put-attribute> + <put-attribute name="body" value=""></put-attribute> + <put-attribute name="footer" value="/WEB-INF/fusion/jsp/ebz/ebz_footer_raptor.jsp"></put-attribute> + </definition> + + <definition name="ebz_template_noheader_nofooter" template="/WEB-INF/fusion/jsp/ebz_template_noheader_nofooter.jsp"> + <put-attribute name="body" value=""></put-attribute> + </definition> + + <definition name="ebz_template_report_embedded" + template="/WEB-INF/fusion/jsp/ebz/ebz_template_report_embedded.jsp"> + <put-attribute name="body" value=""></put-attribute> + </definition> + + <definition extends="ebz_template" name="user_profile"> + <put-attribute name="body" value="/WEB-INF/jsp/user_profile.jsp"></put-attribute> + </definition> + + <definition extends="ebz_template" name="profile_search"> + <put-attribute name="body" value="/WEB-INF/fusion/jsp/profile_search.jsp"></put-attribute> + <put-attribute name="viewName" value="profile_search"></put-attribute> + </definition> + + <definition extends="ebz_template" name="profile"> + <put-attribute name="body" value="/WEB-INF/fusion/jsp/profile.jsp"></put-attribute> + <put-attribute name="viewName" value="profile"></put-attribute> + </definition> + + <definition extends="ebz_template" name="menu"> + <put-attribute name="body" value="/WEB-INF/jsp/menu.jsp"></put-attribute> + <put-attribute name="viewName" value="menu"></put-attribute> + </definition> + + + <definition extends="ebz_template" name="welcome"> + <put-attribute name="body" value="/WEB-INF/jsp/welcome.jsp"></put-attribute> + <put-attribute name="viewName" value="welcome"></put-attribute> + </definition> + + <definition extends="ebz_template" name="role_list"> + <put-attribute name="body" value="/WEB-INF/fusion/jsp/role_list.jsp"></put-attribute> + <put-attribute name="viewName" value="role_list"></put-attribute> + </definition> + + <definition extends="ebz_template" name="role"> + <put-attribute name="body" value="/WEB-INF/fusion/jsp/role.jsp"></put-attribute> + <put-attribute name="viewName" value="role"></put-attribute> + </definition> + + <definition extends="ebz_template" name="role_function_list"> + <put-attribute name="body" value="/WEB-INF/fusion/jsp/role_function_list.jsp"></put-attribute> + <put-attribute name="viewName" value="role_function_list"></put-attribute> + </definition> + + <definition extends="ebz_template" name="post_search"> + <put-attribute name="body" value="/WEB-INF/fusion/jsp/post_search.jsp"></put-attribute> + <put-attribute name="viewName" value="post_search"></put-attribute> + </definition> + + <definition name="error" template="/WEB-INF/jsp/error.jsp"/> + + <definition name="report" template="/app/fusion/scripts/DS2-view-models/ds2-reports/all-reports.html" /> + + <definition extends="ebz_template" name="report_wizard"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/report_wizard.jsp"></put-attribute> + <put-attribute name="viewName" value="report_wizard"></put-attribute> + </definition> + + <definition extends="ebz_template_report_embedded" name="report_embedded"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/report_ebz_embedded.jsp"></put-attribute> + </definition> + <definition extends="ebz_template" name="report_sample"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/report_sample.jsp"></put-attribute> + </definition> + <definition extends="ebz_template_noheader_nofooter" name="test_run_sql"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/test_run_sql.jsp"></put-attribute> + </definition> + <definition extends="ebz_template_noheader_nofooter" name="date_start_field_run_sql"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/date_start_field_run_sql.jsp"></put-attribute> + </definition> + <definition extends="ebz_template_noheader_nofooter" name="date_end_field_run_sql"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/date_end_field_run_sql.jsp"></put-attribute> + </definition> + <definition extends="ebz_template_noheader_nofooter" name="test_field_run_sql"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/test_field_run_sql.jsp"></put-attribute> + </definition> + <definition extends="ebz_template_noheader_nofooter" name="default_field_run_sql"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/default_field_run_sql.jsp"></put-attribute> + </definition> + <definition extends="ebz_template_noheader_nofooter" name="popup_testrun_sql"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/popup_testrun_sql.jsp"></put-attribute> + </definition> + <definition extends="ebz_template_noheader_nofooter" name="popup_semaphore"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/popup_semaphore.jsp"></put-attribute> + </definition> + <definition extends="ebz_template_noheader_nofooter" name="popup_import_semaphore"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/popup_import_semaphore.jsp"></put-attribute> + </definition> + <definition extends="ebz_template_noheader_nofooter" name="popup_table_cols"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/popup_table_cols.jsp"></put-attribute> + </definition> + <definition extends="ebz_template_noheader_nofooter" name="popup_drill_down_report"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/popup_drill_down_report.jsp"></put-attribute> + </definition> + <definition extends="ebz_template_noheader_nofooter" name="popup_sql"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/popup_sql.jsp"></put-attribute> + </definition> + + <definition name="raptor/error_page.jsp" template="/WEB-INF/fusion/raptor/error_page.jsp"/> + + <definition extends="ebz_template_raptor" name="wizard_schedule_only"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/wizard_schedule_only.jsp"></put-attribute> + <put-attribute name="viewName" value="wizard_schedule_only"></put-attribute> + </definition> + + <definition extends="ebz_template" name="report_import"> + <put-attribute name="body" + value="/WEB-INF/fusion/raptor/report_import.jsp"></put-attribute> + <put-attribute name="viewName" value="report_import"></put-attribute> + </definition> + + <definition name="data_out" template="/WEB-INF/fusion/jsp/data_out.jsp" /> + <definition extends="ebz_template" name="collaborate_list"> + <put-attribute name="body" value="/WEB-INF/fusion/jsp/collaborateList.jsp"></put-attribute> + </definition> + + <definition extends="ebz_template" name="jcs_admin"> + <put-attribute name="body" value="/WEB-INF/fusion/jsp/jcs_admin.jsp"></put-attribute> + <put-attribute name="viewName" value="jcs_admin"></put-attribute> + </definition> + + <definition extends="ebz_template" name="usage_list"> + <put-attribute name="body" value="/WEB-INF/fusion/jsp/usage_list.jsp"></put-attribute> + <put-attribute name="viewName" value="usage_list"></put-attribute> + </definition> + + <definition name="collaboration" template="/WEB-INF/fusion/jsp/webrtc/collaboration.jsp"/> + +</tiles-definitions> diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml index bda281c2..84f7b7ed 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml @@ -621,7 +621,8 @@ select user_id, notification_id, is_for_online_users, is_for_all_roles, msg_header, msg_description,msg_source,start_Time, end_time, priority, created_date, creator_ID,active_YN from ( - select a.*, b.role_id,b.recv_user_id + select a.notification_ID,a.is_for_online_users,a.is_for_all_roles,a.active_YN, + a.msg_header,a.msg_description,a.msg_source,a.start_time,a.end_time,a.priority,a.creator_ID,a.created_date,b.role_id,b.recv_user_id from ep_notification a, ep_role_notification b where a.notification_id = b.notification_id and (end_time is null || SYSDATE() <= end_time ) @@ -639,7 +640,23 @@ )b where ( - a.role_id = b.role_id||a.recv_user_id=:user_id + a.role_id = b.role_id + ) + union + select :user_id, notification_id, is_for_online_users, is_for_all_roles, msg_header, msg_description,msg_source,start_Time, end_time, priority, created_date, creator_ID,active_YN + from + ( + select a.notification_ID,a.is_for_online_users,a.is_for_all_roles,a.active_YN, + a.msg_header,a.msg_description,a.msg_source,a.start_time,a.end_time,a.priority,a.creator_ID,a.created_date, b.role_id,b.recv_user_id + from ep_notification a, ep_role_notification b + where a.notification_id = b.notification_id + and (end_time is null || SYSDATE() <= end_time ) + and (start_time is null || SYSDATE() >= start_time) + and a.is_for_all_roles = 'N' + ) a + where + ( + a.recv_user_id=:user_id ) union ( @@ -656,9 +673,9 @@ and not exists ( - select * from ep_user_notification m where user_id = :user_id and m.notification_id = a.notification_id and is_viewed = 'Y' + select ID,User_ID,notification_ID,is_viewed,updated_time from ep_user_notification m where user_id = :user_id and m.notification_id = a.notification_id and is_viewed = 'Y' ) - order by priority desc, start_Time desc,created_date desc + order by priority desc, created_date desc,start_Time desc ) t, @@ -682,7 +699,8 @@ <return alias="adminNotificationHistoryVOResult" class="org.openecomp.portalapp.portal.transport.EpNotificationItemVO" /> <![CDATA[ - SELECT + SELECT * from ( +SELECT n.notification_ID AS notificationId, n.is_for_online_users AS isForOnlineUsers, n.is_for_all_roles AS isForAllRoles, @@ -701,7 +719,33 @@ LEFT JOIN fn_user u on u.user_id = n.creator_id WHERE - n.active_YN='Y' order by n.start_time desc + n.active_YN='Y' and msg_source='EP' + + UNION + + SELECT + n.notification_ID AS notificationId, + n.is_for_online_users AS isForOnlineUsers, + n.is_for_all_roles AS isForAllRoles, + n.active_YN AS activeYn, + n.msg_header AS msgHeader, + n.msg_description AS msgDescription, + n.msg_source AS msgSource, + n.start_Time AS startTime, + n.end_time AS endTime, + n.priority, + n.creator_ID AS creatorId, + n.created_date AS createdDate, + u.org_user_id AS loginId + FROM + ep_notification n + LEFT JOIN + fn_user u on u.user_id = n.creator_id + JOIN + ep_role_notification r on r.notification_ID=n.notification_ID + WHERE + n.active_YN='Y' and r.recv_user_id = :user_id and msg_source!='EP' + )n order by n.startTime desc ]]> </sql-query> @@ -757,7 +801,9 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name creator_ID,active_YN from ( - select a.*, b.role_id,CASE WHEN a.creator_ID IS NOT NULL THEN u.org_user_id + select a.notification_ID,a.is_for_online_users,a.is_for_all_roles,a.active_YN, + a.msg_header,a.msg_description,a.msg_source,a.start_time,a.end_time,a.priority,a.creator_ID,a.created_date, + b.role_id,CASE WHEN a.creator_ID IS NOT NULL THEN u.org_user_id ELSE NULL END AS login_id,b.recv_user_id @@ -785,8 +831,38 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name ) b where ( - a.role_id = b.role_id||a.recv_user_id=:user_id + a.role_id = b.role_id ) + UNION + select + :user_id, login_id,notification_id, is_for_online_users, is_for_all_roles, + msg_header, msg_description,msg_source, start_Time, end_time, priority, created_date, + creator_ID,active_YN + from + ( + select a.notification_ID,a.is_for_online_users,a.is_for_all_roles,a.active_YN, + a.msg_header,a.msg_description,a.msg_source,a.start_time,a.end_time,a.priority,a.creator_ID,a.created_date, + b.role_id,CASE WHEN a.creator_ID IS NOT NULL THEN u.org_user_id + + ELSE NULL + END AS login_id,b.recv_user_id + from ep_notification a, ep_role_notification b,fn_user u + where a.notification_id = b.notification_id and (u.user_id=a.creator_ID OR a.creator_ID IS NULL) + and a.is_for_all_roles = 'N' + and ( + (start_time is null and end_time is null and a.created_date >= DATE_ADD(curdate(),INTERVAL-31 DAY)) + or + (start_time is not null and end_time is null and start_time >= DATE_ADD(curdate(),INTERVAL -31 DAY)) + or + (start_time is null and end_time is not null and end_time >= DATE_ADD(curdate(),INTERVAL -31 DAY)) + or + (start_time is not null and end_time is not null and end_time >= DATE_ADD(curdate(),INTERVAL -31 DAY)) + ) + ) a + where + ( + a.recv_user_id=:user_id + ) union ( select @@ -973,6 +1049,20 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name ]]> </sql-query> + <sql-query name="getAppsAdmins"> + <return alias="adminUserApp" class="org.openecomp.portalapp.portal.domain.AdminUserApp" /> + <![CDATA[ + SELECT apps.APP_NAME, apps.APP_ID, user.USER_ID, user.FIRST_NAME, user.LAST_NAME, user.org_user_id FROM fn_user_role userrole INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID INNER JOIN fn_app apps ON apps.APP_ID = userrole.APP_ID WHERE user.active_yn='Y' AND userrole.ROLE_ID = :accountAdminRoleId AND (apps.ENABLED = 'Y' OR apps.APP_ID=1) + ]]> + </sql-query> + + <sql-query name="getPortalAdmins"> + <return alias="portalAdmin" class="org.openecomp.portalapp.portal.transport.PortalAdmin" /> + <![CDATA[ + SELECT u.user_id, u.first_name, u.last_name, u.login_id FROM fn_user u, fn_user_role ur WHERE u.active_yn = 'Y' AND u.user_id = ur.user_id AND ur.role_id= :adminRoleId + ]]> + </sql-query> + <!-- Gets personalized list of enabled and accessible apps for regular user --> <sql-query name="getPersUserApps"> <return alias="persUserApps" class="org.openecomp.portalapp.portal.domain.EPApp" /> @@ -1322,7 +1412,7 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name <![CDATA[ select distinct -- multiple roles yield multiple rows - a.APP_ID as id, a.APP_NAME as name, a.APP_IMAGE_URL as imageUrl, + a.APP_ID as id, a.APP_NAME as name, a.ML_APP_NAME as mlAppName, a.APP_IMAGE_URL as imageUrl, a.APP_DESCRIPTION as description, a.APP_NOTES as notes, a.APP_URL as url, a.APP_ALTERNATE_URL as alternateUrl, IF(a.app_type = '2', TRUE, FALSE) as restricted, @@ -1361,12 +1451,11 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name ]]> </sql-query> - <sql-query name="getAppDetails"> - <return alias="appDetails" class="org.openecomp.portalapp.portal.domain.EPApp" /> + <sql-query name="getMyloginAppDetails"> + <return alias="myloginAppDetails" class="org.openecomp.portalapp.portal.domain.EPApp" /> <![CDATA[ - - SELECT * FROM fn_app where app_name =:appName + SELECT * FROM fn_app where ml_app_name =:appName ; ]]> </sql-query> @@ -1374,7 +1463,6 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name <sql-query name="deleteAccountEndpoint"> <![CDATA[ - DELETE FROM ep_endpoints_basic_auth_account WHERE account_id =:accountId ; ]]> @@ -1382,7 +1470,6 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name <sql-query name="deleteAccountEndpointRecord"> <![CDATA[ - DELETE FROM ep_endpoints_basic_auth_account WHERE account_id =:accountId AND ep_id =:epId ; ]]> @@ -1390,7 +1477,6 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name <sql-query name="deleteEPEndpoint"> <![CDATA[ - DELETE FROM ep_endpoints WHERE id =:epId ; ]]> @@ -1398,7 +1484,6 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name <sql-query name="deleteBasicAuthAccount"> <![CDATA[ - DELETE FROM ep_basic_auth_account WHERE id =:accountId ; ]]> @@ -1408,12 +1493,20 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name <return alias="appRoles" class="org.openecomp.portalapp.portal.domain.EPRole" /> <![CDATA[ - SELECT * FROM fn_role where role_name =:roleName and app_id =:appId ; ]]> </sql-query> - + + <sql-query name="getPortalAppRoles"> + <return alias="appRoles" class="org.openecomp.portalapp.portal.domain.EPRole" /> + + <![CDATA[ + + SELECT * FROM fn_role where role_name =:appRoleName and app_id is null + ; + ]]> + </sql-query> <sql-query name="deleteMicroserviceParameter"> <![CDATA[ @@ -1523,7 +1616,7 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name <![CDATA[ select distinct -- multiple roles yield multiple rows - a.APP_ID as id, a.APP_NAME as name, a.APP_IMAGE_URL as imageUrl, + a.APP_ID as id, a.APP_NAME as name, a.ML_APP_NAME as mlAppName, a.APP_IMAGE_URL as imageUrl, a.APP_DESCRIPTION as description, a.APP_NOTES as notes, a.APP_URL as url, a.APP_ALTERNATE_URL as alternateUrl, IF(a.app_type = '2', TRUE, FALSE) as restricted, @@ -1540,6 +1633,8 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name case -- regular app, user has a role, no personalization when a.OPEN = 'N' and r.ROLE_ID is not null and p.STATUS_CD is null then TRUE + -- regular app, user has role, admin forced a personalization + when a.OPEN = 'N' and r.ROLE_ID is not null and p.STATUS_CD = 'S' then TRUE -- regular app, user has no role, admin forced a personalization when a.OPEN = 'N' and r.ROLE_ID is null and p.STATUS_CD = 'S' then TRUE -- open app and has personalization @@ -1591,5 +1686,30 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name ]]> </sql-query> + + <!--delete the records from ep_notification table when the endtime is more than 3 months--> + <sql-query name="deleteNotificationsFromEpNotificationTable"> + + <![CDATA[ + delete from ep_notification where curdate() >= DATE_ADD(end_time,INTERVAL 3 MONTH) + ]]> + </sql-query> + + + <!-- delete the records from ep_role_notification table when the endtime is more than 3 months --> + <sql-query name="deleteNotificationsFromEpRoleNotificationTable"> + + <![CDATA[ + delete from ep_role_notification where notification_id in (select notification_id from ep_notification where curdate() >= DATE_ADD(end_time,INTERVAL 3 MONTH)) + ]]> + </sql-query> + + <!-- delete the records from ep_user_notification table when the endtime is more than 3 months--> + <sql-query name="deleteNotificationsFromEpUserNotificationTable"> + + <![CDATA[ + delete from ep_user_notification where notification_id in (select notification_id from ep_notification where curdate() >= DATE_ADD(end_time,INTERVAL 3 MONTH)) + ]]> + </sql-query> </hibernate-mapping> diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/Fusion.hbm.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/Fusion.hbm.xml index f6d22a27..c1d6fa17 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/Fusion.hbm.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/Fusion.hbm.xml @@ -1,335 +1,335 @@ -<?xml version="1.0"?>
-<!--
- ================================================================================
- ECOMP Portal
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ================================================================================
- -->
-
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
-
-<!--
-Publishes mappings and queries for EP SDK library features ONLY.
-Portal app mappings and features are in EP.hbm.xml.
--->
-<hibernate-mapping package="org.openecomp.portalsdk.core.domain">
-
- <!-- User class mapping details -->
- <class name="User" table="FN_USER">
- <id name="id" column="user_id" >
- <generator class="native">
- <param name="sequence">seq_fn_user</param>
- </generator>
- </id>
-
- <property name="orgId" column="org_id"/>
- <property name="managerId" column="manager_id"/>
- <property name="firstName" column="first_name"/>
- <property name="middleInitial" column="middle_name"/>
- <property name="lastName" column="last_name"/>
- <property name="phone" column="phone"/>
- <property name="fax" column="fax"/>
- <property name="cellular" column="cellular"/>
- <property name="email" column="email"/>
- <property name="addressId" column="address_id"/>
- <property name="alertMethodCd" column="alert_method_cd"/>
-
- <property name="address1" column="address_line_1"/>
- <property name="address2" column="address_line_2"/>
- <property name="city" column="city"/>
- <property name="state" column="state_cd"/>
- <property name="zipCode" column="zip_code"/>
- <property name="country" column="country_cd"/>
-
- <property name="hrid" column="hrid"/>
- <property name="orgUserId" column="org_user_id"/>
- <property name="orgCode" column="org_code"/>
- <property name="loginId" column="login_id"/>
- <property name="loginPwd" column="login_pwd"/>
- <property name="lastLoginDate" column="last_login_date" type="timestamp"/>
-
- <property name="locationClli" column="location_clli" />
- <property name="orgManagerUserId" column="org_manager_userid" />
- <property name="company" column="company" />
- <property name="department" column="department" />
- <property name="departmentName" column="department_name" />
- <property name="businessUnit" column="business_unit" />
- <property name="businessUnitName" column="business_unit_name" />
- <property name="jobTitle" column="job_title" />
- <property name="siloStatus" column="silo_status" />
- <property name="financialLocCode" column="fin_loc_code" />
-
- <property name="active" column="active_yn" type="yes_no"/>
- <property name="internal" column="is_internal_yn" type="yes_no"/>
-
- <property name="created" type="timestamp" column="created_date" />
- <property name="modified" type="timestamp" column="modified_date" />
-
- <property name="createdId" column="created_id" />
- <property name="modifiedId" column="modified_id" />
- <property name="timeZoneId" column="timezone" />
-
- <set name="userApps" table="FN_USER_ROLE" lazy="false" sort="natural" inverse="true" cascade="all-delete-orphan">
- <key column="user_id"/>
- <one-to-many class="org.openecomp.portalsdk.core.domain.UserApp" />
- </set>
-
- <set name="pseudoRoles" table="FN_USER_PSEUDO_ROLE" lazy="false" sort="natural">
- <key column="user_id"/>
- <many-to-many column="pseudo_role_id" class="org.openecomp.portalsdk.core.domain.Role" />
- </set>
- </class>
-
- <class name="UserApp" table="fn_user_role">
- <composite-id>
- <key-property name="userId" type="long">
- <column name="user_id" precision="11" scale="0" />
- </key-property>
- <key-many-to-one name="app" class="org.openecomp.portalsdk.core.domain.App" column="app_id" />
- <key-many-to-one name="role" class="org.openecomp.portalsdk.core.domain.Role" column="role_id" />
- </composite-id>
- <property name="priority" type="java.lang.Short">
- <column name="priority" precision="4" scale="0" />
- </property>
- </class>
-
- <!-- User App class mapping details -->
- <class name="App" table="fn_app">
- <id name="id" column="app_id"/>
- <property name="name" column="app_name"/>
- <property name="appPassword" column="app_password"/>
- <property name="username" column="app_username"/>
-
- </class>
-
- <!-- User Role class mapping details -->
- <class name="Role" table="FN_ROLE_V">
- <id name="id" column="role_id">
- <generator class="native">
- <param name="sequence">seq_fn_role</param>
- </generator>
- </id>
-
- <property name="name" column="role_name"/>
- <property name="priority" column="priority" />
- <property name="active" column="active_yn" type="yes_no"/>
-
- <set name="roleFunctions" table="FN_ROLE_FUNCTION" lazy="false" sort="natural">
- <key column="role_id"/>
- <many-to-many column="function_cd" class="org.openecomp.portalsdk.core.domain.RoleFunction"/>
- </set>
-
- <set name="childRoles" table="FN_ROLE_COMPOSITE" lazy="false" sort="natural">
- <key column="parent_role_id"/>
- <many-to-many column="child_role_id" class="org.openecomp.portalsdk.core.domain.Role"/>
- </set>
-
- <set name="parentRoles" table="FN_ROLE_COMPOSITE" lazy="false" sort="natural">
- <key column="child_role_id"/>
- <many-to-many column="parent_role_id" class="org.openecomp.portalsdk.core.domain.Role"/>
- </set>
-
- </class>
-
-
-
- <!-- User Role Function class mapping details -->
- <class name="RoleFunction" table="FN_FUNCTION">
- <id name="code" column="function_cd" />
- <property name="name" column="function_name" />
- </class>
-
- <!-- Menu class mapping details -->
- <class name="Menu" table="FN_MENU">
- <id name="id" column="menu_id">
- <generator class="native">
- <param name="sequence">seq_fn_menu</param>
- </generator>
- </id>
-
- <property name="menuLevel" column="level-1"/>
- <property name="label" column="label"/>
- <property name="parentId" column="parent_id"/>
- <property name="action" column="action"/>
- <property name="functionCd" column="function_cd"/>
- <property name="sortOrder" column="sort_order"/>
- <property name="servlet" column="servlet"/>
- <property name="queryString" column="query_string"/>
- <property name="externalUrl" column="external_url"/>
- <property name="target" column="target"/>
- <property name="active" column="active_yn" type="yes_no"/>
- <property name="separator" column="separator_yn" type="yes_no"/>
- <property name="imageSrc" column="image_src" />
- </class>
-
- <class name="MenuData" table="FN_MENU">
- <!-- <id name="id" column="menu_id"/> -->
- <id name="id" column="menu_id">
- <generator class="native">
- <param name="sequence">seq_fn_menu</param>
- </generator>
- </id>
- <property name="label" column="label"/>
- <property name="action" column="action"/>
- <property name="functionCd" column="function_cd"/>
- <property name="sortOrder" column="sort_order"/>
- <property name="servlet" column="servlet"/>
- <property name="queryString" column="query_string"/>
- <property name="externalUrl" column="external_url"/>
- <property name="target" column="target"/>
- <property name="active" column="active_yn" type="yes_no"/>
- <property name="separator" column="separator_yn" type="yes_no"/>
- <property name="imageSrc" column="image_src" />
- <property name="menuSetCode" column="menu_set_cd" />
-
- <many-to-one name="parentMenu" column="parent_id" class="MenuData"/>
-
- <set name="childMenus" lazy="false" sort="natural" inverse="true" where="active_yn = 'Y'">
- <key column="parent_id"/>
- <one-to-many class="MenuData"/>
- </set>
- </class>
-
- <!-- Broadcast Message class mapping details -->
- <class name="BroadcastMessage" table="fn_broadcast_message">
- <id name="id" column="message_id">
- <generator class="native">
- <param name="sequence">seq_fn_broadcast_message</param>
- </generator>
- </id>
- <property name="messageText" column="message_text"/>
- <property name="locationId" column="message_location_id"/>
-
- <property name="startDate" column="broadcast_start_date" type="timestamp"/>
- <property name="endDate" column="broadcast_end_date" type="timestamp"/>
-
- <property name="sortOrder" column="sort_order"/>
- <property name="active" column="active_yn" type="yes_no"/>
-
- <property name="siteCd" column="broadcast_site_cd" />
- </class>
-
- <!-- State Lookup class mapping details -->
- <class name="LuState" table="FN_LU_STATE">
- <id name="abbr" column="state_cd" />
- <property name="state" />
- </class>
-
- <!-- Country Lookup class mapping details -->
- <class name="LuCountry" table="FN_LU_COUNTRY">
- <id name="abbr" column="country_cd" />
- <property name="country" />
- <property name="fullName" column="full_name" />
- <property name="webphoneCountryLabel" column="fullwebphone_country_label_name" />
- </class>
-
- <class name="LuTimeZone" table="FN_LU_TIMEZONE">
- <id name="timezoneId" column="timezone_id" />
- <property name="name" column="timezone_name" />
- <property name="value" column="timezone_value" />
- </class>
-
- <!-- Audit Log class mapping details -->
- <class name="AuditLog" table="fn_audit_log">
- <id name="id" column="log_id">
- <generator class="native">
- <param name="sequence">seq_fn_audit_log</param>
- </generator>
- </id>
- <property name="activityCode" column="activity_cd"/>
- <property name="affectedRecordId" column="affected_record_id" />
- <property name="comments" column="comments" />
- <property name="userId" column="user_id" />
- </class>
-
- <!-- Lookup (id/value bean) class mapping details -->
- <class name="Lookup">
- <composite-id name="nameValueId" class="org.openecomp.portalsdk.core.domain.support.NameValueId">
- <key-property name="val"/>
- <key-property name="lab" />
- </composite-id>
- </class>
-
- <class name="UrlsAccessible" table="V_URL_ACCESS">
- <composite-id name="urlsAccessibleKey" class="org.openecomp.portalsdk.core.domain.UrlsAccessibleKey">
- <key-property name="url" column="url"/>
- <key-property name="functionCd" column="function_cd"/>
- </composite-id>
- </class>
-
- <query name="functionCDlist">
- select distinct functionCd from MenuData
- </query>
-
- <query name="menuData">
- from MenuData where menuSetCode = :menu_set_cd and parentMenu is null
- </query>
- <query name="restrictedUrls">
- FROM UrlsAccessible A where upper(A.urlsAccessibleKey.url) = upper(:current_url)
- </query>
-
- <query name="getUserNameById">
- select firstName, lastName from User where id = :user_id
- </query>
-
- <query name="getUserEmail">
- select email from User where id = :user_id
- </query>
-
- <query name="getAllUsers">
- select id, firstName, lastName from User where active = true order by lastName, firstName
- </query>
-
- <query name="getRoleNameById">
- select name from Role where id = :role_id
- </query>
-
- <query name="getAllRoles">
- select id, name from Role order by name
- </query>
-
- <sql-query name="getBytesPublishedDelivered">
- <return-scalar column="Published" type="java.lang.String"/>
- <return-scalar column="Delivered" type="java.lang.String"/>
- <![CDATA[
- select concat(Round(sum(bytespublished)/(1024*1024*1024*1024), 0), ' Pb') 'Published', concat(Round(sum(bytesdelivered)/(1024*1024*1024*1024), 0), ' Pb') ' Delivered' from kpi_drvolumes where day = (select max(day) from kpi_drvolumes)
- ]]>
- </sql-query>
-
- <sql-query name="getDataRouterFeedStats">
- <return-scalar column="TOTAL_FEEDS" type="java.lang.Long"/>
- <return-scalar column="ACTIVE_FEEDS" type="java.lang.Long"/>
- <return-scalar column="ACTIVE_SUBS" type="java.lang.Long"/>
- <![CDATA[
- SELECT SUM(TOTALFEEDS) TOTAL_FEEDS, SUM(ACTIVEFEEDS) ACTIVE_FEEDS, SUM(ACTIVESUBS) ACTIVE_SUBS FROM kpi_drsumm where day = (select max(day) from kpi_drvolumes)
- ]]>
- </sql-query>
-
- <sql-query name="getLOCStatsCat">
- <![CDATA[
- select CATEGORY1 CATEGORY from demo_kpi_sourcecode_stats group by category1
- ]]>
- </sql-query>
-
- <sql-query name="getLOCStats">
- <![CDATA[
- select sum(total_lines) TOTAL_LINES from demo_kpi_sourcecode_stats group by category1
- ]]>
- </sql-query>
-
-</hibernate-mapping>
+<?xml version="1.0"?> +<!-- + ================================================================================ + ECOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ================================================================================ + --> + +<!DOCTYPE hibernate-mapping PUBLIC + "-//Hibernate/Hibernate Mapping DTD 3.0//EN" + "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> + +<!-- +Publishes mappings and queries for EP SDK library features ONLY. +Portal app mappings and features are in EP.hbm.xml. +--> +<hibernate-mapping package="org.openecomp.portalsdk.core.domain"> + + <!-- User class mapping details --> + <class name="User" table="FN_USER"> + <id name="id" column="user_id" > + <generator class="native"> + <param name="sequence">seq_fn_user</param> + </generator> + </id> + + <property name="orgId" column="org_id"/> + <property name="managerId" column="manager_id"/> + <property name="firstName" column="first_name"/> + <property name="middleInitial" column="middle_name"/> + <property name="lastName" column="last_name"/> + <property name="phone" column="phone"/> + <property name="fax" column="fax"/> + <property name="cellular" column="cellular"/> + <property name="email" column="email"/> + <property name="addressId" column="address_id"/> + <property name="alertMethodCd" column="alert_method_cd"/> + + <property name="address1" column="address_line_1"/> + <property name="address2" column="address_line_2"/> + <property name="city" column="city"/> + <property name="state" column="state_cd"/> + <property name="zipCode" column="zip_code"/> + <property name="country" column="country_cd"/> + + <property name="hrid" column="hrid"/> + <property name="orgUserId" column="org_user_id"/> + <property name="orgCode" column="org_code"/> + <property name="loginId" column="login_id"/> + <property name="loginPwd" column="login_pwd"/> + <property name="lastLoginDate" column="last_login_date" type="timestamp"/> + + <property name="locationClli" column="location_clli" /> + <property name="orgManagerUserId" column="org_manager_userid" /> + <property name="company" column="company" /> + <property name="department" column="department" /> + <property name="departmentName" column="department_name" /> + <property name="businessUnit" column="business_unit" /> + <property name="businessUnitName" column="business_unit_name" /> + <property name="jobTitle" column="job_title" /> + <property name="siloStatus" column="silo_status" /> + <property name="financialLocCode" column="fin_loc_code" /> + + <property name="active" column="active_yn" type="yes_no"/> + <property name="internal" column="is_internal_yn" type="yes_no"/> + + <property name="created" type="timestamp" column="created_date" /> + <property name="modified" type="timestamp" column="modified_date" /> + + <property name="createdId" column="created_id" /> + <property name="modifiedId" column="modified_id" /> + <property name="timeZoneId" column="timezone" /> + + <set name="userApps" table="FN_USER_ROLE" lazy="false" sort="natural" inverse="true" cascade="all-delete-orphan"> + <key column="user_id"/> + <one-to-many class="org.openecomp.portalsdk.core.domain.UserApp" /> + </set> + + <set name="pseudoRoles" table="FN_USER_PSEUDO_ROLE" lazy="false" sort="natural"> + <key column="user_id"/> + <many-to-many column="pseudo_role_id" class="org.openecomp.portalsdk.core.domain.Role" /> + </set> + </class> + + <class name="UserApp" table="fn_user_role"> + <composite-id> + <key-property name="userId" type="long"> + <column name="user_id" precision="11" scale="0" /> + </key-property> + <key-many-to-one name="app" class="org.openecomp.portalsdk.core.domain.App" column="app_id" /> + <key-many-to-one name="role" class="org.openecomp.portalsdk.core.domain.Role" column="role_id" /> + </composite-id> + <property name="priority" type="java.lang.Short"> + <column name="priority" precision="4" scale="0" /> + </property> + </class> + + <!-- User App class mapping details --> + <class name="App" table="fn_app"> + <id name="id" column="app_id"/> + <property name="name" column="app_name"/> + <property name="appPassword" column="app_password"/> + <property name="username" column="app_username"/> + + </class> + + <!-- User Role class mapping details --> + <class name="Role" table="FN_ROLE_V"> + <id name="id" column="role_id"> + <generator class="native"> + <param name="sequence">seq_fn_role</param> + </generator> + </id> + + <property name="name" column="role_name"/> + <property name="priority" column="priority" /> + <property name="active" column="active_yn" type="yes_no"/> + + <set name="roleFunctions" table="FN_ROLE_FUNCTION" lazy="false" sort="natural"> + <key column="role_id"/> + <many-to-many column="function_cd" class="org.openecomp.portalsdk.core.domain.RoleFunction"/> + </set> + + <set name="childRoles" table="FN_ROLE_COMPOSITE" lazy="false" sort="natural"> + <key column="parent_role_id"/> + <many-to-many column="child_role_id" class="org.openecomp.portalsdk.core.domain.Role"/> + </set> + + <set name="parentRoles" table="FN_ROLE_COMPOSITE" lazy="false" sort="natural"> + <key column="child_role_id"/> + <many-to-many column="parent_role_id" class="org.openecomp.portalsdk.core.domain.Role"/> + </set> + + </class> + + + + <!-- User Role Function class mapping details --> + <class name="RoleFunction" table="FN_FUNCTION"> + <id name="code" column="function_cd" /> + <property name="name" column="function_name" /> + </class> + + <!-- Menu class mapping details --> + <class name="Menu" table="FN_MENU"> + <id name="id" column="menu_id"> + <generator class="native"> + <param name="sequence">seq_fn_menu</param> + </generator> + </id> + + <property name="menuLevel" column="level-1"/> + <property name="label" column="label"/> + <property name="parentId" column="parent_id"/> + <property name="action" column="action"/> + <property name="functionCd" column="function_cd"/> + <property name="sortOrder" column="sort_order"/> + <property name="servlet" column="servlet"/> + <property name="queryString" column="query_string"/> + <property name="externalUrl" column="external_url"/> + <property name="target" column="target"/> + <property name="active" column="active_yn" type="yes_no"/> + <property name="separator" column="separator_yn" type="yes_no"/> + <property name="imageSrc" column="image_src" /> + </class> + + <class name="MenuData" table="FN_MENU"> + <!-- <id name="id" column="menu_id"/> --> + <id name="id" column="menu_id"> + <generator class="native"> + <param name="sequence">seq_fn_menu</param> + </generator> + </id> + <property name="label" column="label"/> + <property name="action" column="action"/> + <property name="functionCd" column="function_cd"/> + <property name="sortOrder" column="sort_order"/> + <property name="servlet" column="servlet"/> + <property name="queryString" column="query_string"/> + <property name="externalUrl" column="external_url"/> + <property name="target" column="target"/> + <property name="active" column="active_yn" type="yes_no"/> + <property name="separator" column="separator_yn" type="yes_no"/> + <property name="imageSrc" column="image_src" /> + <property name="menuSetCode" column="menu_set_cd" /> + + <many-to-one name="parentMenu" column="parent_id" class="MenuData"/> + + <set name="childMenus" lazy="false" sort="natural" inverse="true" where="active_yn = 'Y'"> + <key column="parent_id"/> + <one-to-many class="MenuData"/> + </set> + </class> + + <!-- Broadcast Message class mapping details --> + <class name="BroadcastMessage" table="fn_broadcast_message"> + <id name="id" column="message_id"> + <generator class="native"> + <param name="sequence">seq_fn_broadcast_message</param> + </generator> + </id> + <property name="messageText" column="message_text"/> + <property name="locationId" column="message_location_id"/> + + <property name="startDate" column="broadcast_start_date" type="timestamp"/> + <property name="endDate" column="broadcast_end_date" type="timestamp"/> + + <property name="sortOrder" column="sort_order"/> + <property name="active" column="active_yn" type="yes_no"/> + + <property name="siteCd" column="broadcast_site_cd" /> + </class> + + <!-- State Lookup class mapping details --> + <class name="LuState" table="FN_LU_STATE"> + <id name="abbr" column="state_cd" /> + <property name="state" /> + </class> + + <!-- Country Lookup class mapping details --> + <class name="LuCountry" table="FN_LU_COUNTRY"> + <id name="abbr" column="country_cd" /> + <property name="country" /> + <property name="fullName" column="full_name" /> + <property name="webphoneCountryLabel" column="fullwebphone_country_label_name" /> + </class> + + <class name="LuTimeZone" table="FN_LU_TIMEZONE"> + <id name="timezoneId" column="timezone_id" /> + <property name="name" column="timezone_name" /> + <property name="value" column="timezone_value" /> + </class> + + <!-- Audit Log class mapping details --> + <class name="AuditLog" table="fn_audit_log"> + <id name="id" column="log_id"> + <generator class="native"> + <param name="sequence">seq_fn_audit_log</param> + </generator> + </id> + <property name="activityCode" column="activity_cd"/> + <property name="affectedRecordId" column="affected_record_id" /> + <property name="comments" column="comments" /> + <property name="userId" column="user_id" /> + </class> + + <!-- Lookup (id/value bean) class mapping details --> + <class name="Lookup"> + <composite-id name="nameValueId" class="org.openecomp.portalsdk.core.domain.support.NameValueId"> + <key-property name="val"/> + <key-property name="lab" /> + </composite-id> + </class> + + <class name="UrlsAccessible" table="V_URL_ACCESS"> + <composite-id name="urlsAccessibleKey" class="org.openecomp.portalsdk.core.domain.UrlsAccessibleKey"> + <key-property name="url" column="url"/> + <key-property name="functionCd" column="function_cd"/> + </composite-id> + </class> + + <query name="functionCDlist"> + select distinct functionCd from MenuData + </query> + + <query name="menuData"> + from MenuData where menuSetCode = :menu_set_cd and parentMenu is null + </query> + <query name="restrictedUrls"> + FROM UrlsAccessible A where upper(A.urlsAccessibleKey.url) = upper(:current_url) + </query> + + <query name="getUserNameById"> + select firstName, lastName from User where id = :user_id + </query> + + <query name="getUserEmail"> + select email from User where id = :user_id + </query> + + <query name="getAllUsers"> + select id, firstName, lastName from User where active = true order by lastName, firstName + </query> + + <query name="getRoleNameById"> + select name from Role where id = :role_id + </query> + + <query name="getAllRoles"> + select id, name from Role order by name + </query> + + <sql-query name="getBytesPublishedDelivered"> + <return-scalar column="Published" type="java.lang.String"/> + <return-scalar column="Delivered" type="java.lang.String"/> + <![CDATA[ + select concat(Round(sum(bytespublished)/(1024*1024*1024*1024), 0), ' Pb') 'Published', concat(Round(sum(bytesdelivered)/(1024*1024*1024*1024), 0), ' Pb') ' Delivered' from kpi_drvolumes where day = (select max(day) from kpi_drvolumes) + ]]> + </sql-query> + + <sql-query name="getDataRouterFeedStats"> + <return-scalar column="TOTAL_FEEDS" type="java.lang.Long"/> + <return-scalar column="ACTIVE_FEEDS" type="java.lang.Long"/> + <return-scalar column="ACTIVE_SUBS" type="java.lang.Long"/> + <![CDATA[ + SELECT SUM(TOTALFEEDS) TOTAL_FEEDS, SUM(ACTIVEFEEDS) ACTIVE_FEEDS, SUM(ACTIVESUBS) ACTIVE_SUBS FROM kpi_drsumm where day = (select max(day) from kpi_drvolumes) + ]]> + </sql-query> + + <sql-query name="getLOCStatsCat"> + <![CDATA[ + select CATEGORY1 CATEGORY from demo_kpi_sourcecode_stats group by category1 + ]]> + </sql-query> + + <sql-query name="getLOCStats"> + <![CDATA[ + select sum(total_lines) TOTAL_LINES from demo_kpi_sourcecode_stats group by category1 + ]]> + </sql-query> + +</hibernate-mapping> diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/Workflow.hbm.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/Workflow.hbm.xml index 9a853e7f..b1ea7a4a 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/Workflow.hbm.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/Workflow.hbm.xml @@ -1,48 +1,48 @@ -<?xml version="1.0"?>
-<!--
- ================================================================================
- ECOMP Portal
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ================================================================================
- -->
-
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
-
-<hibernate-mapping package="org.openecomp.portalsdk.workflow.domain">
-
-
- <!-- WorkflowSchedule mapping details -->
- <class name="WorkflowSchedule" table="fn_schedule_workflows">
- <id name="id" column="id_schedule_workflows">
- <generator class="native">
- </generator>
- </id>
-
- <property name="serverUrl" column="workflow_server_url"/>
- <property name="workflowKey" column="workflow_key"/>
- <property name="arguments" column="workflow_arguments"/>
- <property name="cronDetails" column="startDateTimeCron"/>
- <property name="startDateTime" column="start_date_time"/>
- <property name="endDateTime" column="endDateTime"/>
- <property name="recurrence" column="recurrence"/>
-
- </class>
-
-
-
-</hibernate-mapping>
+<?xml version="1.0"?> +<!-- + ================================================================================ + ECOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ================================================================================ + --> + +<!DOCTYPE hibernate-mapping PUBLIC + "-//Hibernate/Hibernate Mapping DTD 3.0//EN" + "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> + +<hibernate-mapping package="org.openecomp.portalsdk.workflow.domain"> + + + <!-- WorkflowSchedule mapping details --> + <class name="WorkflowSchedule" table="fn_schedule_workflows"> + <id name="id" column="id_schedule_workflows"> + <generator class="native"> + </generator> + </id> + + <property name="serverUrl" column="workflow_server_url"/> + <property name="workflowKey" column="workflow_key"/> + <property name="arguments" column="workflow_arguments"/> + <property name="cronDetails" column="startDateTimeCron"/> + <property name="startDateTime" column="start_date_time"/> + <property name="endDateTime" column="endDateTime"/> + <property name="recurrence" column="recurrence"/> + + </class> + + + +</hibernate-mapping> diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/error.jsp b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/error.jsp index 0505b68c..84d7223b 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/error.jsp +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/error.jsp @@ -1,20 +1,20 @@ -<%--
- ================================================================================
- ECOMP Portal
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ================================================================================
- --%>
-${errMsg}
+<%-- + ================================================================================ + ECOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ================================================================================ + --%> +${errMsg} diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/index.jsp b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/index.jsp index 39437e78..3ead17cc 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/index.jsp +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/index.jsp @@ -1,21 +1,21 @@ -<%--
- ================================================================================
- ECOMP Portal
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ================================================================================
- --%>
-<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
-<c:redirect url="/index.html"/>
+<%-- + ================================================================================ + ECOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ================================================================================ + --%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<c:redirect url="/index.html"/> diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login.jsp b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login.jsp index e10ba624..d90704c3 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login.jsp +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login.jsp @@ -1,120 +1,120 @@ -<%--
- ================================================================================
- ECOMP Portal
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ================================================================================
- --%>
-<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
-<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
-<%@ page import="java.net.URLEncoder" %>
-<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties" %>
-<!DOCTYPE html>
-<html ng-app="abs">
- <head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
- <link rel="stylesheet" type="text/css" href="static/ebz/fn-ebz.css" >
- <link rel="stylesheet" type="text/css" href="static/ebz/sandbox/styles/style.css" >
- <script src="static/js/jquery-1.10.2.js" type="text/javascript"></script>
- <script src= "static/ebz/angular_js/angular.js"></script>
- <script src= "static/ebz/angular_js/angular-sanitize.js"></script>
- <script src= "static/ebz/angular_js/att_abs_tpls.js"></script>
- <script src= "static/ebz/angular_js/app.js"></script>
- <script src= "static/ebz/angular_js/gestures.js"></script>
- <script src="static/js/modalService.js"></script>
- <style>
- .terms {
- font-family: Verdana,Arial,Helvetica, sans-serif;
- font-size: 12px;
- }
- </style>
- </head>
- <body style="padding-top: 15px;display: none;">
- <%
- String returnUrl = request.getParameter("returnUrl");
- String redirectUrl = request.getParameter("redirectUrl");
- returnUrl = ((returnUrl == null) ? (request.isSecure() ?"https://":"http://") + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/process_csp" + "?redirectUrl=" + redirectUrl: URLEncoder.encode(returnUrl));
- %>
- <c:set var="returnUrl" value="<%=returnUrl%>"/>
- <c:set var="cspLoginUrl" value="<%=SystemProperties.getProperty(SystemProperties.CSP_LOGIN_URL)%>"/>
- <div ng-controller="loginController">
- <!-- AT&T Logo -->
- <div style="position: fixed; left:15px; top:15px; ">
- <img src="static/fusion/images/logo_att_header.jpg" alt="AT&T" />
- </div>
- <div class="centered style="-webkit-transform: translateZ(0);background:white, z-index:0;">
- <div class="centered" style="height:15px">
- <div class="centered">
- <div align="center" style="display: block;margin-left: auto;margin-right: auto;width: 100%;">
- <img src="static/fusion/images/ecomp-login.jpg" height="250"/>
- <br>
- <font class="headerText">
- <a id="goUrl" href="${cspLoginUrl}"><b>Click here to login</b></a>
- </font>
- </div>
- <br />
- <br />
- </div>
- </div>
- <br/><br/><br/><br/><br/><br/><br/><br/>
- <div id="footer" style="margin-top:300px">
- <div style="margin-left:auto;margin-right:auto;text-align: center;">
- <p><font class="terms">
- <b>Warning:</b> This system is restricted to AT&T authorized users for business purposes.
- Unauthorized access is a violation of the law.
- <br>
- This service may be monitored for administrative and security reasons.
- By proceeding, you consent to this monitoring.
- </font></p>
- </div>
- <div class="terms" style="text-align: center;">
- <a target="_top" href="http://www.att.com/terms/">Terms and Conditions</a> |
- <a target="_top" href="http://www.att.com/privacy/">Privacy Policy</a>.
- <br><span>© 2017 AT&T. All rights reserved.</span>
- </div>
- </div>
- </div>
- </body>
-<script>
- function getParameterByName(name, url) {
- if (!url) url = window.location.href;
- name = name.replace(/[\[\]]/g, "\\$&");
- var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
- results = regex.exec(url);
- if (!results) return '';
- if (!results[2]) return '';
- return (results[2].replace(/\+/g, " "));
- }
-
- var winHref = window.location.href;
- var appPathIndex = winHref.substring(0,winHref.lastIndexOf(".htm")).lastIndexOf("/");
- var goUrl =winHref.substring(0,appPathIndex+1) + "process_csp" + "?redirectUrl=" + getParameterByName('redirectUrl') ;
- document.getElementById("goUrl").href = document.getElementById("goUrl").href + goUrl;
- if(getParameterByName('skipClick')=="Yes"){
- document.getElementById("goUrl").click();
- }else{
- $("body").show();
- }
-
-</script>
-<script>
-app.controller("loginController", function ($scope) {
-
-});
-</script>
-</html>
+<%-- + ================================================================================ + ECOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ================================================================================ + --%> +<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ page import="java.net.URLEncoder" %> +<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties" %> +<!DOCTYPE html> +<html ng-app="abs"> + <head> + <meta charset="utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> + <link rel="stylesheet" type="text/css" href="static/ebz/fn-ebz.css" > + <link rel="stylesheet" type="text/css" href="static/ebz/sandbox/styles/style.css" > + <script src="static/js/jquery-1.10.2.js" type="text/javascript"></script> + <script src= "static/ebz/angular_js/angular.js"></script> + <script src= "static/ebz/angular_js/angular-sanitize.js"></script> + <script src= "static/ebz/angular_js/att_abs_tpls.js"></script> + <script src= "static/ebz/angular_js/app.js"></script> + <script src= "static/ebz/angular_js/gestures.js"></script> + <script src="static/js/modalService.js"></script> + <style> + .terms { + font-family: Verdana,Arial,Helvetica, sans-serif; + font-size: 12px; + } + </style> + </head> + <body style="padding-top: 15px;display: none;"> + <% + String returnUrl = request.getParameter("returnUrl"); + String redirectUrl = request.getParameter("redirectUrl"); + returnUrl = ((returnUrl == null) ? (request.isSecure() ?"https://":"http://") + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/process_csp" + "?redirectUrl=" + redirectUrl: URLEncoder.encode(returnUrl)); + %> + <c:set var="returnUrl" value="<%=returnUrl%>"/> + <c:set var="cspLoginUrl" value="<%=SystemProperties.getProperty(SystemProperties.CSP_LOGIN_URL)%>"/> + <div ng-controller="loginController"> + <!-- AT&T Logo --> + <div style="position: fixed; left:15px; top:15px; "> + <img src="static/fusion/images/logo_att_header.jpg" alt="AT&T" /> + </div> + <div class="centered style="-webkit-transform: translateZ(0);background:white, z-index:0;"> + <div class="centered" style="height:15px"> + <div class="centered"> + <div align="center" style="display: block;margin-left: auto;margin-right: auto;width: 100%;"> + <img src="static/fusion/images/ecomp-login.jpg" height="250"/> + <br> + <font class="headerText"> + <a id="goUrl" href="${cspLoginUrl}"><b>Click here to login</b></a> + </font> + </div> + <br /> + <br /> + </div> + </div> + <br/><br/><br/><br/><br/><br/><br/><br/> + <div id="footer" style="margin-top:300px"> + <div style="margin-left:auto;margin-right:auto;text-align: center;"> + <p><font class="terms"> + <b>Warning:</b> This system is restricted to AT&T authorized users for business purposes. + Unauthorized access is a violation of the law. + <br> + This service may be monitored for administrative and security reasons. + By proceeding, you consent to this monitoring. + </font></p> + </div> + <div class="terms" style="text-align: center;"> + <a target="_top" href="http://www.att.com/terms/">Terms and Conditions</a> | + <a target="_top" href="http://www.att.com/privacy/">Privacy Policy</a>. + <br><span>© 2017 AT&T. All rights reserved.</span> + </div> + </div> + </div> + </body> +<script> + function getParameterByName(name, url) { + if (!url) url = window.location.href; + name = name.replace(/[\[\]]/g, "\\$&"); + var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), + results = regex.exec(url); + if (!results) return ''; + if (!results[2]) return ''; + return (results[2].replace(/\+/g, " ")); + } + + var winHref = window.location.href; + var appPathIndex = winHref.substring(0,winHref.lastIndexOf(".htm")).lastIndexOf("/"); + var goUrl =winHref.substring(0,appPathIndex+1) + "process_csp" + "?redirectUrl=" + getParameterByName('redirectUrl') ; + document.getElementById("goUrl").href = document.getElementById("goUrl").href + goUrl; + if(getParameterByName('skipClick')=="Yes"){ + document.getElementById("goUrl").click(); + }else{ + $("body").show(); + } + +</script> +<script> +app.controller("loginController", function ($scope) { + +}); +</script> +</html> diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login_external.jsp b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login_external.jsp index fe5eef06..94c2f55e 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login_external.jsp +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login_external.jsp @@ -1,162 +1,162 @@ -<%--
- ================================================================================
- ECOMP Portal
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ================================================================================
- --%>
-<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
-<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
-<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
-<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties" %>
-<c:set var="title" value="Login" />
-<c:set var="isMobileEnabled"
- value="<%=(SystemProperties.getProperty(SystemProperties.MOBILE_ENABLE)!= null && SystemProperties.getProperty(SystemProperties.MOBILE_ENABLE).trim().equals(\"true\"))%>" />
-
-<!DOCTYPE html>
-<html ng-app="abs">
- <head>
- <title>
- Login
- </title>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
- <link rel="stylesheet" type="text/css" href="static/ebz/fn-ebz.css" >
- <link rel="stylesheet" type="text/css" href="static/fusion/css/jquery-ui.css">
- <script src="static/js/jquery-1.10.2.js" type="text/javascript"></script>
- <script src= "static/ebz/angular_js/angular.js"></script>
- <script src= "static/ebz/angular_js/angular-sanitize.js"></script>
- <script src= "static/ebz/angular_js/att_abs_tpls.js"></script>
- <script src= "static/ebz/angular_js/app.js"></script>
- <script src= "static/ebz/angular_js/gestures.js"></script>
- <script src="static/js/modalService.js"></script>
- <style>
- .terms {
- font-family: Verdana,Arial,Helvetica, sans-serif;
- font-size: 9px;
- }
- </style>
- </head>
- <body style="padding-top: 15px;">
- <div ng-controller="externalLoginController">
- <!-- Remove Video -----
- <div style="position: fixed; left: -25%; top: -25%; height: 150%; width: 150%; z-index:-1;">
- <video src="http://www.business.att.com/content/mixedmedia/network-on-demand.mp4" autoplay="true" defaultmuted="true" muted="true" height="100%" width="100%"></video>
- </div>
- -->
- <div style="position: fixed; left:15px; top:15px;z-index:-1;">
- <img src="static/fusion/images/logo_att_header.jpg" alt="AT&T" />
- </div>
- <div class="centered style="-webkit-transform: translateZ(0);background:white, z-index:0;">
- <div align="center" id="errorInfo" style="display:none;float:left;font-size:12px;margin-left:5px"><span style="color:red">Invaild username or password, Please try again</span></div>
- <br/>
- <div align="center" style="margin-left:auto;margin-right:auto;width:40%;padding:6px;background-color:white">
- <img src="static/fusion/images/ecomp-login.jpg"/><span style=" color: #c97d25; font-size: 56px; position: relative; text-shadow: 3px 0 #8F9477, 0 2px #d7e7dc, 4px 0 #72b7b2, 0 0px black; top:-144px; left: -26px; font-weight: bold; font-style: italic; font-family:sans-serif">Portal</span>
- <h2> ECOMP Portal </h2>
- <label>
- <label class="form-field__label">Login ID:</label>
- </label>
- <input type="text" class="fn-ebz-text" ng-model="loginId" style="width: 140px;height:25px;border-radius:7px;font-size:18px;padding-left:5px;"
- maxlength="30" />
- <br/>
- <br/>
- <label > Password:</label>
- <input type="password" class="span3" ng-model="password" style="width: 140px;height:25px;border-radius:7px;font-size:18px;padding-left:5px;"
- maxlength="30" onkeydown="if (event.keyCode == 13) document.getElementById('loginBtn').click()"/>
- <br />
- <br />
-
- <input id="loginBtn" type="image" ng-click="loginExternal();" src="static/fusion/images/login_button.gif" alt="Login" />
- <br>
- </div>
- </div>
- <br/><br/><br/><br/><br/><br/><br/>
- <div id="footer">
- <div style="margin-left:auto;margin-right:auto;text-align: center;">
- <p><font class="terms">
- <b>Warning:</b> This system is restricted to AT&T authorized users for business purposes. Unauthorized access is a violation of the law. This service may be monitored for administrative and security reasons. By proceeding, you consent to this monitoring.
- </font></p>
- </div>
- <div class="terms" align="left">
- <a target="_top" href="http://www.att.com/terms/">Terms and Conditions</a> | <a target="_top" href="http://www.att.com/privacy/">Privacy Policy</a>.<br><span>© 2016 AT&T. All rights reserved.</span>
- </div>
- </div>
- </div>
- </body>
-<script>
-app.controller("externalLoginController", function ($scope) {
- // Table Data
-
- $scope.viewPerPage = 200;
- $scope.currentPage = 2;
- $scope.totalPage;
- $scope.searchCategory = "";
- $scope.searchString = "";
- $scope.loginId="";
- $scope.password="";
- $scope.loginError=true;
- $scope.viewPerPage = 200;
- $scope.currentPage = 2;
- $scope.totalPage;
- $scope.searchCategory = "";
- $scope.searchString = "";
- $scope.loginId="";
- $scope.password="";
-
-
- $scope.loginExternal = function() {
-
- $.ajax({
- url: "login_external/login?"+"loginId="+$scope.loginId+"&password="+$scope.password,
- type : "POST",
- success:function (response){
- if(response=="success"){
- window.location.href = 'welcome.htm';
- }else{
- $("#errorInfo").show();
- }
- },
- error:function( jqXHR, status,error ){
- $("#errorInfo").show();
- }
-
- });
-
- };
-
-
- /**
- $scope.loginExternal = function() {
-
-
- var redirectUrl = "login_external/login";
- var form = $('<form action="' + redirectUrl + '" method="post">' +
- '<input type="hidden" name="loginId" value='+$scope.loginId+' />' +
- '<input type="hidden" name="password" value='+$scope.password+' />' +
- '</form>');
-
- $('body').append(form);
- $(form).submit();
-
-
- };
- */
-
-});
-</script>
-
-</html>
+<%-- + ================================================================================ + ECOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ================================================================================ + --%> +<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> +<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties" %> +<c:set var="title" value="Login" /> +<c:set var="isMobileEnabled" + value="<%=(SystemProperties.getProperty(SystemProperties.MOBILE_ENABLE)!= null && SystemProperties.getProperty(SystemProperties.MOBILE_ENABLE).trim().equals(\"true\"))%>" /> + +<!DOCTYPE html> +<html ng-app="abs"> + <head> + <title> + Login + </title> + <meta charset="utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> + <link rel="stylesheet" type="text/css" href="static/ebz/fn-ebz.css" > + <link rel="stylesheet" type="text/css" href="static/fusion/css/jquery-ui.css"> + <script src="static/js/jquery-1.10.2.js" type="text/javascript"></script> + <script src= "static/ebz/angular_js/angular.js"></script> + <script src= "static/ebz/angular_js/angular-sanitize.js"></script> + <script src= "static/ebz/angular_js/att_abs_tpls.js"></script> + <script src= "static/ebz/angular_js/app.js"></script> + <script src= "static/ebz/angular_js/gestures.js"></script> + <script src="static/js/modalService.js"></script> + <style> + .terms { + font-family: Verdana,Arial,Helvetica, sans-serif; + font-size: 9px; + } + </style> + </head> + <body style="padding-top: 15px;"> + <div ng-controller="externalLoginController"> + <!-- Remove Video ----- + <div style="position: fixed; left: -25%; top: -25%; height: 150%; width: 150%; z-index:-1;"> + <video src="http://www.business.att.com/content/mixedmedia/network-on-demand.mp4" autoplay="true" defaultmuted="true" muted="true" height="100%" width="100%"></video> + </div> + --> + <div style="position: fixed; left:15px; top:15px;z-index:-1;"> + <img src="static/fusion/images/logo_att_header.jpg" alt="AT&T" /> + </div> + <div class="centered style="-webkit-transform: translateZ(0);background:white, z-index:0;"> + <div align="center" id="errorInfo" style="display:none;float:left;font-size:12px;margin-left:5px"><span style="color:red">Invaild username or password, Please try again</span></div> + <br/> + <div align="center" style="margin-left:auto;margin-right:auto;width:40%;padding:6px;background-color:white"> + <img src="static/fusion/images/ecomp-login.jpg"/><span style=" color: #c97d25; font-size: 56px; position: relative; text-shadow: 3px 0 #8F9477, 0 2px #d7e7dc, 4px 0 #72b7b2, 0 0px black; top:-144px; left: -26px; font-weight: bold; font-style: italic; font-family:sans-serif">Portal</span> + <h2> ECOMP Portal </h2> + <label> + <label class="form-field__label">Login ID:</label> + </label> + <input type="text" class="fn-ebz-text" ng-model="loginId" style="width: 140px;height:25px;border-radius:7px;font-size:18px;padding-left:5px;" + maxlength="30" /> + <br/> + <br/> + <label > Password:</label> + <input type="password" class="span3" ng-model="password" style="width: 140px;height:25px;border-radius:7px;font-size:18px;padding-left:5px;" + maxlength="30" onkeydown="if (event.keyCode == 13) document.getElementById('loginBtn').click()"/> + <br /> + <br /> + + <input id="loginBtn" type="image" ng-click="loginExternal();" src="static/fusion/images/login_button.gif" alt="Login" /> + <br> + </div> + </div> + <br/><br/><br/><br/><br/><br/><br/> + <div id="footer"> + <div style="margin-left:auto;margin-right:auto;text-align: center;"> + <p><font class="terms"> + <b>Warning:</b> This system is restricted to AT&T authorized users for business purposes. Unauthorized access is a violation of the law. This service may be monitored for administrative and security reasons. By proceeding, you consent to this monitoring. + </font></p> + </div> + <div class="terms" align="left"> + <a target="_top" href="http://www.att.com/terms/">Terms and Conditions</a> | <a target="_top" href="http://www.att.com/privacy/">Privacy Policy</a>.<br><span>© 2016 AT&T. All rights reserved.</span> + </div> + </div> + </div> + </body> +<script> +app.controller("externalLoginController", function ($scope) { + // Table Data + + $scope.viewPerPage = 200; + $scope.currentPage = 2; + $scope.totalPage; + $scope.searchCategory = ""; + $scope.searchString = ""; + $scope.loginId=""; + $scope.password=""; + $scope.loginError=true; + $scope.viewPerPage = 200; + $scope.currentPage = 2; + $scope.totalPage; + $scope.searchCategory = ""; + $scope.searchString = ""; + $scope.loginId=""; + $scope.password=""; + + + $scope.loginExternal = function() { + + $.ajax({ + url: "login_external/login?"+"loginId="+$scope.loginId+"&password="+$scope.password, + type : "POST", + success:function (response){ + if(response=="success"){ + window.location.href = 'welcome.htm'; + }else{ + $("#errorInfo").show(); + } + }, + error:function( jqXHR, status,error ){ + $("#errorInfo").show(); + } + + }); + + }; + + + /** + $scope.loginExternal = function() { + + + var redirectUrl = "login_external/login"; + var form = $('<form action="' + redirectUrl + '" method="post">' + + '<input type="hidden" name="loginId" value='+$scope.loginId+' />' + + '<input type="hidden" name="password" value='+$scope.password+' />' + + '</form>'); + + $('body').append(form); + $(form).submit(); + + + }; + */ + +}); +</script> + +</html> diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/web.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/web.xml index 9c89f942..2aa2d26f 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/web.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/web.xml @@ -1,56 +1,56 @@ -<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ================================================================================
- ECOMP Portal
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ================================================================================
- -->
-
-<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
- <display-name>fusion</display-name>
-
- <!--
- <context-param>
- <param-name>log4jConfigLocation</param-name>
- <param-value>/WEB-INF/conf/log4j.properties</param-value>
- </context-param>
-
- <listener>
- <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
- </listener>
- -->
-
- <!-- The Portal app can function on a HA cluster -->
- <distributable/>
-
- <filter>
- <filter-name>CorsFilter</filter-name>
- <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
- <init-param>
- <param-name>cors.allowed.methods</param-name>
- <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
- </init-param>
- <init-param>
- <param-name>cors.allowed.headers</param-name>
- <param-value>EPService,JSESSIONID,X-ECOMP-RequestID,X-Widgets-Type,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
- </init-param>
- </filter>
-
- <filter-mapping>
- <filter-name>CorsFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-</web-app>
+<?xml version="1.0" encoding="UTF-8"?> +<!-- + ================================================================================ + ECOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ================================================================================ + --> + +<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> + <display-name>fusion</display-name> + + <!-- + <context-param> + <param-name>log4jConfigLocation</param-name> + <param-value>/WEB-INF/conf/log4j.properties</param-value> + </context-param> + + <listener> + <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> + </listener> + --> + + <!-- The Portal app can function on a HA cluster --> + <distributable/> + + <filter> + <filter-name>CorsFilter</filter-name> + <filter-class>org.apache.catalina.filters.CorsFilter</filter-class> + <init-param> + <param-name>cors.allowed.methods</param-name> + <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value> + </init-param> + <init-param> + <param-name>cors.allowed.headers</param-name> + <param-value>EPService,JSESSIONID,X-ECOMP-RequestID,X-Widgets-Type,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value> + </init-param> + </filter> + + <filter-mapping> + <filter-name>CorsFilter</filter-name> + <url-pattern>/*</url-pattern> + </filter-mapping> +</web-app> diff --git a/ecomp-portal-BE-common/src/main/webapp/index.jsp b/ecomp-portal-BE-common/src/main/webapp/index.jsp index dfff393d..c8f0a6dd 100644 --- a/ecomp-portal-BE-common/src/main/webapp/index.jsp +++ b/ecomp-portal-BE-common/src/main/webapp/index.jsp @@ -1,34 +1,34 @@ -<%--
- ================================================================================
- ECOMP Portal
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property
- ================================================================================
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ================================================================================
- --%>
-<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
-
-<%-- Redirected because we can't set the welcome page to a virtual URL. --%>
-<%-- <c:redirect url="/login.htm"/>
- --%>
- <html>
- <head>
- <title>ecompportal-BE index.jsp</title>
- </head>
- <body>
- <h2>ECOMP Portal Core</h2>
- This is the ecompportal-BE application, page index.jsp.
- </body>
- </html>
-
+<%-- + ================================================================================ + ECOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ================================================================================ + --%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + +<%-- Redirected because we can't set the welcome page to a virtual URL. --%> +<%-- <c:redirect url="/login.htm"/> + --%> + <html> + <head> + <title>ecompportal-BE index.jsp</title> + </head> + <body> + <h2>ECOMP Portal Core</h2> + This is the ecompportal-BE application, page index.jsp. + </body> + </html> + |