308528d5d5f2befde59e09d88ecb6cf8330d4928
[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                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to serialize ");
119                 }
120                 return ByteBuffer.wrap(bo.toByteArray());
121         }
122
123         public static MusicSession parseMetaData (Row row) throws Exception{
124                 logger.debug(EELFLoggerDelegate.debugLogger, "parseMetaData: start");
125
126                 if(row==null)
127                         return null;
128                 String sessionId = row.getString("primary_id");
129                 MusicSession musicSession = new MusicSession(sessionId);
130                 musicSession.setCreationTime(Instant.parse(row.getString("creation_time")));
131                 musicSession.setLastAccessedTime(Instant.parse(row.getString("last_access_time")));
132                 musicSession.setMaxInactiveInterval(Duration.parse(row.getString("max_inactive_interval")));
133                 return musicSession;
134         }
135         
136         public static Set<String> getMusicExcludedAPI(){
137                 Set<String> excludedApiSet = new HashSet<>();
138                 String musicExcludedApi = MusicProperties.getProperty(MusicProperties.MUSIC_EXCLUDE_API);
139                 String[] musicExcludedApiArray = musicExcludedApi.split(",");
140                 if(musicExcludedApiArray.length>0){
141                         for(String str : musicExcludedApiArray){
142                                 excludedApiSet.add(str.trim());
143                         }
144                 }
145                 return excludedApiSet;
146         }
147         
148         public static boolean isExcludedApi(String api){
149                 Set<String> excludedApiSet = getMusicExcludedAPI();
150                 for(String str: excludedApiSet){
151                         if(api.matches(str))
152                                 return true;
153                 }
154                 return false;
155         }
156
157         
158         public static boolean isMusicSerializeCompress(){
159                 if(musicSerializeCompress==null){
160                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_SERIALIZE_COMPRESS +" fall back to eventual put");
161                         return false;
162                 }
163                 return musicSerializeCompress.trim().equalsIgnoreCase("true");
164         }
165
166         public static boolean isAtomicPut(){
167                 if(atomicPut==null){
168                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_ATOMIC_PUT +" fall back to eventual put");
169                         return false;
170                 }
171                 return atomicPut.trim().equalsIgnoreCase("true");
172         }
173
174         public static boolean isAtomicGet(){
175                 if(atomicGet==null){
176                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_ATOMIC_GET +" fall back to eventual get");
177                         return false;
178                 }
179                 return atomicGet.trim().equalsIgnoreCase("true");
180         }
181
182         public static boolean isCached(){
183                 if(cached==null){
184                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_CACHE +" fall back to non cache");
185                         return false;
186                 }
187                 return cached.trim().equalsIgnoreCase("true");
188         }
189         
190         public static int convertHoursToMillSec(int hour){
191                 return hour* MILLIS_IN_HOUR;
192         }
193         
194         public static boolean cleanUp(){
195                 Date lastCleanUpDate = MusicCleanUp.getInstance().getLastCleanUpTime();
196                 if(lastCleanUpDate==null)
197                         return false;
198                 else{
199                         int cleanUpDurationMili = convertHoursToMillSec(Integer.valueOf(cleanUpFreq));
200                         Date currentTime = new Date();
201                         long diffInMillies = Math.abs(currentTime.getTime() - lastCleanUpDate.getTime());
202                         if(diffInMillies > cleanUpDurationMili){
203                                 MusicCleanUp.getInstance().updateLastCleanUpTimeToCurrent();
204                                 return true;
205                         }
206                         else 
207                                 return false;
208                 }
209         }
210         
211         public static boolean isMusicEnable(){
212                 if(musicEnable==null)
213                         return false;
214                 if(musicEnable.equals("true"))
215                         return true;
216                 else
217                         return false;
218         }
219 }