Changes made to fix left menu routing
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / music / util / MusicUtil.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright © 2018 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.music.util;
39
40 import java.io.ByteArrayInputStream;
41 import java.io.ByteArrayOutputStream;
42 import java.io.IOException;
43 import java.io.ObjectInputStream;
44 import java.io.ObjectOutputStream;
45 import java.nio.ByteBuffer;
46 import java.time.Duration;
47 import java.time.Instant;
48 import java.util.Arrays;
49 import java.util.Date;
50 import java.util.HashSet;
51 import java.util.Set;
52 import java.util.zip.GZIPInputStream;
53 import java.util.zip.GZIPOutputStream;
54
55 import org.onap.music.eelf.logging.EELFLoggerDelegate;
56 import org.onap.portalapp.music.conf.MusicSession;
57
58 import com.datastax.driver.core.ResultSet;
59 import com.datastax.driver.core.Row;
60
61 public class MusicUtil {
62         private static final Set<String> sessionAttrNameSet = new HashSet<>(Arrays.asList("CREATION_TIME", "LAST_ACCESS_TIME","MAX_INACTIVE_INTERVAL","EXPIRY_TIME","PRINCIPAL_NAME"));
63
64         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
65         private static String atomicPut = MusicProperties.getProperty(MusicProperties.MUSIC_ATOMIC_PUT);
66         private static String atomicGet = MusicProperties.getProperty(MusicProperties.MUSIC_ATOMIC_GET);
67         private static String cached = MusicProperties.getProperty(MusicProperties.MUSIC_CACHE);
68         private static String cleanUpFreq = MusicProperties.getProperty(MusicProperties.MUSIC_CLEAN_UP_FREQUENCY);
69         private static String musicSerializeCompress = MusicProperties.getProperty(MusicProperties.MUSIC_SERIALIZE_COMPRESS);
70         private static String musicEnable = MusicProperties.getProperty(MusicProperties.MUSIC_ENABLE);
71         private static final int MILLIS_IN_HOUR = 3600000; 
72
73         public static boolean isSessionMetaAttr(String key){
74                 return sessionAttrNameSet.contains(key);
75         }
76
77         public static <T> T musicRestResponseDataParsing(ResultSet rs, String attributeName) throws Exception{
78                 logger.debug(EELFLoggerDelegate.debugLogger, "musicRestResponseDataParsing: start");
79                 Row row = rs.one();
80                 if(!sessionAttrNameSet.contains(attributeName)){
81                         if(row!=null)
82                                 return MusicUtil.musicDeserialize(row.getBytes("attribute_bytes"));
83                 }else{
84                         return (T) row.getString(attributeName);
85                 }
86                 return null;
87         }
88
89         public static <T> T musicDeserialize (ByteBuffer byteBuf) throws Exception{
90                 logger.debug(EELFLoggerDelegate.debugLogger, "musicDeserialize: start");
91                 ByteArrayInputStream byteArr = new ByteArrayInputStream(byteBuf.array());
92                 ObjectInputStream ois  = null;
93                 if(isMusicSerializeCompress()){
94                         GZIPInputStream zos = new GZIPInputStream(byteArr);
95                         ois = new ObjectInputStream(zos);
96                 }else{
97                         ois = new ObjectInputStream(byteArr);           
98                 }
99                 return (T) ois.readObject();
100         }
101
102         public static ByteBuffer musicSerialize (Object value) throws Exception{
103                 logger.debug(EELFLoggerDelegate.debugLogger, "musicSerialize: start");
104                 ByteArrayOutputStream bo = new ByteArrayOutputStream();                 
105                 try {   
106                         if(isMusicSerializeCompress()){
107                                 GZIPOutputStream zos = new GZIPOutputStream(bo);
108                                 ObjectOutputStream oos = new ObjectOutputStream(zos);
109                                 oos.writeObject(value);
110                                 oos.flush();
111                                 zos.finish();
112                         }else{          
113                                 ObjectOutputStream oos = new ObjectOutputStream(bo);
114                                 oos.writeObject(value);
115                                 oos.flush();
116                         }
117                 } catch (IOException e) {
118                         String message="Failed to serialize ";
119                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
120                 }
121                 return ByteBuffer.wrap(bo.toByteArray());
122         }
123
124         public static MusicSession parseMetaData (Row row) throws Exception{
125                 logger.debug(EELFLoggerDelegate.debugLogger, "parseMetaData: start");
126
127                 if(row==null)
128                         return null;
129                 String sessionId = row.getString("primary_id");
130                 MusicSession musicSession = new MusicSession(sessionId);
131                 musicSession.setCreationTime(Instant.parse(row.getString("creation_time")));
132                 musicSession.setLastAccessedTime(Instant.parse(row.getString("last_access_time")));
133                 musicSession.setMaxInactiveInterval(Duration.parse(row.getString("max_inactive_interval")));
134                 return musicSession;
135         }
136         
137         public static Set<String> getMusicExcludedAPI(){
138                 Set<String> excludedApiSet = new HashSet<>();
139                 String musicExcludedApi = MusicProperties.getProperty(MusicProperties.MUSIC_EXCLUDE_API);
140                 String[] musicExcludedApiArray = musicExcludedApi.split(",");
141                 if(musicExcludedApiArray.length>0){
142                         for(String str : musicExcludedApiArray){
143                                 excludedApiSet.add(str.trim());
144                         }
145                 }
146                 return excludedApiSet;
147         }
148         
149         public static boolean isExcludedApi(String api){
150                 Set<String> excludedApiSet = getMusicExcludedAPI();
151                 for(String str: excludedApiSet){
152                         if(api.matches(str))
153                                 return true;
154                 }
155                 return false;
156         }
157
158         
159         public static boolean isMusicSerializeCompress(){
160                 if(musicSerializeCompress==null){
161                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_SERIALIZE_COMPRESS +" fall back to eventual put");
162                         return false;
163                 }
164                 return musicSerializeCompress.trim().equalsIgnoreCase("true");
165         }
166
167         public static boolean isAtomicPut(){
168                 if(atomicPut==null){
169                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_ATOMIC_PUT +" fall back to eventual put");
170                         return false;
171                 }
172                 return atomicPut.trim().equalsIgnoreCase("true");
173         }
174
175         public static boolean isAtomicGet(){
176                 if(atomicGet==null){
177                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_ATOMIC_GET +" fall back to eventual get");
178                         return false;
179                 }
180                 return atomicGet.trim().equalsIgnoreCase("true");
181         }
182
183         public static boolean isCached(){
184                 if(cached==null){
185                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_CACHE +" fall back to non cache");
186                         return false;
187                 }
188                 return cached.trim().equalsIgnoreCase("true");
189         }
190         
191         public static int convertHoursToMillSec(int hour){
192                 return hour* MILLIS_IN_HOUR;
193         }
194         
195         public static boolean cleanUp(){
196                 Date lastCleanUpDate = MusicCleanUp.getInstance().getLastCleanUpTime();
197                 if(lastCleanUpDate==null)
198                         return false;
199                 else{
200                         int cleanUpDurationMili = convertHoursToMillSec(Integer.valueOf(cleanUpFreq));
201                         Date currentTime = new Date();
202                         long diffInMillies = Math.abs(currentTime.getTime() - lastCleanUpDate.getTime());
203                         if(diffInMillies > cleanUpDurationMili){
204                                 MusicCleanUp.getInstance().updateLastCleanUpTimeToCurrent();
205                                 return true;
206                         }
207                         else 
208                                 return false;
209                 }
210         }
211         
212         public static boolean isMusicEnable(){
213                 if(musicEnable==null)
214                         return false;
215                 if(musicEnable.equals("true"))
216                         return true;
217                 else
218                         return false;
219         }
220 }